How to separate values in a variable in powershell? - windows

This may sound like a stupid question, but I am trying to separate the values in a variable so that I can cross compare them with another variable to decide what to do within an if statement.
Basically, I want to take the beginning letter of a users username, whatever letter that is, will then be compared to both variable to decide what action to take. So for example if the username is "Josh" the message "Home2" should appear. I'm not sure whether what I'm trying to achieve is possible but any help is appreciated.
$UserName = $env:username
$HomeDriveLetterAK = "\\charlie\home_A-K\$Username"
$HomeDriveLetterAK = "\\charlie\home_L-Z\$Username"
$Home1 = "A, B, C, D, E, F"
$Home2 = "H, I, J, K, L, M"
If ($username.StartsWith($Home1, 1))
{
[System.Windows.Forms.MessageBox]::Show("Home1" , "Status" , 'OK', 'error')
}
ElseIf ($username.StartsWith($Home2, 1))
{
[System.Windows.Forms.MessageBox]::Show("Home2" , "Status" , 'OK', 'error')
}

Alternatively, you can use a Switch:
$username = "John"
Switch -Wildcard ( $username[0] )
{
'[A-F]' { [System.Windows.Forms.MessageBox]::Show("Home1" , "Status" , 'OK', 'error') }
'[G-M]' { [System.Windows.Forms.MessageBox]::Show("Home2" , "Status" , 'OK', 'error') }
'[N-S]' { [System.Windows.Forms.MessageBox]::Show("Home3" , "Status" , 'OK', 'error') }
'[T-Z]' { [System.Windows.Forms.MessageBox]::Show("Home4" , "Status" , 'OK', 'error') }
Default { Write-Output 'Unable to determine "Home" for this user.'}
}

First, make $Home1 & $Home2 arrays, not CSV strings. I'll make parsing everything a lot easier. Then use the ToCharArray() method on the String object that is $username to get the first character, and the -contains operator to compare.
$Home1 = ("A","B","C","D","E","F")
$Home2 = ("H","I","J","K","L","M")
$FirstLetter = $username.ToCharArray()[0];
if ($Home1 -contains $FirstLetter) {
[System.Windows.Forms.MessageBox]::Show("Home1" , "Status" , 'OK', 'error');
} elseif ($Home2 -contains $FirstLetter) {
[System.Windows.Forms.MessageBox]::Show("Home2" , "Status" , 'OK', 'error');
}
BTW, you probably want to fix the variable name in this line too:
$HomeDriveLetterAK = "\\charlie\home_L-Z\$Username"

Related

Retrieve value from json based on key provided using cypress

let expectedKey = 'Student';
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => {
if(expectedKey === 'Student'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.studentCode);
}
if(expectedDKey === 'Department'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.departmentCode);
}
if(expectedKey === 'Paper'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.paperCode);
}
if(expectedKey === 'Results'){
cy.get('app-screen').find('#code-details').should('have.text', appDetails.resultsCode);
}
}
I don't want to use these many if blocks as there will more keys in the future. Instead, I have to pick the required value for studentCode, departmentCode, paperCode, or resultsCode from JSON based on expectedKey. Any help please?
You can access object properties by dot notation (foo.bar) or bracket notation (foo['bar']). In your case, you'll have to ensure expectedKey matches a valid key in your object with assertion before the cy commands.
let expectedKey = 'studentCode';
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => {
expect(appDetails, 'valid key').to.have.property(expectedKey)
cy.get('app-screen').find('#code-details').should('have.text', appDetails[expectedKey]);
}
Assuming that you have the expectedKey inside the cy.readFile(), you can do like this:
Create a custom command at cypress/support/commands.js:
Cypress.Commands.add('codeDetailsText', (expectedKey, appDetails) => {
expectedKeyCode = expectedKey.toLowerCase() + 'Code'
cy.get('app-screen')
.find('#code-details')
.should('have.text', appDetails[expectedKeyCode])
})
In your test just write:
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => {
//Assuming expectedKey value is available here
cy.codeDetailsText(expectedKey, appDetails)
})

Mail merge template : local variable not getting value in if..else

