text:
Q: Get selected images from DKAssests Using DKImagePickerController from selecting multiple images and videos from gallery. But only able to select images and videos from gallery, yet not able to get selected images from DKAssets and save to array. Spent more than a day.
Below is the code trying:
let pickerController = DKImagePickerController()

        pickerController.assetType = DKImagePickerControllerAssetType.AllAssets
        pickerController.allowsLandscape = false
        pickerController.allowMultipleTypes = true
        pickerController.sourceType = DKImagePickerControllerSourceType.Both
        pickerController.singleSelect = false

        // Clear all the selected assets if you used the picker controller as a single instance.
        //      pickerController.defaultSelectedAssets = nil

        pickerController.defaultSelectedAssets = self.assets

        pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in
            print("didSelectAssets")

    }
    self.presentViewController(pickerController, animated: true) {}

Please guide, thanks ion advance.

A: Try this function. it worked for me.
func showImagePickerWithAssetType
    (
    assetType: DKImagePickerControllerAssetType,
    allowMultipleType: Bool,
    sourceType: DKImagePickerControllerSourceType = [.Camera, .Photo],
    allowsLandscape: Bool,
    singleSelect: Bool) {

        let pickerController = DKImagePickerController()
        pickerController.assetType = assetType
        pickerController.allowsLandscape = allowsLandscape
        pickerController.allowMultipleTypes = allowMultipleType
        pickerController.sourceType = sourceType
        pickerController.singleSelect = singleSelect
        //          pickerController.showsCancelButton = true
        //          pickerController.showsEmptyAlbums = false
        //          pickerController.defaultAssetGroup = PHAssetCollectionSubtype.SmartAlbumFavorites

        // Clear all the selected assets if you used the picker controller as a single instance.
        //          pickerController.defaultSelectedAssets = nil
        pickerController.defaultSelectedAssets = self.assets

        pickerController.didSelectAssets = { (assets: [DKAsset]) in
            print("didSelectAssets")

            self.assets = assets
            if assets.count > 0 {
                self.cameramoment.titleLabel?.textColor = UIColor.redColor()
                //self.cameramoment.titleLabel?.alpha = 50
                //self.cameramoment.titleLabel?.textColor = UIColor(red: 0.0, green: 184.0, blue: 214.0, alpha: 1.0)
            }
            else {
                //self.cameramoment.setImage( UIImage (named: "grey_camera_32x32"), forState: .Normal)
              self.cameramoment.titleLabel?.textColor = UIColor.lightGrayColor()
              self.cameramoment.titleLabel?.alpha = 50
            }
            self.collectionview.reloadData()

        }

        if UI_USER_INTERFACE_IDIOM() == .Pad {
            pickerController.modalPresentationStyle = .FormSheet;
        }

        self.presentViewController(pickerController, animated: true) {}
}

Call this function like this.
self.showImagePickerWithAssetType(DKImagePickerControllerAssetType.AllPhotos, allowMultipleType: true, allowsLandscape: true, singleSelect: false)

self.assets is defines as,
var assets: [DKAsset] = []

To get the image from DKAsset. try this.
for asset in assets {
  asset.fetchImageWithSize(requiredImageSize, completeBlock: { image, info in
            if let img = image {
              let fixOrientationImage=img.fixOrientation()
              cell.postmomentimage1.image = fixOrientationImage
            }
    })
}

A: import Foundation
import UIKit
import DKImagePickerController

class addPhotoViewController: UIViewController {

var assets:[DKAsset] = []
var pickerController: DKImagePickerController!

@IBOutlet weak var selectedPhoto: UIImageView!

@IBAction func sec(_ sender: Any) {

    let pickerController = DKImagePickerController()
    pickerController.singleSelect = true

    pickerController.didSelectAssets = { (assets: [DKAsset]) in
        print("didSelectAssets")
        print(assets)
        for asset in assets {
            asset.fetchOriginalImage(true, completeBlock: { image, info in
                if let img = image {
                    let fixOrientationImage=img
                    print(fixOrientationImage)
                    print(info)
                    self.selectedPhoto.image = fixOrientationImage
                }
            })
        }
    }
    self.present(pickerController, animated: true) {}
   }
}


text:
Q: how to use ajax in custom page and post in wordpress I have created a custom pages whit country and city dropdown. I want to use ajax to select city to according to the country selection.
I tried to add ajax call directly in my page but it doesnt work
I dont know how to fix it.
Please help me, your help will appreciated heartly.
my link is as under
my site

A: You need to use wp_ajax_(action) hook in order to use ajax in your pages.
<?php

    add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
    add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );

    function prefix_ajax_add_foobar() {
        // Handle request then generate response using WP_Ajax_Response
    }
?>
<script>

    jQuery.post(
        '<?php echo admin_url('admin-ajax.php') ?>',
        {
            'action': 'add_foobar',
            'data':   'foobarid'
        },
        function(response){
            alert('The server responded: ' + response);
        }
    );
    </script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Encode HEVC/H.265/HDR Video for YouTube from 10bit Pro-Res using FFmpeg I want to have an HDR YouTube video published, my source file is either an Apple ProRes or DNxHR using a chroma subsamplig 4:4:4 or full RGB, both 10bit, so the original source file has all what is needed in order to be encoded into a 10bit 4:2:0 H.265/HEVC (HDR).
I have followed some answers listed here, reviewed lots of different approaches, tried out many different commands without success, colors aren't right when using only FFmpeg, to much red, when using only Adobe to encode into H.264 with the recommended settings on their support page, the results is darker, here are the commands I've using:
I have tried this:
ffmpeg \
-i input.mov \
-c:v libx265 \
-tag:v hvc1 \
-crf 21 \
-preset fast \
-pix_fmt yuv420p10le \
-x265-params "colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:master-display=G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,10):max-cll=1000,400" \
-c:a libfdk_aac \
-b:a 128k \
-ac 2 \
-ar 44100 \
-movflags +faststart \
output.mp4

And this:
ffmpeg \
-y \
-hide_banner \
-i input.mov \
-pix_fmt yuv420p10le \
-vf "scale=out_color_matrix=bt2020:out_h_chr_pos=0:out_v_chr_pos=0,format=yuv420p10" \
-c:v libx265 \
-tag:v hvc1 \
-crf 21 \
-preset fast \
-x265-params 'crf=12:colorprim=bt2020:transfer=smpte-st-2084:colormatrix=bt2020nc:master-display="G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,1)":max-cll="1000,400"' \
-c:a libfdk_aac \
-b:a 128k \
-ac 2 \
-ar 44100 \
-movflags +faststart \
output.mp4

I have also tried using MKVToolNix in order to insert the metadata into the encoded HEVC/H.265 file with the following command:
/Applications/MKVToolNix-9.7.1.app/Contents/MacOS/mkvmerge \
-o output.mkv \
--colour-matrix 0:9 \
--colour-range 0:1 \
--colour-transfer-characteristics 0:16 \
--colour-primaries 0:9 \
--max-content-light 0:1000 \
--max-frame-light 0:300 \
--max-luminance 0:1000 \
--min-luminance 0:0.01 \
--chromaticity-coordinates 0:0.68,0.32,0.265,0.690,0.15,0.06 \
--white-colour-coordinates 0:0.3127,0.3290 \
input.mp4

But the result is the same and YouTube don't recognize the file as an HDR file, it does only with the first FFmpeg command and with the file encoded with Adobe Premiere, but the colors don't look well, so, maybe I'm getting some concept wrong, thanks for your help.


text:
Q: How to download text file from website using Python? I need to write a function that downloads and stores the today's list of pre-release domains .txt file from
 http://www.namejet.com/pages/downloads.aspx.
So as today is 8th of October you want to get the file "Monday, October 08, 2012".
Tried with requests but didn't work.
I'm having trouble because the file is not stored on a fixed URL but is hidden behind some Javascript.

A: This one's a little tricky as you're dealing with ASP.NET's postback system. If this is for anything other than a personal script, I'd be wary as you're effectively not only using another site's data, but reverse engineering their software as well (however, IANAL and have no idea about legalities around these issues in web systems).
What you're going to want to do is check the POST data (using Firebug, Chrome developer tools, etc) and look for the __EVENTTARGET and __VIEWSTATE attributes of the form object. You'll have to decode the __VIEWSTATE to be readable (check out http://ignatu.co.uk/ViewStateDecoder.aspx). From there, I think you should be able to figure out how to get the data you're looking for.
From Python, it's as easy as:
from urllib2 import urlopen
from urllib import urlencode

data = urlopen('url', urlencode({
    '__VIEWSTATE': 'foo',
    '__EVENTTARGET': 'bar',
})).read()

A: Actually you get text file in response to a POST request with several base64-encoded request parameters. Feel free to play with it
use Firebug or any other debug tool to see the POST content and parameters


text:
Q: Bootstrap | Placing Images/Spans on top of images, and still be responsive? I have been trying to add a Notification and Message button on top of a "profile picture" on my website, that i am having a little fun styling. Now i don't seem to be able to figure out how to place this span with a glyphicon near it, and still have it be responsive.
Here is a picture of what im kinda going for: PICTURE
Here is a picture of what i have at the moment: PICTURE2
This is the current setup:
HTML

CSS
#message-button{
position: relative;
border-radius: 50%;
border: 5px solid green;
background-color: green;

}
I simply have no clue how i would go about moving the glyphicon-comment span up to the image, and still make it responsive.

A: It was easier for me build it in one file then typing dozens of lines of explaination. The point is to let bootstrap do all the work for you in terms of aligning and centering.
I simply used one css class col-xs-12 for the profile image, then you simply start a new bootstrap row with 2 divcontainers with the class col-xs-6 col-sm-6 col-md-6 col-lg-6. That gives you 2 equal boxes at all times. The rest, styling the buttons and the icons is an easy job.
I hope this helps you to understand the concept, you can copy/paste this code into one HTML file and see the result.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Responsive Profile Image with Button</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                <button class="profile-buttons" id="message-button">

                    3
                </button>

                <button class="profile-buttons" id="comment-button">

                    2
                </button>

In order to change the distance / width of the buttons on different devices, just change the width class of the single groups to get them closer or wider. *-offset-* is also very helpful.
You can also use the class img-responsive to give your images the width:100%;height:auto properties for responsiveness.


text:
Q: Port forward from computer (not router management)? Since applications can set up port forwarding rules in my home network's router, I'm assuming I can as well via a command or something of that sort, correct?
Here's my dilemma: I have a Belkin wireless router that loves to "disappear". I'm not sure why, but the remote management of it seems to stop after less than a day pretty consistently. The router will continue to function, but I won't be able to manage it.
I need to forward a particular port to a machine on this network, but I can't power-cycle the router (typically the only way to get the management address (192.168.2.1) to respond again).
So back to the original question; can I set a forward like applications do? Or for that matter, is there an application that I can get to allow me to manage that from the (Windows) PC?
Thanks so much in advance, and all apologies knowing nothing about networking.