{ MERGEFIELD TableStart:Test}{ SET PLAN {MERGEFIELD Name}="XYZ" "1" "0"}}
{ MERGEFIELD TableEnd:Test }
{ IF { REF PLAN } = "1" "Pass" "Fail"}
In this example always getting result Fail, whether Name is "XYZ" or not.
can anyone suggest further ?
In your case in the SET field you should use IF field to evaluate condition. Please see the following field codes:
{ SET PLAN { IF {MERGEFIELD Name} = XYZ "1" "0"} }
{ IF { REF PLAN } = "1" "Pass" "Fail" }
After executing simple mail merge using the following code:
Document doc = new Document(#"C:\Temp\in.docx");
doc.MailMerge.Execute(new string[] { "Name" }, new string[] { "XYZ" });
doc.Save(#"C:\Temp\out.docx");
The resulting document has the following field codes:
{ SET PLAN XYZ = XYZ "1" "0"} }
{ IF { REF PLAN } = "1" "Pass" "Fail" }
which is properly evaluated with "Pass" text.
Also in MS Word document field whitespaces matters. See the screenshot from MS Word document on my side

Spring data mongodb: Optional #Query parameter no longer works

After upgrading to spring data mongodb 1.10.1, I am getting errors when running queries like:
#Query("{$and :["
+ "{ $or : [ { $where: '?0 == null' } , { 'field1' : ?0 } ] },"
+ "{ $or : [ { $where: '?1 == null' } , { 'field2' : ?1 } ] },"
+ "]}")
public Page<Entity> findAll(String param1, String param2)
Checking the error I see the parameter inside the where clause is not quoted and as I result I get:
org.springframework.data.mongodb.UncategorizedMongoDbException: Query
failed with error code 139 and error message 'ReferenceError:
test_param_value is not defined :
I have seen a few answers here recommending this way of handling optional parameters ((spring-data-mongo - optional query parameters?)) but it no longer works and I cannot seem to find anything in the release change log.
In case anyone else is interested, I managed to find a workaround after checking a similar ticket int the Spring Data project.
It seems the way I was checking for null parameters in the query is not a good practice. This is from a Spring developer comment: "placeholders are not designed to compose keys/values but bind parameters. Beyond that, placeholder use in quoted strings is always problematic in terms of escaping. Using SpEL should suit your needs"
So I ended up using SpEL to do the checks on parameters and it works fine. This is how it looks:
#Query("{$and :["
+ "?#{ [0] == null ? { $where : 'true'} : { 'field1' : [0] } },"
+ "?#{ [1] == null ? { $where : 'true'} : { 'field2' : [1] } },"
+ "]}")
public Page<Entity> findAll(String param1, String param2, Pageable pageable);

Ckeditor plugin - validating a text field