A: If it's failing like that, there's a good chance the router is going flaky...my response would be to replace the router.
If I'm reading your question correctly, you can't forwards ports on the computer from the computer. The router is what mediates the connections between the Internet and your internal systems. Otherwise you'd be in a lot more trouble with what malware can and can't do to your router.
The real answer is to get a new router and replace the one going flaky. Home routers are notorious for dying in a short amount of time, at least at my house. I used to have the integrated WAP/Router units (less than ~100 to $150) die within a year or two and replace them.
Anything else is a kludge that's waiting for it to finish dying on you.

A: UPnP Port Works saves the day, and yeah... I'll get a new router.


text:
Q: One way repeated measures ANCOVA? Hi  Is it possible to run a repeated measures one way ANCOVA?
My data is from a cross-over design study, each subject followed 3 different diets.
I can see from a repeated measures ANOVA that there is an effect of the diets on sweat rate (continuous variable). But i think this is influenced by resting core temperature. So i have this measured also across the 3 different conditions in each individual. Can i run a one-way repeated measures ANCOVA to account for the differences in resting core temperature?
I'm running the analysis in SPSS as the 3 diets as the within-subject variable, and sweat rate as the measure, with the 3 core temperatures in as  Covariates.
If the test of within-subject effects is p<0.05 for diet (sphericity assumed) (as it was with the one way repeated measures ANOVA).
The 3 different diet*resting temperature within subject effects are all p>0.05.
Therefore the resting temperature is not impacting sweat rate...?
Or i actually think this should really be a 2 way repeated measures anova?
sorry for the basic questions, I'm new to this.


text:
Q: ¿Por qué no reconoce los paquetes previamente instalados un ambiente virtual de python? Buen día a todos. Me surgió un inconveniente al trabajar con un ambiente virtual de Python. Espero me puedan apoyar.
Todo es correcto al activar el ambiente virtual  con el comando en terminal "venv\Scripts\activate.bat" .
A la extrema izquierda se confirma que esta activado el ambiente virtual con "(venv)". A la hora de explorar los paquetes instalados con el comando "pip list" o "pip freeze" me lanza que solo hay dos paquetes, que son pip y setuptools.
Pero al explorar la carpeta venv/Lib/site-packages me aparecen todos los paquetes que había instalado con anterioridad.
Hice la prueba de instalar un paquete cualquiera de nuevo en el ambiente y me lo instala globalmente en python.
Alguien sabe por que esta sucediendo esto? He intentado acceder a otros ambientes virtuales de otros proyectos en donde si funciona correctamente todo.
Gracias de antemano.

A: El ambiente virtual te hace una copia en limpio del intérprete de Python. Esto es para crear un lugar dónde los paquetes que instales estén ajenos del sistema.
Uno de los casos de uso para el uso de los venv es cuando tienes varios proyectos con diferentes versiones de una misma librería, por lo que no sería conveniente que cuando crearas un nuevo ambiente virtual te copiara a ese entorno todas las librerías que tienes.
Algo interesante a recalcar es que cuando instales las librerías, si ya la tienes instaladas en el sistema pues lo usa como caché


text:
Q: How can I find the background color code for the "LaunchScreen.storyboard"? I changed the background color of the LaunchScreen.storyboard, but the color does not appear as it is supposed to, So I need to divide by 255. Where can I find the code for the backgroundColor of LaunchScreen.storyboard view?

A: The only way you can do this is through Interface Builder.
The LaunchScreen.storyboard does not accept code.
Sometimes, when you change the Launchscreen, for a bug, it is not updated in real time. Reboot the device you can solve.
Xcode Interface Builder

A: It's hard to tell what you are asking. The LaunchScreen.storyboard storyboard is displayed before your app code is run, so you can't write app code to alter that storyboard.


text:
Q: C# Error on application startup - could not load file or assembly some users (i would say it is ~10%) exeperiences a problem while trying to run my application written in C# (.NET 4.0) - at application startup such error occures:
Could not load file or assembly 'lua51.dll'. Such module could not be found.

- It is translation, so in ENG version it could be similar.
The problem is that most of users don't experience this problem, and lua51.dll is present in program's directory. What could be the reason of this error?
I have set Platform: x86 in my project->bulid options, error occurs.

A: This is a common problem, too many programmers just copy the DLL without realizing that lua51.dll has itself dependent DLLs that need to be installed as well.  The error message from Windows is sadly unhelpful, it doesn't report the true cause of the problem.  An event in the Applciation log does, but not enough users look at it.
Unfortunately this doesn't go wrong often enough, lots of machines already have the dependent DLLs available.  This is however an accident, you cannot rely on it.  Those odds get lower and lower as well, the dependency is getting old.
You'll need to read the Install Notes to know what is required:

Lua for Windows and it's modules all depend on the MSVC++ 2005 runtime library. Lua for Windows install will automatically download this runtime and install it for you if you don't have runtime installed on your computer. The runtime is contained in the file vcredist_x86.exe

So either rely on the Lua installer or get the vcredist installed yourself.


text:
Q: Best practice for Decorator design pattern In the right place Decorator design pattern shines, but i noticed in many applications few mistakes made while using decorator.
an exemple (using java.io) which demonstrate the problem with bad using of Decorator.
public OutputStream foo(...){
    return new BufferedOutputStream(...);
}

The problem with this method, it return a BufferedOutputStream as OutputStream, so a user may decorate again this object by BufferedOutputStream (he don't know that the method return a buffered stream), so here we got double buffering for free (worsing more the performance for nothing).
another exemple :
public void foo(OutputStream os){
    BufferedOutputStream bos = new BufferedOutputStream(is);
    ...
}

Here another exemple, the user may supply BufferedOutputStream to foo which already decorate it for internal use, the user may want to increase performance by providing a buffered stream, but in reality he's making it more worse, its not his fault, he don't know what the method do inside (Black box).
So anyone can tell me what is the best practices for using Decorator design pattern, not only with java.io but with general use for Decorator?


text:
Q: Can i create nested tables on MySql? for example,access example db, every student record have a nested table about guardians.
http://img101.imageshack.us/img101/9881/53882937.jpg

A: No. Something like that is almost always done as a single mapping table for all students, with a foreign key column pointing to the student table to specify which student a particular row relates to.
You then just filter the table to match a given student, and present that list without a student column, in the UI. It looks like a separate table to the user, but that's not actually how it's stored.
(If you did create a separate guardians table for each student, you'd make it impossible to do queries like 'find students for a particular guardian'.)


text:
Q: What's the cmd / batch alternative to the deprecated wmic? I'm aware of wmic being deprecated as of 2012 and I now typically use PowerShell anyway, so had moved away from it already.
However, I frequently encounter cases where I need to work within batch files and do not have the option of migrating the solution to PowerShell.
My question is this: with wmic deprecated, what is the recommended alternative for continued access to the Windows Management Instrumentation from the command prompt and from batch files?
The best I can think of currently is something along the lines of:
powershell -command "(Get-CimInstance Win32_Processor) | select *" | some_other_program.exe

(this example to get processor attributes)
But one major downside of that is that errorlevels and the environment are no longer accessible. That is, the powershell command completes successfully, even if the command does not). And changes made to the environment in the powershell command do not propagate to the batch file.
Any suggestions on how to specifically address those issues, or on better alternatives to calling powershell from the batch for access to WMI are welcome, but specifically I'd like to know how to run a powershell command and access the results other than the standard out.

A:
But one major downside of that is that errorlevels and the environment are no longer accessible.

The simplest way to make a PowerShell command invoked via the PowerShell CLI (powershell.exe in Windows PowerShell, pwsh in PowerShell (Core) 7+) report a nonzero exit code is to throw a script-terminating (thread-terminating) error, which results in error code 1 - which your batch file can test for:
@echo off

:: # Simulate a failing CIM call
powershell -c "$ErrorActionPreference='Stop'; Get-CimInstance Win32_NoSuchClass"

:: # Exit, if the PowerShell command failed.
if ERRORLEVEL 1 echo Error: Get-CimInstance failed>&2 & exit /b %ERRORLEVEL%

echo Moving on...

$ErrorActionPreference='Stop' at the start of the command ensures that any subsequent error becomes a script-terminating one.
To ignore non-terminating errors selectively, use -ErrorAction Ignore command-individually.
If no error occurs, the exit code is implicitly 0.
PowerShell's error handling is bewilderingly complex; see this GitHub issue for a comprehensive summary.
Note:

*

*Native PowerShell commands such as Get-CimInstance do not set exit codes; the best you can do is to map errors to exit code 1, and success to exit code 0.

*If you call external programs from PowerShell, their exit code is reflected in automatic variable $LASTEXITCODE; you can use exit $LASTEXITCODE to pass that exit code through from your PowerShell command string; however, you can generally simply call external programs from your batch file directly - no detour via PowerShell needed.

And changes made to the environment in the powershell command do not propagate to the batch file.

True, the PowerShell command invariably runs in a child process, whose environment has no impact on the calling process.
Generally:

*

*Capture output from the PowerShell command in a file or process it in memory with a for /f loop (see example below) - unless passing the output through is sufficient.

*If you truly need to modify the calling batch file's environment, have the PowerShell command output the data for those modifications, and apply them in the batch file.

*

*E.g., if you want your PowerShell command to set environment variables, make it output <name>=<value> string pairs that the batch file can use to set these variables.

An example of tailoring output from a PowerShell command for parsing in a batch file with for /f; note that the quoting can get tricky:
@echo off

:: # Get the .Name and .MaxClockSpeed property values from the Win32_Processor instance.
for /f "tokens=1,* delims==" %%i in ('powershell -c "$ErrorActionPreference='Stop'; Get-CimInstance Win32_Processor | %% { foreach ($n in 'Name', 'MaxClockSpeed') { \""$n=$($_.$n)\"" } }"') do (
  echo [%%i]=[%%j]
)

:: # Exit, if the PowerShell command failed.
if ERRORLEVEL 1 echo Error: Get-CimInstance failed>&2 & exit /b %ERRORLEVEL%

The above yields something like:
[Name]=[Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz]
[MaxClockSpeed]=[2304]


text:
Q: Simple BMI calculation with two additional fields So I have the following form which calculates the users BMI and redirects the user to a certain page depending on the result:
HTML
<form name="bmiForm">

Your Weight(kg): <input type="text" name="weight">

Your Height(cm): <input type="text" name="height">

   <input type="button" value="Calculate BMI" onClick="calculateBmi()">

Your BMI: <input type="text" name="bmi" size="10">

</form>

JavaScript

It works an absolute treat. However, I now need two more inputs.

*

*Have you tried diet and exercise?

*Have you ever had diabetes?

So I would obviously need a select option for "Yes" and "No" for each and added functionality within the if statement.
I tried adding:
var diabetes = document.bmiForm.diabetes.value

To the script and then another condition within the if statement, but no luck.
Where can I go from here? Any suggestions for accomplishing the above.
Any help would be greatly appreciated.

A: For checkbox you have to do like this :
 if (document.getElementById('diabetes').checked) {    //here 'diabetes' is id of checkbox
        alert("checked");
    }
 else { alert("not checked") }

and for dropdown do as :
var e = document.getElementById("diabetes");
var selectvalue= e.options[e.selectedIndex].value;  //you can get selected value with this
var selecttext= e.options[e.selectedIndex].text;    //you can get selected text with this


text:
Q: How to submit new github issue through access token using rust I'm trying to write a rust script that submits an issue with given name, label and body to a specific repository using github access token. I've found github-rs and octocrab, but can't figure out how this exact function works.
UPDATE
Here's the code using rust-curl:
use std::io::Read;
use curl::easy::{Easy, List};

fn main() {
    let mut data = r#"{
        "title": "Found a bug",
        "body": "I'm having a problem with this.",
        "labels": [
          "bug"
        ]
      }"#.as_bytes();
    let mut easy = Easy::new();
    easy.url("https://api.github.com").unwrap();

    let mut list = List::new();
    list.append("Authorization: token TOKEN_HERE").unwrap();
    easy.http_headers(list).unwrap();
    easy.perform().unwrap();
    easy.post(true).unwrap();
    easy.post_field_size(data.len() as u64).unwrap();
    let mut transfer = easy.transfer();
    transfer.read_function(|buf| {
        Ok(data.read(buf).unwrap_or(0))
    }).unwrap();
    transfer.perform().unwrap();
}