I am creating plugin
I have this piece of code below:
What i am trying to do is make sure the email address they enter is valid.
Just not sure how to stop the onOK if the email address is not valid.
Thanks
This is a code snippet of the plugin
contents : [
{
id : 'info',
label : editor.lang.form.title,
title : editor.lang.form.title,
elements : [
{
id : 'destEmail',
type : 'text',
label : 'Email form results to:',
'default' : 'randy#me.com',
required : true,
accessKey : 'T',
commit : function( element )
{
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (this.getValue().search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
element.setAttribute('id', this.getValue() );
}
}
]
}
]
Please take a look on official sample and validate property. You can write your own validation method at this point.
You can also use one of the available (still not documented in API). You probably want to do something like this (CKEditor 4):
...
validate: CKEDITOR.dialog.validate.regex( /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i, "Please enter a valid email address." );
...
It is also possible to combine existing validators and/or write custom validators:
function customValidator( x, msg ) {
return function() {
var value = this.getValue(),
pass = !!( CKEDITOR.dialog.validate.integer()( value ) && value < x );
if ( !pass ) {
return msg;
}
};
}
...
validate: customValidator( 5, 'Error message when larger than 5.' )
...

How to validate youtube video ids?

I want to validate youtube video ids sbumitted in the URL to one of my sites before accessing the Youtube API, but I don't know what the allowed characters are in such an id. I see people on the net guessing it can contain numbers and characters, but I haven't yet seen an official specification of these video ids.
Is there one?
See this thread for official info.
you can hit this: http://gdata.youtube.com/feeds/api/videos/VIDEO_ID (Page now returns: "No longer available".)
and determine if the video is valid based on response
There's no way you can check the validity of the ID with RegEx, since not all alpha-numeric values are valid ID's.
p.s. i'm pretty sure i saw "dashes" in video ID's
p.p.s. "underscore" is a valid character also: http://www.youtube.com/watch?v=nrGk0AuFd_9
[a-zA-Z0-9_-]{11} is the regex (source), but there's no guarantee that the video will be there even if regex is valid
With v3 of the YouTube API I achieved this by calling:
GET https://www.googleapis.com/youtube/v3/videos?part=id&id=Tr5WcGSDqDg&key={YOUR_API_KEY}
This returns something like:
{
"kind": "youtube#videoListResponse",
"etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/P2cGwKgbH6EYZAGxiKCZSH8R1KY\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [{
"kind": "youtube#video",
"etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/Rgd0_ApwigPcJHVX1Z2SIQ5FJtU\"",
"id": "Tr5WcGSDqDg"
}]
}
So you can just do a check:
if(json.hasOwnProperty('pageInfo') && json.pageInfo.totalResults === 1) {
if(items[0].kind==='youtube#video') {
//valid video ID
}
}
If you are looking for a quicker and more scalable solution I would say to use REGEX with some logging/fallback for errors to be pro-active if YouTube changes their ID in the future.
I've been working with the YouTube API for a while now, dealing with millions of videos. Looping through them, I found this to be the most ideal:
/^[A-Za-z0-9_-]{11}$/
A more detailed example say in PHP:
public static function validId($id) {
return preg_match('/^[a-zA-Z0-9_-]{11}$/', $id) > 0;
}
I solved this issue in the same way Roman recommended. In my helper:
Be sure to include your requires at the top of the file:
require "net/http"
require "uri"
Then:
def validate_id(youtube_id)
uri = URI.parse("http://gdata.youtube.com/feeds/api/videos/#{ youtube_id }")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
%Q{ #{response.code} }
end
Be sure there is no white space between the brackets in "#{response.code}"
Lastly, compare it to the desired response:
def youtube_data(youtube_id)
if validate_id(youtube_id) == "200"
#video is good code
else %Q{ Video is no longer valid }
end
end
Here is a simple implementation in JavaScript:
async function validVideoId(id) {
const url = "http://img.youtube.com/vi/" + id + "/mqdefault.jpg";
const { status } = await fetch(url);
if (status === 404) return false;
return true;
}
console.log(validVideoId('60ItHLz5WEA'));
I just look to see if it is alphanumeric with possible dash or not. You might want to look into oEmbed, you can query YouTube to see if the ID is a valid video or not.
Here is a simple implementation of Roman's approach in PHP:
function validYoutube($id){
$id = trim($id);
if (strlen($id) === 11){
$file = #file_get_contents('http://gdata.youtube.com/feeds/api/videos/'.$id);
return !!$file;
}
return false;
}
And here are the tests:
echo validYoutube('Nv7U6_WhqvQ');
echo validYoutube('Nv7U6_Whqvf');
echo validYoutube('Nv7U6_Whqzz');
I think this works for checking if the video exists or not. Other validation can be done using REGEX as mentioned above. (Implemented using PHP)
public function verifyVideoID($videoID) {
parse_str(file_get_contents("http://youtube.com/get_video_info?el=detailpage&video_id=".$videoID), $info);
if (isset($info['errorcode'])) {
$response = ['response' => false];
return response()->json($response);
} else {
$response = ['response' => true];
return response()->json($response);
}
}
Here's one I came up with from combining info from other answers here and elsewhere:
function validId($id) {
return preg_match('/^[a-zA-Z0-9_-]{11}$/', $id) > 0;
}
function isvalYtube($url) {
$purl = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));
if (!strpos($url, 'youtu.be/') && ($purl != 'youtu.be')) {
if (strpos($url, 'watch') && ($purl = 'youtube.com')) {
parse_str(parse_url($url, PHP_URL_QUERY), $id);
if (!empty($id['v'])) { return(validId($id['v']) ? true : false); } else { return false; }
}
} else {
if (!empty(basename($url))) { return(validId(basename($url)) ? true : false); } else { return false; }
}
}
echo isvalYtube($url) ? 'valid link' : 'invalid link';
First function checks if we're dealing with a valid Youtube video ID.
Second function simply checks if it's a valid youtube VIDEO LINK or VIDEO from PLAYLIST LINK, excluding channel links.
Note: It doesn't determine if it's an active video nor does it check if it exists or not. These functions act merely as Youtube video-link syntax checkers and should be treated as such.
Usage examples:
$url = 'http://www.youtube.com/watch?v=o_QBk4VwnIA';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'http://youtu.be/o_QBk4VwnIA';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'http://www.youtube.com/watch?v=o_QBk4VwnIA&feature=youtu.be';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'https://www.youtube.com/watch?v=Sq3eLdixvCc&list=OLAK5uy_nvaYLo9AG_rZyqkXzYlkJfLjBuZS84bIU';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'valid link'
$url = 'https://www.youtube.com/channel/UCMPQY9gW0hQ9e_-IdQUKEAw';
echo isvalYtube($url) ? 'valid link' : 'invalid link';
//returns 'invalid link'
Simple use this code:
public class HelloWorld{
public static void main(String []args){
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
String video_url = "https://www.youtube.com/watch?v=as3tGTN2u98";
if (video_url.matches(expression)) {
System.out.println("It's valid");
}
}
}

Resources