A: If those librairies don't include an easy way, you could fall back to alexcrichton/curl-rust
It does let you add custom headers, including the "Authorization: token MY_TOKEN_NUMBERS" you can see used here, which will authenticate you.
From there, your curl call (in rust) can use the GitHub API "create issue" endpoint:
POST /repos/:owner/:repo/issues

with the data:
{
  "title": "Found a bug",
  "body": "I'm having a problem with this.",
  "assignees": [
    "octocat"
  ],
  "milestone": 1,
  "labels": [
    "bug"
  ]
}


text:
Q: Error connecting to exchange server remotely via PowerShell I am trying to connect to my Exchange server remotely using PowerShell. The Exchange server is on its own dedicated Exchange forest. I am trying to open the connection on a forest that does not have the Exchange server.
This is what I have in my PowerShell script:
$powershell_url = "http://exhange_server_url.com/PowerShell/"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $powershell_url -Authentication Kerberos

When I run this script, I get this error:

[exhange_server_url.com] Connecting to
  remote server failed with the following error message : The WinRM
  client cannot process the request. The authentication mechanism
  requested by the client is not supported by  the server or unencrypted
  traffic is disabled in the service configuration. Verify the
  unencrypted traffic setting in the service configuration or specify
  one of the authentication mechanisms supported by the server.  To use
  Kerberos, sp ecify the computer name as the remote destination. Also
  verify that the client computer and the destination computer ar e
  joined to a domain. To use Basic, specify the computer name as the
  remote destination, specify Basic authentication a nd provide user
  name and password. Possible authentication mechanisms reported by
  server: For more information, see the  about_Remote_Troubleshooting
  Help topic.
      + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [],
  PSRemotingTransportExc    eption
      + FullyQualifiedErrorId : PSSessionOpenFailed

How do I resolve this issue?

A: Did you make sure your account is enabled for Remote Exchange?
Here is a site for more information:Technet Article

A: This is what I ended up doing:
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\Administrator","password"
#connect with remote cas server
$powershell_url = "http://cas-server/PowerShell/"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $powershell_url  -credential $credentials -Authentication Kerberos


text:
Q: How to check whether my PC supports PCI Express I'm trying to figure out whether my system supports PCI Express without opening up the box. lspci doesn't mention "Express" or "PCI-e" anywhere, but dmesg reports that a "PCI Express Hot Plug Controller Driver" is in use.

A: Easiest thing you can do is restart the machine and write down the model number then Google it and look up the specification.
Simple, but works!

A: If you want the motherboard make and model so you can google it, but you don't want to reboot, you should be able to get that info from /sys/class/dmi/id/board_vendor and /sys/class/dmi/id/board_name

A: One thing to note is if your machine has a 1x, 2x, 4x, 8x, 16x PCI-E port and then buy the appropriate hardware.


text:
Q: Opencart website not working after updating modifications my website does not work anymore after updating my modifications in Open Cart. I am stuck and don't know what to do. In the console there are several errors. This is my header of my OpenCart website. I don't know where the problem is coming from but my whole CSS is gone.
<!DOCTYPE html>

<html dir="<?php echo $direction; ?>" lang="<?php echo $lang; ?>">

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php echo $title; ?></title>
<base href="<?php echo $base; ?>" />
<?php if ($description) { ?>
<meta name="description" content="<?php echo $description; ?>" />
<?php } ?>
<?php if ($keywords) { ?>
<meta name="keywords" content= "<?php echo $keywords; ?>" />
<?php } ?>

<link href="catalog/view/javascript/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />

<link href="catalog/view/javascript/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="//fonts.googleapis.com/css?family=Open+Sans:400,400i,300,700" rel="stylesheet" type="text/css" />
<link href="catalog/view/theme/default/stylesheet/stylesheet.css" rel="stylesheet">
<?php foreach ($styles as $style) { ?>
<link href="<?php echo $style['href']; ?>" type="text/css" rel="<?php echo $style['rel']; ?>" media="<?php echo $style['media']; ?>" />
<?php } ?>

<?php foreach ($links as $link) { ?>
<link href="<?php echo $link['href']; ?>" rel="<?php echo $link['rel']; ?>" />
<?php } ?>
<?php foreach ($scripts as $script) { ?>

<?php } ?>
<?php foreach ($analytics as $analytic) { ?>
<?php echo $analytic; ?>
<?php } ?>

<body class="<?php echo $class; ?>">

    <?php echo $currency; ?>
    <?php echo $language; ?>

<a href="<?php echo $contact; ?>"> <?php echo $telephone; ?>

<a href="<?php echo $account; ?>" title="<?php echo $text_account; ?>" class="dropdown-toggle" data-toggle="dropdown"> <?php echo $text_account; ?>

            <?php if ($logged) { ?>

<a href="<?php echo $account; ?>"><?php echo $text_account; ?>

<a href="<?php echo $order; ?>"><?php echo $text_order; ?>

<a href="<?php echo $transaction; ?>"><?php echo $text_transaction; ?>

<a href="<?php echo $download; ?>"><?php echo $text_download; ?>

<a href="<?php echo $logout; ?>"><?php echo $text_logout; ?>

            <?php } else { ?>

<a href="<?php echo $register; ?>"><?php echo $text_register; ?>

<a href="<?php echo $login; ?>"><?php echo $text_login; ?>

            <?php } ?>

<a href="<?php echo $wishlist; ?>" id="wishlist-total" title="<?php echo $text_wishlist; ?>"> <?php echo $text_wishlist; ?>

<a href="<?php echo $shopping_cart; ?>" title="<?php echo $text_shopping_cart; ?>"> <?php echo $text_shopping_cart; ?>

<a href="<?php echo $checkout; ?>" title="<?php echo $text_checkout; ?>"> <?php echo $text_checkout; ?>

          <?php if ($logo) { ?>
          <a href="<?php echo $home; ?>"><img src="<?php echo $logo; ?>" title="<?php echo $name; ?>" alt="<?php echo $name; ?>" class="img-responsive" />
          <?php } else { ?>

<a href="<?php echo $home; ?>"><?php echo $name; ?>

          <?php } ?>

<?php echo $search; ?>

<?php echo $cart; ?>

<?php if ($categories) { ?>

<?php echo $text_category; ?>
      <button type="button" class="btn btn-navbar navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"></button>

        <?php foreach ($categories as $category) { ?>
        <?php if ($category['children']) { ?>

<a href="<?php echo $category['href']; ?>" class="dropdown-toggle" data-toggle="dropdown"><?php echo $category['name']; ?>

              <?php foreach (array_chunk($category['children'], ceil(count($category['children']) / $category['column'])) as $children) { ?>

                <?php foreach ($children as $child) { ?>

<a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?>

                <?php } ?>

              <?php } ?>

            <a href="<?php echo $category['href']; ?>" class="see-all"><?php echo $text_all; ?> <?php echo $category['name']; ?>

        <?php } else { ?>

<a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?>

        <?php } ?>
        <?php } ?>

<?php } ?>

Here is the URL to the website because there are several errors:
http://tramag.nl


text:
Q: Is it okay to use the scope of one controller from another using a service? I was told if you need to share between controllers you should use a service. I have controller A, which is a list of news websites, and controller B which is a list of articles on the sites from controller A. Controller B contains the list of articles and an iframe to display the articles. But when you click on controller A it should fade out the iframe and fade in the list. In order to accomplish this I give Controller B's scope to a service that is injected into both controller A and controller B. My question is whether or not it's okay to do that.
Basically, I do this:
app.factory("sharedService", function () {
    var $scope = null;
    return {
        SetScope: function (scope) {
            $scope = scope;
        },
        ControllerB_Action: function () {
            $scope.doSomething();
        }
    };
});
app.controller("controllerA", ["$scope", "sharedService", function ($scope, sharedService) {
    $scope.onaction = function () {
        sharedService.ControllerB_Action();
    }
}]);
app.controller("controllerB", ["$scope", "sharedService", function ($scope, sharedService) {
    sharedService.SetScope($scope);
}]);

A: I would say its not a good pattern, since basically, the $scope is an Object that represents your current view or DOM-State. A controllers (and/or Link-Functions of directives) are the Glue between this state and your Application-Logic - so in my opinion, the $scope-Object should always remain inside the Controllers/Links.
Therefore if you wanna share Data between 2 Controllers, you should extract what you wanna share inside the Service, but not put the whole scope there (since it has lots of additional information that you dont need and want inside both controllers).
What you can do is simply link the data you wanna share by reference - that way, your Service will also Sync the Data between the two Scopes.

A: There's probably a world of ways of doing this, but I'll tell you what I would do:
I'd make use of event emmiters.
Disclaimer: I haven't tested this code
Assuming that Controller B is nested in Controller A:
    Controller A

    var controllerBFunction_A;
    $scope.$on('EventFromControllerB',function(data){
         controllerBFunction_A = data.sharedFunctions.controllerBFunction_A;
    });

    Controller B

    $scope.$emit('EvenFromControllerB',{
                                              sharedFunctions: [
                                                controllerBFunction_A,
                                                controllerBFunction_B,
                                                someOtherObject
                                              ]
                                            });

I think this could work. In my opinion this has the benefit of selecting what you want to share between those controllers...but probably there's a more elegant way of doing this.


text:
Q: mp3 encoder in iOS with arm64 I am using mp3 encoder in my app. I got project from Github reference: - https://github.com/rpplusplus/iOSMp3Recorder
This project working fine with armv7.But apple do not accept my app because i have removes arm64 support.
This code doesn't work with arm64.Can anyone suggest me any alternate or compatible this project for arm64.
I got this error when i add arm64
ld: warning: ignoring file /Users/ranjitsingh/Documents/Projects/LabelVoice/libmp3lame.dylib, missing required architecture x86_64 in file /Users/ranjitsingh/Documents/Projects/LabelVoice/libmp3lame.dylib (2 slices)
Undefined symbols for architecture x86_64:
  "_lame_close", referenced from:
      -[RecordViewController toMp3] in RecordViewController.o
  "_lame_encode_buffer_interleaved", referenced from:
      -[RecordViewController toMp3] in RecordViewController.o
  "_lame_encode_flush", referenced from:
      -[RecordViewController toMp3] in RecordViewController.o
  "_lame_init", referenced from:
      -[RecordViewController toMp3] in RecordViewController.o
  "_lame_init_params", referenced from:
      -[RecordViewController toMp3] in RecordViewController.o
  "_lame_set_VBR", referenced from:
      -[RecordViewController toMp3] in RecordViewController.o
  "_lame_set_in_samplerate", referenced from:
      -[RecordViewController toMp3] in RecordViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Thanks in advance.


text:
Q: tablet/handset layout structure with fragments In this article http://developer.android.com/guide/practices/tablets-and-handsets.html
we use res/layout/main.xml with one fragment for handsets and res/layout-large/main.xml with two fragments for tablets. We must check if second fragment is in the layout to define if app runs on tablet or on phone.
I have 4 layout (2 for phone and 2 for tablet):

*

*layout-port

*layout-land

*layout-sw600dp-port

*layout-sw600dp-land

I check screen orientation to define if display is in portrait or landscape mode and check if layout contains a fragment to define if it is tablet or phone.
Is there any better way to work with layouts and fragments?
Is it possible to use one layout if we have two fragments for example http://i.stack.imgur.com/FtzKs.png and if a phone display doesn't fit both of them to show only the first one?
Thanks in advance! :)

A: What you're showing there is indeed possible! That is something called a Master Detail Flow (if you're developing in Eclipse with adt, check out he new activity wizard, which provides this as a template option).
This layout is basically just two fragments inside an activity (or, now, as of android 4.2, they can be nested in another fragment as well!) that interact with each other in a certain way. To create the layouts you linked to, one would detect whether the device is a phone or a tablet, and then set the visibility of the two fragments in different situations accordingly.
You will find a number of methods for detecting screen size here, whether you want to use screen size in inches, pixels, or the manufacturers' default categories.
And properties like visibility and sizing can be set programmatically using Layout Params and its various subclasses.
In any particular case, whether you choose to use multiple layouts to support different screen sizes or to do more of it programmatically is up to you. Personally, I think that it is always a good practice to design your code modularly and then use layouts to put all the pieces together (it'll save you a lot of headaches down the line if you decide you want to change things up). But either way, supporting more devices will always require more code, and there are no two ways around that...one of the curses of android development :P


text:
Q: Find the maximum distance between two elements that don't differ by more than k Given an array arr, find the maximum abs(i-j) such that abs(arr[i] - arr[j]) <= k.
After a lot of thought, I came up with the following algorithm,
1) Create a new array of pair<arr[i], i> (say arrayIndexPairs)
2) Sort this arrayIndexPairs based on the array value (first of pair).
3) Build a segment tree on the index (second of pair) with the arrayIndexPairs so that we can answer range max queries
4) for i <- 0 to n-1
    4.1) rightIndex = Binary search the array values (first of pair) for ceil(arrayIndexPairs[i].first) in the interval [i+1, n-1]
    4.2) int maxIndex = rangeQueryForMax(i+1, rightIndex)
    4.3) result = max(result, maxIndex - i);
return result

The complexity is O(n log n) for the sort + for every element we do a binary search O(log n) + rangeQuery, O(log n). The overall time complexity is O(nlogn + n*2*logn) which is asymptotically O(nlogn).
Is the approach correct? Is is possible to formulate a linear time solution? I tried using hashmaps but find it very hard to arrive at a linear solution.

A: I came up with this:
def find_max_abs(l, k):
    for lenght_of_interval in range(len(l), 1, -1):
        for start_of_interval in range(0, len(l) - lenght_of_interval + 1):
            if abs(l[start_of_interval] - l[start_of_interval + lenght_of_interval - 1]) <= k:
                return lenght_of_interval - 1

Should work nicely, but it's not linear(worst case N²). I am interested if a linear algorithm exists

A: For the general case, your idea seems efficient.
For the case where the elements are all integers, you can do it in  Θ(n k) expected time. If k = o(log(n)), this is a saving. If k is a constant, this is linear in n.

*

*Place all your elements in a hash table mapping each element e to its position in the array i (if there is more than a single e, let each entry you place in the hash table overwrite the previous one - it doesn't matter).

*For each element e at position i, and d = -k, -(k - 1), ... 0, 1, ... k, check if e + d is in the hash table. If so, you have the position of e + d, say j, from the hash table.

*Retain the positions of the maximal distance you found in 2.

A: It seems a bit forced the definition of  "linear".
I would approach in a different way. We can notice that the function distance d is searching for the max.
So we know that there is the following combinations:
 - DIST    COUPLES       COUNT

*

*d=n-1   (a[0],a[n-1])  1

*d=n-2   (a[0],a[n-2]),    (a[1],a[n-1])    2

*...

*d=1     (a[0],a[1])...(a[n-2],a[n-1])   n-1

Since we search the maximum we are going to investigate first by the maximal distances . So we have best case O(1), worst case the sum from 1 to n-1 =(n-1)*(n/2) =O(n2).
Average I would expect better performances, since it is can be implemented very efficently.
Here the C implementation:
#include "stdio.h"
#include "stdlib.h"
#define ARRAYSIZE 10000

int find_dist(int * result, const int *array, int n,int k )
{
  int i,j,ti;
  for (i=n-1;i>0;i--)
  {
     ti=i;
     for (j=0;ti< n ; j++,ti++)
        if (abs(array[j]-array[ti])<=abs(k))
            {
                result[0]=j;
                result[1]=ti;
                return 1;
            }
   }
return 0;
}

int main()
{
  int array[ARRAYSIZE],result[2],i;
  for (i=0;i<ARRAYSIZE;i++)
    {
        array[i]=rand()%1000;
        //printf("%d ",array[i]);
    }
  if (find_dist(result,array,ARRAYSIZE,3))
    printf ("\n%d %d\n",result[0],result[1]);
  else
    printf ("No items match requirement\n");
 }


text:
Q: Alter a table which has non-unique non-clustered index to add a column I have a table named Person which already have few non-unique non-clustered index and one clustered index (based on primary key).
I have to write two queries:

*

*I need to alter the table to add column birthplace. Do I need to check any index while writing the alter table person add birthplace varchar(128) not null?

*My next requirement is I have another column named cityCode narvar(10). This I need to include in my existing non-unique, non-clustered index. How should I write my script? should I drop my index and recreate it?
Please suggest. I am able to find some related questions, but not clear about non-unique non-clustered index.

A:
alter table person add birthplace varchar(128) not null

Be aware when you specify not null without default value you will get error. It's recommended to add default value. But in case you can not consider any, then add column as nullable then update it later. At the end make it NOT NULL using below code:
alter table person Alter column birthplace varchar(128) not null

And if you want to involve new column to an existing index then use CREATE INDEX with DROP_EXISTING option. The performance is more efficient.  To do so,
generate a create index script then modify script by adding new column to the column list of index and then add this at the end of CREATE INDEX statement.
WITH (DROP_EXISTING = ON)


text:
Q: Is there a trick to editing the status of an Ad Group? According to the Facebook documentation, you can update the run status of an individual ad group via the ads api.
To do this, you submit a POST request to /<AD_GROUP_ID>/ with adgroup_status=X where X is your status (1 for active, 9 for paused, etc).  However, making this request results in the status NOT changing, and the only response you get back from Facebook is a JSON representation of the Ad Group.
Has anyone been able to successfully submit ad group status updates to the facebook ads api?  If so, are you using the method outlined above, or is there another trick to it?
thanks!
EDIT
I cross posted this into the Facebook Bug tracker in hopes to create a trail/awareness/find more people who were having this problem. https://developers.facebook.com/bugs/354657724569051
EDIT
An example of the request I'm making.  This request is being tested from the Facebook Graph Explorer
https://graph.facebook.com/6003521999629?adgroup_status=9&method=POST&access_token=<access_token>

A: We have not been experiencing problems with changing adgroup_status. Try submitting the status number as an integer and then as a string (I don't remember which type they expect). Note that if the campaign is paused, setting the adgroup_status to 1 will actually change it to 8 (campaign_paused). The fact that you're getting the adgroup to redownload (I presume you have the redownload=1 parameter) tells me that your call is mostly correct. I just confirmed that this works:
curl -F "adgroup_status=9" \
-F "ids=..." \
-F "access_token=..." \
https://graph.facebook.com/

A: If you're making that API call and receiving the adgroup's details back instead of a 'true' response, it means you're making a GET request, not a POST request.
Update your code to make a HTTP POST request, and this will resolve your issue, John Pickard's answer above is an example of making a POST request in curl, but it will change depending on your application's language and/or which Facebook SDK you're using.


text:
Q: Format text loaded from a .txt-file to a UITextView? I have a UITextView that fetches text from a plain .txt-file (using the code below).
I've tried to change the look of the text both in the interface builder and programmatically, but nothing works.
Is it not possible to format a text that is read from a txt-file?
    NSString *path = [[NSBundle mainBundle]pathForResource:@"plain3" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[self.myText setText:content];


text:
Q: How to get the length of the left/right offsets in a QSlider? I'm trying to make a subclass of QSlider that allows the user to insert "bookmarks" so they can remember significant locations on the slider. I've run into a problem painting the tabs on the slider - using QStyle.sliderPositionFromValue, I get a value but it is slightly inaccurate. If I'm on the left side of the slider, the tab is painted too far left, and on the right side it is painted too far right. I believe this is because QSlider.width() returns the width of the whole object, including the small offsets at the left and right. So width() might return 630 pixels, when the length of the slider itself is really 615.
This is the code I'm using to get the pixel position and draw a line across the slider.
pos = QStyle.sliderPositionFromValue(self.minimum(),self.maximum(),sliderIndex,self.width())
painter.drawLine(pos,0,pos,self.height())

I've been looking at the QT Source here starting on line 2699 and it seems like I need to be using the PixelMetric class from QStyle. I've tried using:
self.style().pixelMetric(QStyle.PM_SliderSpaceAvailable)

But that returns 0, which is clearly not the value I need.
I'd appreciate any advice.
Edit: As suggested in the comments, I changed the call to:
self.style().pixelMetric(QStyle.PM_SliderSpaceAvailable, QStyleOption(1,QStyleOption.SO_Slider),self)

This however, returns -14, which also doesn't match for the value of the offsets (I tried using self.width()-14 but the offset remains.


text:
Q: How to call a method in the parent iPhone app from Today Extension in Swift? I have just created an Apple Watch extension to my iPhone App and used the following method to update my app data.
// Call the parent application which launches a method to update the app data
WatchViewController.openParentApplication([:],
    reply: { (reply, error) -> Void in
        self.updateGui() // update the gui when done
    })

Is there anything similar for Apple Today Extensions (widgets)? It feels wrong to implement all the client-server communication again for the extension.
Or how do you suggest to update my data (stored in app group throughout iPhone app, WatchKit and Today Extension).

A: No need to write client-server communication code separate for container app and its extension.
Apple recommends embedded frameworks for the same. You create an embedded framework which can be used across both targets. Place code that will need to be used by both the container app and extension in the framework to avoid code repetition.
And for sharing data between container app and extension, you can use NSUserDefaults through AppGroup.
Please check Apple documentation.


text:
Q: Package organization and project structure design I am trying to create a textsearcher library in java, that will have an interface TextSearcher and 3 classes implementing it: RegexPatternSearcher, SingleTokenSearcher and MultiTokenSearcher
I then created a TextSearcherFacade class that exposes static methods like:

*

*static findEmailAddresses(String input) - uses RegexPatternSearcher

*static findPhoneNumbers(String input) - uses RegexPatternSearcher

*static findDisallowedWords(String input, Set<String> disAllowedWords) - uses SingleTokenSearcher
I want users of the library to have these (i.e. methods from TextSearcherFacade) simple methods exposed for ease of use.
However, I don't like the idea of a single TextSearcherFacade class with methods that configure and create the RegexPatternSearcher, SingleTokenSearcher and MultiTokenSearcher because these methods depend on different classes and seem logically different.
I am trying to look for a better and more extensible way to design this library. Any help is greatly appreciated.

A: You could create a class for each of your find methods. For example, you could have an EmailFinder, PhoneNumberFinder, etc.
Additionally, they could implement an interface with a List<FindResult> find(String input) method, and you could use them by instantiating them and calling the find() method.


text:
Q: Stereographic Projection Continuity Via Open Balls Suppose $S^2 \setminus \{N\}$ is a centered-at-origin unit sphere with the north pole removed and $\mathbb{R}^2$ is an xy-plane at height $z = 0$. The following stereographic projection functions:
$$f(p_{1}, p_{2},p_{3}) = (\dfrac{p_{1}}{1 - p_{3}}, \dfrac{p_{2}}{1 - p_{3}})$$
$$\text{and}$$
$$f^{-1}(q_{1}, q_{2}) = (\dfrac{2q_{1}}{q_{1}^{\:2} + q_{2}^{\:2} + 1}, \dfrac{2{q_2}}{q_{1}^{\:2} + q_{2}^{\:2} + 1}, \dfrac{q_{1}^{\:2} + q_{2}^{\:2} - 1}{q_{1}^{\:2} + q_{2}^{\:2} + 1})$$
provide maps between $P \in S^2 \setminus \{N\}$ and $Q \in \mathbb{R}^2$
There are many methods of proving that $f$ and $f^{-1}$ are continuous. My favorite method is to use open balls because it correlates heavily with the open set definition of continuity.
I believe that $f$ maps circles to circles as shown here:http://www.cs.bsu.edu/homepages/hfischer/math345/stereo.pdf
A spherical cap $\mathcal{O}_x$ centered at $x \in \mathcal{O}_x$, of our punctured 2-sphere can be defined as:
$$\mathcal{O}_x = \{y \in S^2 \setminus\{N\}: d(x, y) < r\}$$ $$\text{where $r$ is a great circle distance and}$$ $$d(x, y) = acos(x \cdot y)$$
Let $C = (c_1, c_2, c_3) \in S^2 \setminus \{N\}$. A cap centered at $C \in S^2$ can then be defined as:
$$\mathcal{O}_c = \{P \in S^2 \setminus \{N\}: acos(p_1c_1 + p_2c_2 + p_3c_3) < r\}$$
Following the same steps of the Circle-to-Circle proof, plugging in a cap instead of a circle, one can conclude that the image $f(\mathcal{O}_c)$ is equal to:
$$f(\mathcal{O}_c) =  \{Q \in \mathbb{R}^2: (q_1 + \frac{c_1}{c_3 - cos(r)})^2 + (q_2 + \frac{c_2}{c_3 - cos(r)})^2 < \frac{1 - cos^2(r)}{(c_3 - cos(r))^2}\}$$
If $r < \pi$, and $c_3 \neq cos(r)$, this matches the definition of an open euclidean ball of $\mathbb{R}^2$ which has a $$center = -(\frac{c_1}{c_3 - cos(r)}, \frac{c_2}{c_3 - cos(r)})$$ $$\text{and a}$$ $$radius = \sqrt{\frac{1 - cos^2(r)}{(c_3 - cos(r))^2}}$$
$\implies f$ maps spherical caps to open balls
$\implies f$ maps unions of open spherical caps to unions of open balls
The spherical caps as defined above are a basis for the topology on $S^2$, which essentially means that they are the open balls of $S^2$
The open Euclidean balls in the plane are a basis for the topology on $\mathbb{R}^2$
$\implies$ Any open set of $S^2$ can be formed from unions of its basis elements. Likewise, any open set of $\mathbb{R}^2$ can be formed from unions of its basis elements
$\implies f$ maps open sets to open sets
$\implies f^{-1}$ is continuous

QUESTIONS:
I also want to prove that $f$ is continuous, so if $f$ maps circles to circles, why does $f^{-1}$ also do so? Could it be implied by construction of the circle-to-circle proof? Would it have to proven in a separate circle-to-circle for $f^{-1}$? Could it be implied due to $f$ being bijective?
I claimed that "The spherical caps as defined above are a basis for the topology on $S^2$"
This makes sense to me, but I'm not too sure why. Could this be shown by proving that any open set of $S^2$ is equivalent to unions of these spherical caps? How could that be done? I know the topology of the sphere is generally thought of as the open sets of $\mathbb{R}^3$  intersected with the sphere.
Any other pointers or comments on this proof will be appreciated.


text:
Q: Socket.io with Next.js not recognising inbuilt node packages I am making a website using socket.io and next.js and for some reason I am getting an error saying

error - ./node_modules/ws/lib/sender.js:6:0 Module not found: Can't resolve 'tls'
Import trace for requested module: ./node_modules/ws/index.js
./node_modules/engine.io/build/server.js
./node_modules/engine.io/build/engine.io.js
./node_modules/socket.io/dist/index.js
./node_modules/socket.io/wrapper.mjs ./pages/index.js

I don't understand why it's not using the inbuilt package. So I installed "tls", and now its stuck on "fs" and no matter how many times i install fs it doesn't work. does anyone have a solution?


text:
Q: django: create object from constructor or model form After obtaining data from a model form based on a Model, say
form_data = MyModelForm(request.POST)

Then I can either create an instance of Model by
instance = Model(**form_data.cleaned_data)

Or by
instance = form_data.save()

I wonder which one is the preferred way in the django world

A: There is a significant difference between the two.
instance = Model(**form_data.cleaned_data) doesn't save the object in the database. It only creates a local instance.
instance = form_data.save() adds the object to the database (it performs a commit, if so supported), and it also has the side effect of triggering validation.
If you want to do custom post-processing of the object before saving it, you pass commit=False to the save() method.
instance = form_data.save(commit=False)
# do some stuff with instance
instance.save()


text:
Q: How to customize gInfoWindow I want to know how to customize a gInfoWindow, but not just the HTML inside it, also the window its self(no rounded corners,backgroundcolor...)
I am a bit noob with google map API V2, so some step by step tips would be of great help.
This is my current code, so you can give me some tips on how i should modify it:
var marker1 = new GMarker(new GLatLng(53.117024,79.04068), {
        draggable: false,
        title: 'My marker'
        });

              GEvent.addListener(marker1, "click", function() {
        marker1.openInfoWindowHtml('
Custom inner xhtml
');
        });

                map.addOverlay(marker1);

A: Do you have to use version 2?  Google maps version 3 has a utility library that allows you to alter the info window appearance, InfoBox and InfoBubble.
Google Maps Utility Library v3


text:
Q: Show that $n^2 + m^2 = 2nm$ is an equivalent relation How can I show this is an equivalence relation:
$nRm ⟺ n^2 + m^2  = 2nm$
I had no problem proving the first two steps (reflexivity and symetric). However, for the transitivity part, I can't get to show it. Anyone can help me?

A: Hint: $n^2+m^2=2nm\iff(n-m)^2=0\iff n=m$.

A: This is a solution without the fact that this relation is equivalent to standard equality
let $n^2 + m^2 = 2mn$ and  $m^2 + p^2 = 2mp$. This is equivalent to mRn and pRm
Subtracting the equations, $$n^2 - p^2 = 2m(n-p)$$
$$(n-p)(n+p) = 2m(n-p)$$
So either n = p and nRp trivially or we can divide by $n - p$
$$n+p = 2m$$
$$\frac{n+p}{2} = m$$
$$n^2 + (\frac{n+p}{2})^2 = 2n\frac{n+p}{2}$$
$$n^2 + \frac{n^2+2np+p^2}{4} = n^2+np$$
$$\frac{n^2+2np+p^2}{4} = np$$
$$n^2+2np+p^2 = 4np$$
$$n^2+p^2 = 2np$$
so nRp
Therefore nRm and mRp $\Rightarrow$ nRp


text:
Q: Grid view overlapping on another grid view in wpf I have a grid view that declared in another grid view. My problem is the free space of upper grid view overlapping on the bottom grid view. Ho can i fix this problem ?
This is my XAML code :
<Window x:Class="WpfApp15.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp15"
    x:Name="myWin"
    mc:Ignorable="d"
    Title="MainWindow" Height="500" Width="400" >
<Grid>
   <Grid.ColumnDefinitions>
       <ColumnDefinition Width="50"/>
       <ColumnDefinition Width="*"/>
       <ColumnDefinition Width="50"/>
   </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="80"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="80"/>
    </Grid.RowDefinitions>
    <Grid Row="1" Column="1" MinWidth="150" MinHeight="240">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Grid.Column="0" Content="%" Margin="2"/>
        <Button Grid.Row="0" Grid.Column="1" Content=">\" Margin="2"/>
        <Button Grid.Row="0" Grid.Column="2" Content="x^2" Margin="2"/>
        <Button Grid.Row="0" Grid.Column="3" Content="1/x" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="0" Content="CE" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="1" Content="C" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="2" Content=">" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="3" Content="/" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="0" Content="7" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="1" Content="8" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="2" Content="9" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="3" Content="X" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="0" Content="4" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="1" Content="5" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="2" Content="6" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="3" Content="-" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="0" Content="1" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="1" Content="2" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="2" Content="3" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="3" Content="+" Margin="2"/>
        <Button Grid.Row="5" Grid.Column="0" Content="+-" Margin="2"/>
        <Button Grid.Row="5" Grid.Column="1" Content="0" Margin="2"/>
        <Button Grid.Row="5" Grid.Column="2" Content="." Margin="2"/>
        <Button Grid.Row="5" Grid.Column="3" Content="=" Margin="2"/>
    </Grid>
</Grid>

In this two picture you can see my problem well
My whole view
My problem

A: When I run the code nothing is immediately cut off, so I assume you mean the buttons are cut off when resizing.
I would make the height of the inner grid "Auto" and move the MinHeight to the Window itself. I'd increase the MinHeight to something lime 350 as well if that's acceptable.
<Window x:Class="WpfApp15.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp15"
    x:Name="myWin"
    mc:Ignorable="d"
    Title="MainWindow" Height="500" Width="400" MinHeight="350">
<Grid>
   <Grid.ColumnDefinitions>
       <ColumnDefinition Width="50"/>
       <ColumnDefinition Width="*"/>
       <ColumnDefinition Width="50"/>
   </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="80"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="80"/>
    </Grid.RowDefinitions>
    <Grid Row="1" Column="1" MinWidth="150" Height="Auto">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Grid.Column="0" Content="%" Margin="2"/>
        <Button Grid.Row="0" Grid.Column="1" Content=">\" Margin="2"/>
        <Button Grid.Row="0" Grid.Column="2" Content="x^2" Margin="2"/>
        <Button Grid.Row="0" Grid.Column="3" Content="1/x" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="0" Content="CE" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="1" Content="C" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="2" Content=">" Margin="2"/>
        <Button Grid.Row="1" Grid.Column="3" Content="/" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="0" Content="7" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="1" Content="8" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="2" Content="9" Margin="2"/>
        <Button Grid.Row="2" Grid.Column="3" Content="X" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="0" Content="4" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="1" Content="5" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="2" Content="6" Margin="2"/>
        <Button Grid.Row="3" Grid.Column="3" Content="-" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="0" Content="1" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="1" Content="2" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="2" Content="3" Margin="2"/>
        <Button Grid.Row="4" Grid.Column="3" Content="+" Margin="2"/>
        <Button Grid.Row="5" Grid.Column="0" Content="+-" Margin="2"/>
        <Button Grid.Row="5" Grid.Column="1" Content="0" Margin="2"/>
        <Button Grid.Row="5" Grid.Column="2" Content="." Margin="2"/>
        <Button Grid.Row="5" Grid.Column="3" Content="=" Margin="2"/>
    </Grid>
</Grid>


text:
Q: How do I call Apache's MethodUtils methods with mocks from Mockito as paramaters? I use org.apache.commons.beanutils.MethodUtils (api link) on occasion.  I generally avoid reflection, but alas this case called for it.
My problem comes to testing.  I use Mockito for mocking, and when I call MethodUtils.invokeMethod with a mock as an argument, MethodUtils throws a NoSuchMethodError because it thinks the mocked object doesn't match the parameter type.  Any suggestions?
Signature of concrete method I'm calling:
public void propagateMirrorRateOfferId(MasterAvailabilityRule masterAvailabilityRule)

My mock generation:
@RunWith(MockitoJUnitRunner.class)
public class SomeTest {

    private static final Long RATE_OFFER_ID = 1L;
    private static final Long RATE_ENTITY_ID = 2L;
    private static final Long ORIGINAL_RATE_OFFER_ID = 3L;
    private static final Long ORIGINAL_RATE_ENTITY_ID = 4L;

    @Mock MasterAvailabilityRule masterAvailabilityRule;
    PropertyAvailabilityRule propertyAvailabilityRule;

    @Before
    public void setUp() throws Exception {
        propertyAvailabilityRule = new PropertyAvailabilityRule();
        propertyAvailabilityRule.setMirrorRateOfferId(ORIGINAL_RATE_OFFER_ID);
        propertyAvailabilityRule.setMirrorRateEntityId(ORIGINAL_RATE_ENTITY_ID);
    }

    @Test
    public void testPropagate() throws Exception {
        // arrange
        when(masterAvailabilityRule.determineAvailabilityMirroringRelationship(any(String.class))).
            thenReturn(new AvailabilityMirroringRelationship(RATE_OFFER_ID, RATE_ENTITY_ID));
        when(masterAvailabilityRule.isMirrorLocked()).
                thenReturn(true);

        // action
        SomeUtility.thatCallsMethodUtilsAndPassesThisMock(masterAvailabilityRule);

        // assert
        assertEquals("Should have updated the mirrored rate offer id.", RATE_OFFER_ID, propertyAvailabilityRule.getMirrorRateOfferId());
        assertEquals("Should have updated the mirrored rate entity id.", RATE_ENTITY_ID, propertyAvailabilityRule.getMirrorRateEntityId());

    }
}

Thanks all, figured it out
In coming up with the examples for you guys, I put the MethodUtils call directly in my test and it worked.  Turns out the I had imported the MethodUtils class from org.apache.commons.lang.reflect.MethodUtils in my utility class.  For some reason, that version of the class fails with the mocks.  When I use org.apache.commons.beanutils.MethodUtils it works.  Not sure why.  Perhaps I should update my original question to ask why the one in the reflect package fails... Anyway, will mark my question as answered once enough time has passed for me to submit an answer.

A: Turns out the I had imported the MethodUtils class from org.apache.commons.lang.reflect.MethodUtils in my utility class. For some reason, that version of the class fails with the mocks. When I use org.apache.commons.beanutils.MethodUtils it works.


text:
Q: Can {that} be used as "which" and "where" in the same sentence? Consider the following sentence:

If you use {foreign word} with {the equivalent of "in"} then what you're referring to is a place that
you're familiar with, one that you probably love and have good
memories.

Can "that" be used as both "which" and "where" at the same time here?
I would also go as far as asking: can I omit it?

A: You can use "that" as both which and where, but you need to append "of" to the end of the sentence:

"what you're referring to is a place that you're familiar with, one
that you probably love and have good memories of"

Likewise, you can also omit "that":

"what you're referring to is a place that you're familiar with, one
you probably love and have good memories of"

This is because you drop out the first part of the and, leaving you with "what you're referring to is a place that you're familiar with, one that you probably love and have good memories of"

A: The pronouns "that" and "which" are used to introduce relative clauses, but there's a big difference between the two, especially in speech. Consider the following examples:

This is the house that I like that has a swimming pool.

The relative clause "that has a swimming pool" restrictively modifies "house that I like," suggesting that you know that I like multiple houses, so I'm narrowing it down for you by telling you that this house of those houses that you know I like is the one with a swimming pool, the swimming pool being the feature that sets it apart from the rest.

This is the house that I like, which has a swimming pool.

The relative clause "which has a swimming pool" nonrestrictively modifies "house that I like, suggesting that there's only one house that I like, not multiples houses, and telling you it has a swimming pool, information that is purely parenthetical and nonessential to the operation of the sentence, just an added bit of trivia.
In the above examples, the first has no comma, while the second example has a comma. Since grammar calls for there being no comma between a restrictive clause and the antecedent it modifies, not seeing a comma in the first sentence immediately tells us that that's a restrictive clause, and since grammar calls for there being a comma between a nonrestrictive clause and the antecedent it modifies, seeing a comma in the second sentence immediately tells us that it's a nonrestrictive clause.
However, when we're speaking and not reading, we don't have the benefit of seeing if there's a comma there or not, nor can we hear that comma because it generally results in no discernable pause, so when speaking, how we communicate that the clause is restrictive, like in the first example, is we use "that" and how we communicate the clause is nonrestrictive, like the second example, is we use "which."
If the first "that" clause were a nonrestrictive clause, the sentence would instead be said and written as follows:

"What you're referring to is a place, which you're familiar with, one
that you probably love and have good memories of."

As a nonrestrictive clause, you'd offset the clause with commas on either side and use "which," not "that," never "that."
If the second "that" clause were a nonrestrictive clause, the sentence would instead be spoken and written as follows:

"What you're referring to is a place that you're familiar with, one
which you probably love and have good memories of."

That would essentially be the same as saying or writing:

"What you're referring to is a place that you're familiar with, which
you probably love and have good memories of.

If that sentence had NO nonrestrictive clauses, then you'd say and write:

"What you're referring to is a place that you're familiar with that
you probably love and have good memories of."

Notice the lack of commas around the "that" clauses. Now, if you were to insert "one" into the sentence, the word "one" is being used pronounally to introduce a second item in a list of two items in which you don't use the conjunction "and," so a comma is grammatically required, not because it's a nonrestrictive clause but because of the lack of "and," and you know it's not a nonrestrictive clause because you don't use "which" but use "that," as follows:

What you're referring to is a place that you're familiar with, one (a
place) that you probably love and have good memories of.

THE POINT OF THIS ANSWER IS TO EXPLAIN HOW "THAT" AND "WHICH" ARE USED DIFFERENTLY AND THAT WHEN YOU SAY THAT ONE "THAT" MEANS "WHICH" AND THE OTHER MEANS "WHERE" IN YOUR SENTENCE, IT'S INCORRECT. NEITHER MEANS "WHICH." OR IF ONE IS SUPPOSED TO, THEN YOU'VE WRITTEN IT INCORRECTLY AND SHOULD REFER TO ONE OF THE ABOVE EXAMPLES AS THE CORRECTION.
ALSO, NOTICE THE "OF" I ADDED AT THE END OF EACH EXAMPLE. IT'S REQUIRED. WHETHER "THAT YOU HAVE GOOD MEMORIES" OR "WHICH YOU HAVE GOOD MEMORIES," NEITHER IS COMPLETE. BOTH REQUIRE THE PREPOSITION "OF."


text:
Q: Update Value Object fileld in Mvc code First I have a value object named Validity and its attribute StartDate and EndDate.
I have Update this field.but getting some error.The error is:
InvalidOperationException: The entity type 'Validity' has a defining navigation and the supplied entity is currently not being tracked. To start tracking this entity call '.Reference().TargetEntry' on the owner entry.
How to solve this error?
My Code Is:
public async Task<Subscription> Update(string ID, bool Active, string Plan, string Periodicity, decimal Price, string LocationTargets, string paymentStatus,
            DateTime startDate, DateTime endDate, string OperationType)
        {
            #region PaymentStatus
            int EnumPaymentStatus = 0;
            string[] values = Enum.GetNames(typeof(PaymentStatusEnum.PaymentStatus));

            if (values[0] == paymentStatus)
            {
                EnumPaymentStatus = (int)PaymentStatus.Due;
            }
            else if (values[1] == paymentStatus)
            {
                EnumPaymentStatus = (int)PaymentStatus.Open;
            }
            else if (values[2] == paymentStatus)
            {
                EnumPaymentStatus = (int)PaymentStatus.UnPaid;
            }
            else if (values[3] == paymentStatus)
            {
                EnumPaymentStatus = (int)PaymentStatus.Paid;
            }
            #endregion

            #region Periodicity
            int EnumPeriodicityValue = 0;
            string[] values1 = Enum.GetNames(typeof(PeriodicityEnum.EnumPeriodicity));

            if (values1[0] == Periodicity)
            {
                EnumPeriodicityValue = (int)EnumPeriodicity.Monthly;
            }
            else if (values1[1] == Periodicity)
            {
                EnumPeriodicityValue = (int)EnumPeriodicity.Trimestral;
            }
            else if (values1[2] == Periodicity)
            {
                EnumPeriodicityValue = (int)EnumPeriodicity.Semestral;
            }
            else if (values1[3] == Periodicity)
            {
                EnumPeriodicityValue = (int)EnumPeriodicity.Annual;
            }
            #endregion

            #region Operation Type
            int OperationTypeValue = 0;
            string[] values2 = Enum.GetNames(typeof(OperationTypeEnum.EnumOperationType));

            if (values2[0] == OperationType)
            {
                OperationTypeValue = (int)EnumOperationType.NewSubscription;
            }
            else if (values2[1] == OperationType)
            {
                OperationTypeValue = (int)EnumOperationType.SubscriptionRenewal;
            }
            else if (values2[2] == OperationType)
            {
                OperationTypeValue = (int)EnumOperationType.SubscriptionCancellation;
            }
            else if (values2[3] == OperationType)
            {
                OperationTypeValue = (int)EnumOperationType.SubscriptionChange;
            }
            #endregion

            #region Update Data in Subscription Table
            var subscription = new Subscription()
            {
                ID = ID,
                Active = Active,
                Plan = Plan,
                Periodicity = Convert.ToString(EnumPeriodicityValue),
                Price = Price,
                LocationTargets = LocationTargets,
                PaymentStatus = Convert.ToString(EnumPaymentStatus),
                OperationType = Convert.ToString(OperationTypeValue),
                UpdatedAt = DateTime.UtcNow
            };
            subscription.Validity = new Validity(startDate, endDate);
            //Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<Subscription> s = await _db.AddAsync(subscription);

            _db.Entry(subscription).Property(x => x.Active).IsModified = true;
            _db.Entry(subscription).Property(x => x.Plan).IsModified = true;
            _db.Entry(subscription).Property(x => x.Periodicity).IsModified = true;
            _db.Entry(subscription).Property(x => x.Price).IsModified = true;
            _db.Entry(subscription).Property(x => x.LocationTargets).IsModified = true;
            _db.Entry(subscription).Property(x => x.PaymentStatus).IsModified = true;

            _db.Entry(subscription.Validity).Property(x => x.StartDate).IsModified = true;
            _db.Entry(subscription.Validity).Property(x => x.EndDate).IsModified = true;

            _db.Entry(subscription).Property(x => x.OperationType).IsModified = true;
            _db.Entry(subscription).Property(x => x.UpdatedAt).IsModified = true;

            #endregion

            #region Insert Data in SubscriptionHistory Table

            string a = Convert.ToString(GuidComb.Generate());
            var subscriptionhistory = new SubscriptionHistory()
            {
                ID = a,
                Active = Active,
                Plan = Plan,
                Periodicity = Convert.ToString(EnumPeriodicityValue),
                Price = Price,
                LocationTargets = LocationTargets,
                PaymentStatus = Convert.ToString(EnumPaymentStatus),
                OperationType = Convert.ToString(OperationTypeValue)
            };
            subscriptionhistory.Validity = new Validity(startDate, endDate);

            Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<SubscriptionHistory> y = await _db.AddAsync(subscriptionhistory);

            #endregion

            await _db.SaveChangesAsync();
            return subscription;
        }

In Subscription Class:
 public class Subscription: BaseEntity
    {
        public Subscription()
        {
            this.ID = Convert.ToString(System.Guid.NewGuid());
            this.CreatedAt = DateTime.UtcNow;
            this.IsCancel = false;
        }

        private List<Validity> validities = new List<Validity>();

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [MaxLength(128)]
        public string ID { get; set; }

        public bool Active { get; set; }

        [MaxLength(150)]
        public string Plan { get; set; }

        [MaxLength(101)]
        public string Periodicity { get; set; }

        public decimal Price { get; set; }

        [MaxLength(250)]
        public string LocationTargets { get; set; }

        [MaxLength(101)]
        public string PaymentStatus { get; set; }

        public Validity Validity { get; set; }

        [MaxLength(101)]
        public string OperationType { get; set; }

        public bool IsCancel { get; set; }

        public DateTime CreatedAt { get; set; }

        public DateTime UpdatedAt { get; set; }

        public DateTime DeletedAt { get; set; }

        public bool Deleted { get; set; }

        //private List<Validity> validities = new List<Validity>();

        public void Assignvalidity(Validity validitys)
        {
            this.validities.Add(validitys);
        }

    }

In Validity Class:

 public class Validity : ValueObject
    {
        public DateTime StartDate { get; private set; }
        public DateTime EndDate { get; private set; }

        private Validity() { }

        public Validity(DateTime  startdate, DateTime enddate)
        {
            StartDate = startdate;
            EndDate = enddate;
        }

        protected override IEnumerable<object> GetAtomicValues()
        {
            yield return StartDate;
            yield return EndDate;
        }

    }

A: Add this line:
 Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry s =  _db.Update(subscription);
After this line:
subscription.Validity = new Validity(startDate, endDate);

A: In order to update an entity it must be tracked by the entity, in your below code you are creating new object :
var subscription = new Subscription()
            {
                ID = ID,
                Active = Active,
                Plan = Plan,
                Periodicity = Convert.ToString(EnumPeriodicityValue),
                Price = Price,
                LocationTargets = LocationTargets,
                PaymentStatus = Convert.ToString(EnumPaymentStatus),
                OperationType = Convert.ToString(OperationTypeValue),
                UpdatedAt = DateTime.UtcNow
            };

First you need to get that entity from the db, then update related fields and save to db;
[UPDATE]
The validity is a related entity to Subscription, so you need an include query to fetch the object from the db, then you can update and save.
var subscription = _db.Set<Subscription>().Single(x=>x.ID == ID).Include(x=>x.Validity);

subscription.Validity.StartDate = startDate;
subscription.Vaklidity.EndDate = endDate;

_db.SaveChanges();

[UPDATE]
add foreignkey attributes then create a new migration then update the db:
public class Validity : ValueObject
    {
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }

        public string SubscriptionID { get; set; }
        public Subscription Subscription { get; set; }

        // ...
    }

public class Subscription: BaseEntity
    {
        public string ValidityID { get; set; }
        public Validity Validity { get; set; }

        // ...
    }

After updating the db, get the related Validity entity and update it:
var validity = _db.Set<Validity>().Find(x => x.SubscriptionID == ID);

validity.StartDate = startDate;
validity.EndDate = endDate;

_db.SaveChanges();


text:
Q: Assign jenkins variable in application.properties spring boot You can use variable defined in jenkins in an application.properties so that it is overridden by a value when jenkins starts building the application. Some example of this configuration.
Example application.properties
spring.datasource.url = $ {VARIABLE-JENKINS}


text:
Q: Complete copy of Ubuntu system I have a Linode with Ubuntu installed.  The machine is used for things like web sites and Minecraft.
I would like to create a complete 'offline' copy of the server to test some new packages and upgrades of current packages.  I would want to place this copy into a VirtualBox VM.
Data is less important (e.g. user files, web sites, Minecraft worlds, etc), but I would very much like to be able to copy configuration (web site configs, packages installed, etc).
Is this possible?  I feel that there might be an easy way to get the same packages installed across two systems (obtain a list of installed packages and feed this into an installing system), but perhaps it may be more difficult to get the config files (stuffs found in /etc for example) - perhaps difficult is wrong, perhaps more manual is a better description.

A: To install the same packages you could copy the /etc/apt/sources.list contents to the new server and then issue dpkg -l | awk -F" " '{print $2,$3}' | tr " " "=" | tr "\n" " " which will give you all packages installed (via dpkg, apt-get, aptitude, etc).
You could redirect to a file and then use apt-get install < file.txt to install all the same packages with the same version.
Since you're running same distro, same kernel (possibly different after upgrade) and same packages versions it should be OK for you just to copy the /etc folder.

A: Linode has a "duplicate disk image" feature that you can use to copy your VM disks.
This doesn't allow a VirtualBox installation, but it does allow to have a test environment after cloning.

A: One way to do this would be to image the system using Clonezilla. Then create a new virtual machine, boot up the Live CD of Clonezilla in there, and slap the image on a Virtual Hard Drive.

A: I suggest you two different approaches: 1. dd your current disk to a file and back out to your VM disk; or 2. Install a fresh copy of linode on you VM and rsync all the files you want/need into it.
The rsync command will be, from the linode VM, something like this:
rsync -avzgroupP --excude=/proc --exclude=/dev --exclude=/sys --exclude=/lost+found --exclude=/var/log -e ssh root@linode.host:/ /

For the command to be run from the host machine, just switch root@linode.host:/ / to / root@vm.

A: You may want to try Devstructure's Blueprint. It inventories the system and will generate chef, puppet, or bash scripts to regenerate it.


text:
Q: How can I create custom shapes in swiftUI I'm learning swiftui and I want to create some shapes in my app.
I instead of repeating my code I decided to create a function to display the shape.
I tried to create a func that contains the shape and call it where I need it.
import SwiftUI

struct HomeView: View {
    var body: some View {
        VStack{
            HStack{
               rect()
            }
        }
    }
}

func rect() {
    Rectangle()
        .frame(width: 100, height: 100)
        .cornerRadius(18)
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}

What is my problem here, and how can I fix it so I can create different styles for buttons, textboxes, images, etc...

A: To create a function for showing the view one must create @ViewBuilder function and return some View.
You need to do something like this :-
      @ViewBuilder func rect() -> some View {

              Rectangle()
                  .frame(width: 100, height: 100)
                  .cornerRadius(18)

      }

A: You're on the right track, instead of defining a function, define a new view:
struct MyRect: View {

    var body: some View {
        Rectangle()
            .frame(width: 100, height: 100)
            .cornerRadius(18)
    }
}

// Embed with 'MyRect()'

Alternatively, the func rect in your code could have a return type some View:
func rect() -> some View {
    Rectangle()
        .frame(width: 100, height: 100)
        .cornerRadius(18)
}

// Embed with 'rect()'

A: The func rect is of type Void, the body in your View returns some View. You should make your function's return type conform to View, so either:

*

*return a Shape func rect() -> Shape {

*return a View func rect() -> some View {
Do note that if go with option number 1 you cannot return anything that is not a Shape.


text:
Q: Why does this keep going around in a never ending loop? def get_houseid_list():
    """Returns a list of all house ids from db"""
    print 'Building list of all HouseIDs...'
    houseid_list = []
    houseids = session.query(Episode.HouseID).all()
    for i in houseids:
        houseid_list.append(i[0])
    return houseid_list

def walkDir(top, ignore=[]):
    """Returns a complete list of files from a directory, recursing through subfolders"""
    print 'Building list of files...'
    fflist = []
    for root, dirs, files in os.walk(top):
        dirs[:] = [ dn for dn in dirs if dn not in ignore ]
        file_list =  [name for name in files if name[0] != '.']
        if len(file_list):
            for f in file_list:
                try:
                    houseid_parse(f)
                    print 'adding...', f
                    [fflist.append(join(root, f)) for f in file_list]
                except HouseIdException:
                    print 'skipping...', f
            print 'Found', len(file_list), 'files in', root
    return fflist

def get_nonmatches(houseid_list, finallist):
    print 'Comparing files to HouseIDs...'
    nonmatches = []
    for id in houseid_list:
        print 'Searching for files to match', id
        for f in finallist:
            if re.search(id, f, re.IGNORECASE):
                nonmatches.append(f)
    return nonmatches

def writeCSV(nonmatch):
    print 'Writing nonmatches to CSV...'
    csv.write('%s' % nonmatch)

if __name__ == "__main__":

    houseid_list = get_houseid_list()
    print len(houseid_list), 'HouseIDs found'
    wdirs = ['/Volumes/Assets/Projects']
    finallist = []
    for d in wdirs:
        fflist = walkDir(d)
    for f in fflist:
        nonmatches = get_nonmatches(houseid_list,f)
    print 'nonmatches', nonmatches

A: Just some comments on this code, while we wait for you to give us enough information to solve your problem..
It's pretty horrible depending on a side effect like this
[fflist.append(join(root, f)) for f in file_list]

when you can just say
fflist.extend(join(root, f) for f in file_list)

But that looks like a bug to me, do you mean to iterate over file_list again there? Perhaps you just need
fflist.append(join(root, f))

This part seems to remove the condition from it's effect
if len(file_list):
    for f in file_list:
        try:
            houseid_parse(f)
            print 'adding...', f
            [fflist.append(join(root, f)) for f in file_list]
        except HouseIdException:
            print 'skipping...', f
    print 'Found', len(file_list), 'files in', root

Why not write it like this?
for f in file_list:
    try:
        houseid_parse(f)
        print 'adding...', f
        fflist.append(join(root, f))
    except HouseIdException:
        print 'skipping...', f
if file_list:
    print 'Found', len(file_list), 'files in', root

If you are just going to iterate over fflist, maybe you can turn walkDir into a generator
def walkDir(top, ignore=[]):
    """Returns a generator for a complete list of files from a directory,
       recursing through subfolders"""
    for root, dirs, files in os.walk(top):
        dirs[:] = [ dn for dn in dirs if dn not in ignore ]
        file_list =  [name for name in files if name[0] != '.']
        for f in file_list:
            try:
                houseid_parse(f)
                print 'yielding...', f
                yield join(root, f)
            except HouseIdException:
                print 'skipping...', f
        if file_list:
            print 'Found', len(file_list), 'files in', root

Now perhaps you tell us what the output of the program is and why you are sure it's an infinite loop and not just taking a long time to run. For all we can tell this line
houseids = session.query(Episode.HouseID).all()

could just be taking a very long time to execute


text:
Q: MySQL - Use MAX() on one column and also return data from the rest of the row? I'm not sure if this is a complicated issue or if I'm just missing something trivial, but I can't quite figure this out.
I have a table that lists error messages and the time they appeared:
id     created_at          content
1      2017-08-05 08:00    ...
2      2017-08-15 16:00    ...
3      2017-08-15 16:01    ...
4      2017-08-15 16:02    ...
5      2017-08-25 16:00    ...

I group these rows together based on date and hour and count how many errors appeared:
SELECT DATE_FORMAT(created_at, '%d.%m. %h'),
       COUNT(*) AS errorCount
       FROM db.errorData
       GROUP BY DAY(created_at), HOUR(created_at);

Resulting in this:
created_at          errorCount
2017-08-05 08       1
2017-08-15 16       3
2017-08-25 16       1

Now I want to use MAX() to get the highest errorCount. I do this with a subselect:
SELECT MAX(errorCount) AS errorMax
       FROM(
         SELECT DATE_FORMAT(created_at, '%d.%m. %h'),
         COUNT(*) AS errorCount
         FROM db.errorData
         GROUP BY DAY(created_at), HOUR(created_at)
       ) alias;

However, I also want to get the date of the day with the most errors. Simply adding created_at to the first SELECT doesn't work since it only returns the value of the first row.
I don't know how to make this work right now. Can you help me out?

A: You can simply add limit 1 to the end of the query and order it regarding the errors count
SELECT DATE_FORMAT(created_at, '%d.%m. %h'),
  COUNT(*) AS errorCount
FROM db.errorData
  GROUP BY DAY(created_at), HOUR(created_at)
  ORDER BY errorCount DESC
LIMIT 1;

A: Adding ORDER BY clause and LIMIT the count of records will fetch your desired result.
SELECT DATE_FORMAT(created_at, '%d.%m. %h') AS created_at,
       COUNT(*) AS errorCount
  FROM db.errorData
 GROUP BY DAY(created_at), HOUR(created_at)
 ORDER BY errorCount DESC, created_at ASC
 LIMIT 1;

And if there are many days with the same errorCount, you have to take a decision to pick a specific day.
My above solution just picks the oldest day with max errors.

A: SELECT
DATE_FORMAT (created_at, '%d.%m. %h'),
          count(*) as errorCount
from
db.errordata
groupby day(created_at)
HAVING errorCount>= ALL (
 SELECT
 COUNT(*) AS errorCount
 FROM db.errorData
 GROUP BY DAY(created_at), HOUR(created_at)
)

I hope this may help you.


text:
Q: Placeholder-Behaviour for Textbox in Silverlight Is there any property for Textbox in Silverlight like placeholder in html input Tag?
I want to provide some hint to the user what this text box takes as input..
For Example:
When the page is loaded there is a string in TextBox like "search here..." and as soon the user clicks into the TextBox the string disappears and it appears again if the user didn't insert something as soon as the user click out this textbox.

A: I made a slight modification/enhancement to Johan's watermark behavior class, because it doesn't account for when the textfield changes due to binding. (i.e. let's say you had:
<TextBox Text="{Binding AccountNumber,Mode=TwoWay}">
    <i:Interaction.Behaviors>
        <Behaviors:Placeholder Text="Enter Account #..." Foreground="Gray" />
    </i:Interaction.Behaviors>
</TextBox>

And then in your view model:
    public string AccountNumber
    {
        get { return _accountNumber; }
        set { _accountNumber = value;
        RaisePropertyChanged("AccountNumber");
        }
    }

Now the behavior updates the watermark if you do something like "AccountNumber = string.Empty" somewhere in your code:
public class Placeholder : Behavior<TextBox>
{
    private bool _hasPlaceholder;
    private Brush _textBoxForeground;

    public String Text { get; set; }
    public Brush Foreground { get; set; }

    protected override void OnAttached()
    {
        _textBoxForeground = AssociatedObject.Foreground;

        base.OnAttached();
        if (Text != null)
            SetPlaceholderText();
        AssociatedObject.GotFocus += GotFocus;
        AssociatedObject.LostFocus += LostFocus;
        AssociatedObject.TextChanged += TextChanged;
    }

    private void TextChanged(object sender,
        TextChangedEventArgs textChangedEventArgs)
    {
        if (string.IsNullOrWhiteSpace(AssociatedObject.Text) &&
            FocusManager.GetFocusedElement() != AssociatedObject)
        {
            if (Text != null)
                SetPlaceholderText();
        }
    }

    private void LostFocus(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrWhiteSpace(AssociatedObject.Text))
        {
            if (Text != null)
                SetPlaceholderText();
        }
    }

    private void GotFocus(object sender, RoutedEventArgs e)
    {
        if (_hasPlaceholder)
            RemovePlaceholderText();
    }

    private void RemovePlaceholderText()
    {
        AssociatedObject.Foreground = _textBoxForeground;
        AssociatedObject.Text = "";
        _hasPlaceholder = false;
    }

    private void SetPlaceholderText()
    {
        AssociatedObject.Foreground = Foreground;
        AssociatedObject.Text = Text;
        _hasPlaceholder = true;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.GotFocus -= GotFocus;
        AssociatedObject.LostFocus -= LostFocus;
    }
}

A: Here is how to do it with a behavior:
http://weblogs.asp.net/jdanforth/archive/2010/09/17/silverlight-watermark-textbox-behavior.aspx