text:
Q: Need to set default route to upstream DHCP interface on Ubuntu Server 18.04 LTS I'm building an edge router using Ubuntu Server 18.04.03 LTS and need to configure the routing table to define the default route as being the upstream / WAN interface, which gets its IP address and (presumably) the gateway / nexthop address dynamically from the ISP's DHCP server.
A Netplan configuration would seem be the obvious means to do this, and preferable because the configuration would be persistent, but because (according to the Netplan Reference page), the route block's "via" directive (which specifies the gateway IP) is required, Netplan simply isn't up to the task:  One obviously can't specify a dynamically assigned IP address even if specifying an outbound interface is straightforward.  Netplan also provides no obvious means to assure that the route received via DHCP is the default route.  It's as if the Netplan developers simply ignored the entire concept of a default route, which is quite well documented.
This seems to leave ip route, which while volatile and requiring scripting and scheduling to persist nevertheless offers the opportunity to specify a default route by interface alone, so lamentably absent from Netplan.
So, the question is how best to accomplish this.  Can one hack around Netplan's inadequacies, and is the ip route approach viable (albeit via scripting and an associated systemd .service) and perhaps even more robust?
Many thanks for any thoughts.


text:
Q: git merge between different repositories I created a repository with git-svn from a big svn repository (git svn clone).
I've several local commits in my git repository that I don't need to push to svn but I will need to get updates from it.
Now I realized that I don't need the entire svn history in my local repository, since it's using too much space (some Gb) and that I should have used the -r option in the clone command to select a starting point.
I'd linke to start over with a new repository and then merge all the local commits from the old repository, but I'm not sure there is a simple way to do this.
The situation is this:
log of the old repository:

*

*local commit 10

*local commit 9
...

*local commit 1

*svn revision X

*svn revision X-1
...

*svn revision 1

the new repository has just one commit, corresponding to the contend of the revision X of the svn repository.
I tried to use format-patch and apply commands but I'm not sure on how to do this.
Is there a way to do what I need?
Thanks for any help

A: One method is, in your new repository:

*

*to git remote add old your old repository;

*to git fetch old;

*to checkout the branch which contains you want;

*to know the starting point from where your branch was created before the changes;

*and then use git rebase --onto.

When done, git remote rm the old repo and git gc.
See git help rebase for the --onto option: it is very, very useful.

A: You could begin with checking out the revision X from the SVN repository and getting rid of all SVN-related folders. Then git init && git add . && git commit -m "Importing revision X from SVN". Now you've got a Git repository with a snapshot of SVN's revision X.
Afterwards you could use git format-patch to create patches from your old Git repository. git format-patch x.. where x is the commit equivalent to revision X from SVN. It will generate patch files. Execute it in the old Git repository.
Subsequently, in the new repository you can git am all_those_patches.* to get them applied in the new repository.
Cf. man git-am, man git-format-patch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity C# Reflection Get/Set Issue I just can't get this working, so maybe someone can support.
I want to set the value of a specific component field programatically. Here is my code for that (Log_temp is the component):
                FieldInfo info = Log_temp.GetType().GetField("Driver_" + tour.Driver);
                TypedReference infoStructRef = __makeref(Log_temp);

                JSON Tour_Json = JSON.Serialize(tour);

                info.SetValueDirect(infoStructRef, Tour_Json.CreateString());

This works perfectly fine. Now I wanted to not only set the value, but ADD the (string) value to the existing value in the field. Here is what I tried:
            FieldInfo info = Log_temp.GetType().GetField("Driver_" + tour.Driver);
            TypedReference infoStructRef = __makeref(Log_temp);

            JSON Tour_Json = JSON.Serialize(tour);

            info.SetValueDirect(infoStructRef, info.GetValueDirect(infoStructRef).ToString() + Tour_Json.CreateString());

I tried a few other approaches but either I get an error or nothing changes. Could someone help me with this? Thanks a lot!

A: Not a reflection expert but can't you just use GetValue and SetValue
info.SetValue(Log_temp, (string)info.GetValue(Log_temp) + Tour_Json.CreateString());


text:
Q: Random int with no repeat in c++ I am making a quiz application.
All the questions are strored in table and every question means one row. Every row is an int variable.
Program prints 3 random questions from 5 stored questions with this code:
i = rand() % 5 + 1;

i means a row in table, so it randomly chooses one row and question and print it. It all i labeled as "QUESTION" and in the end there is a code:
goto QUESTION;

Which makes the program choose the question once again.
What code should I implement more to make the program NOT TO choose questions already choosen?

A: After selecting the first question, store the question number in an array.
For the next question, again apply the same technique of using rand() to find the next question. But check if it matches with the value of row already stored in the array. If the question number matches, keep on applying the rand() function to get new question number until the question number is different from the first. Once you get the different question, update the array.
Similarly, do it for the third question as well
Hope it helps!!!


text:
Q: I want to make EditText hint to get in centre. Android studio 2.3.1 I have given android:layout_gravity="center", still unable to get it in center.
Please give me solution in XML itself. I am a beginner, so please give simple solution so that I can understand, please bear with me even if you found this so silly.Thank you.

A: Try android:gravity="center"
<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center" />

A: See my updated answer:
    <EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
/>


text:
Q: Positioning item in page from bottom to top I want to show item of a page from bottom to top. Like in chatting or messaging last item is showed in bottom then rest followed to top. Here is an example:

.chart div {
  font: 10px sans-serif;
  background-color: steelblue;
  padding: 3px;
  margin: 1px;
  color: white;
  display: inline-block;
  vertical-align: bottom;
}

          10

            15

            20

            25

            30

Here I want, it will show from 10 to 30 bottom to top anything to do with CSS.
Thank you in advance.

A: This can be VERY easily achieved with CSS flexbox. You may have to add some vendor prefixes, but essential it is done with these 2 lines of code to the parent .chart (You also need to add width: 100% to the children)
CSS:
.chart  {
  display: flex;
  flex-wrap:wrap-reverse;
}
.chart div {
  width: 100%;
}

This will make the items show in reverse. Here is a working fiddle: https://jsfiddle.net/vxtqfqw9/5/
If you want to learn more about the awesome power of flexbox, and how to harness it, I wrote an article that has 2 very helpful resources. :)
http://www.joshuasanger.ca/so-long-floats/

A: You can do it using jquery like below. First take all div in .chart as array and then reverse the array. After that replace the contents of .chart with the array.

var item = $('.chart div').toArray().reverse();
$('.chart').html(item);
.chart div {
    font: 10px sans-serif;
    background-color: steelblue;
    padding: 3px;
    margin: 1px;
    color: white;
    display: inline-block;
    vertical-align: bottom;
}

        10

        15

        20

        25

        30


text:
Q: UITableView Rows Height After Loading Cells I have UITableView that contains 4 different types of customized cells in storyboard. Each cell has customized UILabels which get variable amount of text data from backend. I am struggling with making the cells resizing correctly. I would really want to change the height of each cell but I can not use heightForRowAtIndexPath because it is called before cellForRowAtIndexPath, but the height is actually calculated within each customized cell.
I tried writing in each cells' height into an array while the UITableView is loading, then just reloading it all over again once, but no effect. I tried using CGFloat rowHeight = UITableViewAutomaticDimension with no success either. The customized labels in each cell definitely grow with text which I see when I just statically change row height to higher numbers. So, I would need somehow my labels to push on rows to make them grow, not sure.
Different similar posts on stackoverflow that I found did not help.

A: The issue was that I needed to set up top and bottom constraints to the ContentView and NOT to the cell itself in the storyboard.

Label -> ContentView top and bottom constraints need to be set up. And then UITableViewAutomaticDimension specified in viewDidLoad:
self.tableView.rowHeight = UITableViewAutomaticDimension;

estimatedRowHeight should be set too. For example:
self.tableView.estimatedRowHeight = 76.0f;

A: First Method called is:
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath

Second:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Then:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

set a break point in the above methods and test it. So if you want to preset the height use estimatedHeightForRowAtIndexPathmethod.


text:
Q: How to display an uploaded image (both from drag and drop and file upload from computer)? I am trying to display an uploaded image using jquery fileupload. I want to support both drap and drop and normal file uploading from computer. However, i can only display files that are dropped. I want the uploaded image to be shown in the div #uploadedImg after it gets uploaded. What am I doing wrong?
Here is my jsfiddle (the code does not fit in a code snippet because I could not find the cdn for jquery upload): http://jsfiddle.net/ja5q7u0x/7/

A: So this is what I had to do,
1. In your fileupload function defination you have not mentioned the input id. Line#1216
fileInput: '#up1',

*In your add function look at line#1221 - i made it change to expect value from input field

var dataTransfer =  e.originalEvent.dataTransfer|| e.originalEvent.target;
Just for my convinience i defied an id for input type=file Line#1261
Here is fixed code.
http://jsfiddle.net/ja5q7u0x/22/


text:
Q: How to redirect domain.com to www.domain.com with Nginx? I want to redirect domain.com to www.domain.com on my Nginx server. But me configuration does not work and displays the error message in the internet browser :

The page is not redirected correctly

I added this line to do the redirection :
return 301 $scheme://www.s1biose.com$request_uri;

How to correct this error ? Here is my configuration :
server {
    #listen 80;
    #listen [::]:80 ipv6only=on;
    server_name s1biose.com www.s1biose.com;
    return 301 $scheme://www.s1biose.com$request_uri;
    root /var/www/www-s1biose-com/web;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    location ~ ^/sites/[^/]+/files/.*\.php$ {
        deny all;
    }

    location ~* ^/.well-known/ {
        allow all;
    }

    location ~ (^|/)\. {
        return 403;
    }

    location / {
        try_files $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    }

    location ~ ^/sites/.*/files/styles/ {
        try_files $uri @rewrite;
    }

    location ~ ^(/[a-z\-]+)?/system/files/ {
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        try_files $uri @rewrite;
        expires max;
        log_not_found off;
    }

    listen [::]:443 ssl http2 ipv6only=on;
    listen 443 ssl http2;
    ssl_certificate /etc/letsencrypt/live/s1biose.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/s1biose.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

server {
    if ($host = www.s1biose.com) {
        return 301 https://$host$request_uri;
    }

    if ($host = s1biose.com) {
        return 301 https://$host$request_uri;
    }

    listen 80;
    listen [::]:80;
    server_name s1biose.com www.s1biose.com;
    return 404;
}

A: Your "return 301" line is being run whether the site is accessed using www or not, causing the browser to be redirected endlessly. To only return a 301 for site.com, remove the "return 301" from your main server block, only have it listen for www.site.com, and create a separate server block for site.com.
server {
    #listen 80;
    #listen [::]:80 ipv6only=on;
    server_name www.s1biose.com;
    root /var/www/www-s1biose-com/web;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    location ~ ^/sites/[^/]+/files/.*\.php$ {
        deny all;
    }

    location ~* ^/.well-known/ {
        allow all;
    }

    location ~ (^|/)\. {
        return 403;
    }

    location / {
        try_files $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    }

    location ~ ^/sites/.*/files/styles/ {
        try_files $uri @rewrite;
    }

    location ~ ^(/[a-z\-]+)?/system/files/ {
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        try_files $uri @rewrite;
        expires max;
        log_not_found off;
    }

    listen [::]:443 ssl http2 ipv6only=on;
    listen 443 ssl http2;
    ssl_certificate /etc/letsencrypt/live/s1biose.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/s1biose.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

server {
    # redirect to www
    listen [::]:443;
    listen 443;
    ssl_certificate /etc/letsencrypt/live/s1biose.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/s1biose.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    server_name s1biose.com;
    return 301 https://www.s1biose.com$request_uri;
}

server {
    # force https
    listen [::]:80 ipv6only=on;
    listen 80;
    server_name s1biose.com www.s1biose.com;
    return 301 https://www.s1biose.com$request_uri;
}


text:
Q: Why it doesn't allow to replace the string within IF condition {% if ('Desk Clock' in product_flags) %}
      {{product_flags|replace({"Office & Awards > Office > Clocks": "Office & Awards > Office > Desk Clocks"})}}
{% else ('Wall Clock' in product_flags) %}
      {{product_flags|replace({"Office & Awards > Office > Clocks": "Office & Awards > Office > Wall Clocks"})}}
{% endif %}

Getting this error

Unexpected token "punctuation" of value "(" ("end of statement block" expected)

New to Twig, could you please help me out?


text:
Q: Can't handle successful 204 response and correctly map failing response using RestKit I am writing an iOS app that interacts with a service to update a user's profile. In order to update a user's name, the iOS app PUTs a request with a body of the following format:
 {"name" : {"first" : "FIRSTNAMEGOESHERE", "lastName":"LASTNAMEGOESHERE"}}

In the case where the request body is valid (i.e. both a first and last name are provided), the service returns a 204 (No Content) status code and an empty response body.
In the case where the request body is invalid (e.g. first name is missing, etc.), the service will return a status code of 400 and a response body in the following format:
{"code":"ERRORCODEHERE"}

The iOS app is using RestKit and I have been unable to figure out how to get it to both properly handle the success and failure case. If I use this:
- (void)updateUserName
{
    RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[[NSURL alloc] initWithString:@"http://someqaserver:8080"]];
    [objectManager setRequestSerializationMIMEType:RKMIMETypeJSON];

    RKObjectMapping *userMapping = [RKObjectMapping requestMapping];
    [userMapping addAttributeMappingsFromDictionary:@{@"firstName" : @"first", @"lastName" : @"last"}];

    RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:userMapping objectClass:[OurUser class]                                       rootKeyPath:@"name"];

    [objectManager addRequestDescriptor:requestDescriptor];

    [objectManager putObject:[OurUser getCurrentUser]
                   path:@"/mobile/profile/name"
                   parameters:nil
                   success:^(RKObjectRequestOperation *operation, RKMappingResult *result)
                   {
                     NSLog(@"Success!");
                   }
                   failure:^(RKObjectRequestOperation *operation, NSError *error)
                   {
                     NSLog(@"Fail!");
                   }];
}

This obviously does not work for the error case, but it does successfully execute the success block in the case where a 204 is returned from the server.
If I add the following code before calling putObject, the error handling works, but now the valid 204 case is deemed a failure:
    RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[ServiceError class]];
    [errorMapping addAttributeMappingsFromDictionary:@{@"code" : @"errorCode"}];
    RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)];
    [objectManager addResponseDescriptor:errorDescriptor];

This seems to happen since the accepted HTTP status codes are now set to those of the response descriptors provided and 204 is not one of them (or maybe it's something else?)
How can I get it so that:
1.) if a 204 is returned, it's seen as a success
2.) if a 4XX is returned, it's seen as a failure and the error code is properly mapped to my ServiceError object?
Thanks in advance for any help you can provide.

A: The problem was solved by also adding a response descriptor to handle the 204:
RKResponseDescriptor *successResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[RKObjectMapping mappingForClass:nil]
                                                                                method:RKRequestMethodPUT
                                                                                pathPattern:nil
                                                                                keyPath:nil
                                                                                statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[manager addResponseDescriptor:successResponseDescriptor];

A: code 204 is not an error, any 2xx status is deemed a success. 204 means 'no content', which is a perfectly valid response.
If you expect restkit to treat it as an error, make sure you throw a 3xx, 4xx or a 5xx error. In your case you are using a RKStatusCodeClassClientErrorm which would suggest you should throw a 4xx error.
See wikipedia for a complete list of error codes


text:
Q: What is the best way to store the image in the memory of app? I'm using sqlite db in my app and now I would like to allow user customize the background image make them able to select one from their gallery.
Should I just store the path to image and simpy refer to it every time or should I some how transfer the image to some text and store it completely in my db? The second option prevents in case of picture being deleted from gallery. But I would like to know the most appropriate way of doing that.

A: SQLite has a cursor limit of 1Mb. So, you will probably not be able to store it completely in the DB, when you go to to request it will probably be truncated. Store the path to the image in the database table, and access it that way.

A: You wouldn't store it as text. Store it as blob to your database. In my opinion this is the way to go (if you use SQLite anyway).
If you have large images then store the path to your storage and not the image to the database.

A: I think it would be better to save only the path of the background, you won't be limited by the size of the image

A: In my opinion, the best way to save the customized background image is copy it into the internal storage (private storage) of your application. If you store only the path of the file, then file cannot be available once the user deleted that.
The official docs saying about the internal storage is:

*

*It's always available.

*Files saved here are accessible by only your app by default.

*When the user uninstalls your app, the system removes all your app's files from internal storage.


text:
Q: How to set CSS rule for a DIV in a LI? I have a list of results from a query. That list will be displayed like that:

addr = "+detail[3]+"

Interface = "+detail[0]+"

time = "+detail[1]+"

name = "+detail[2]+"

my CSS :
.Redli
{
   list-style-position: outside;
   list-style-image:url("img/liimg3.gif");
}

.redmarkerinfo
{
   font-size:16px;
   font-weight:600;
   width:inherit;
   height:150;
   text-align:left;
   line-height: 24px;
   padding-top: 20px;
   padding-bottom: 20px;
   color:#333;
   background-color:#ffffff;
   font-family:"Times New Roman", Times, serif;
}

The problem is that my Redli rule can't work ???can someone explain why ??

A: You must start your list with the ul tag and assign the class Redli to it

..

::

A: AS far as I know, you can't put a div inside a UL like that, try this:

addr = "+detail[3]+"

Interface = "+detail[0]+"

time = "+detail[1]+"

name = "+detail[2]+"

A: Do not put
 befor
. Better to put it after and place a class on

Here's my code:

addr = "+detail[3]+"

Interface = "+detail[0]+"

time = "+detail[1]+"

name = "+detail[2]+"


text:
Q: Nuxt.js - How to have separate layout? In my default layout I have header and footer for every page. But in error pages I need a full page without header and footer. So I made another layout and I'm calling it in the export default section. But it's still have header and footer.
default.vue

<template>

    <app-header></app-header>
    <nuxt />
    <app-footer></app-footer>

</template>

error.vue

<template>

Page not found

An error occurred

    <nuxt-link to="/">Home page</nuxt-link>

</template>

fullpage.vue

<template>

    <nuxt />

</template>

Where I'm wrong?

A: You can do like this
    1 - create a layouterror.vue file inside layouts folder (Put nothing inside just the basic code).

    <template>

    </template>

    2 - create a error.vue file inside layouts folder.
    3 - and pass your error file a layout like this =>

   export default {
    layout: 'layouterror'
   }

Maybe its help
Thanks !

A: ON Your Nuxt Project Folder called layouts, Create a file named error.vue and it will automatically detect all your 404 error which is page not found.

error.vue

<template>

Oops, something went wrong!

Back to safety!

</template>


text:
Q: Accessing postgres that is hosted on Heroku So I've deployed my project into Heroku using Gitlab CI/CD using following file:
image: maven:3.8.6-openjdk-18

services:
  - postgres:latest
variables:
  POSTGRES_DB: postgres
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: password
  POSTGRES_HOST_AUTH_METHOD: trust

stages:
  - build
  - deploy

build:
  stage: build
  script:
    - mvn package -Pprod
  artifacts:
    paths:
      - target/cinema.jar

deploy:
  stage: deploy
  image: ruby:latest
  script:
    - apt-get update -qy
    - apt-get install -y ruby-dev
    - gem install dpl
    - dpl --provider=heroku --app=cinema --api-key=$HEROKU_API_KEY
  only:
    - main

I would love to connect from this place to postgres and give user all of the needed privileges on all tables to provided user.
Can't wrap my head around it, in order to make it work.
Thank you for any help!


text:
Q: Why am I getting TypeError: cannot unpack non-iterable builtin_function_or_method object? I am new to coding and I am starting with python. I am trying to make a method that will take an equation and solve for an unknown variable.
It works for just one equation (one operator) but didn't work when I tried to make it return value based on an operator.
This worked:
def solveforx(y):
    x, add, num1, equal, num2 = y.split()

    # convert the strings into ints
    num1, num2 = int(num1), int(num2)
    # convert the result into a string and join it to the string "x = "
    return "x = "+ str(num2 - num1)

print(solveforx("X + 5 = 9"))

This didn't:
def solveforx(y):
    x, op, num1, equal, num2 = y.split

    num1, num2 = int(num1), int(num2)

    if op == "+":
        return "x = " + str(num2 - num1)
    elif op == "-":
        return "x = " + str(num1 + num2)
    elif op == "*":
        return "x = " + str(num2/num1)
    elif op == "/":
        return "x = " + str(num1*num2)
    else:
        return "wrong operator"

print(solveforx("X + 5 = 9"))

TypeError: cannot unpack non-iterable builtin_function_or_method object

A: You forgot the parentheses after y.split, so you tried to unpack the method split instead of its actual result.
It should be
x, op, num1, equal, num2 = y.split()


text:
Q: Xamarin forms Entry with suggestion items in a listview popup when typing the text in it I have an Entry field. And a list of items which I'm fetching it from Database.
I need to show the list popup when typing in the Entry with those items from DB and filter those based on the string.
If the user finds the name in the list, he can select the one and it should display in the Entry followed by space and the user can enter one more string. (similar to entering email addresses in Gmail). If the user doesn't find the name in the list, he can type the particular name and after hitting space he should be able to enter the new string.
I found there is nuget packgae from SyncFusion. Can we achieve this without using any third party libs?

A: You can place listview below of the entry:
In XAML:
<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="40" />
    <RowDefinition Height="40" />
</Grid.RowDefinitions>
        <Entry
            x:Name="entryMain"
            Grid.Row="0"
            TextChanged="OnEntryChanged" />
        <ListView
            x:Name="lstSuggest"
            Grid.Row="1"
            IsVisible="False"
            ItemTapped="ItemSelected"
            SeparatorVisibility="None" />
</Grid>

Code Behind:
lstSuggest.ItemsSource = _suggestion;

private void OnEntryChanged(object sender, TextChangedEventArgs e)
{
    if (entryMain.Text != null && lstSuggest.ItemsSource != null)
    {
        if (_suggestion.Any(x=> x.StartsWith(e.NewTextValue)) && entryMain.Text != string.Empty)
        {
            var items = new List<string>();

            foreach (var item in _suggestion.FindAll(x => x.StartsWith(e.NewTextValue)))
            {
                items.Add(item);
            }

            lstSuggest.ItemsSource = items;
            lstSuggest.IsVisible = true;
        }
        else
        {
            lstSuggest.IsVisible = false;
        }
    }
}

private void ItemSelected(object sender, EventArgs args)
{
    if (((ListView)sender).SelectedItem == null)
        return;

    entryMain.Text = lstSuggest.SelectedItem.ToString();
    ((ListView)sender).SelectedItem = null;
    lstSuggest.IsVisible = false;
}

In addition, if you want remove listview horizontal scrollbar visibility, you can create custom control.
Bonus: Android default https://learn.microsoft.com/tr-tr/xamarin/android/user-interface/controls/auto-complete

A: I would suggest to use EntryAutoComplete package
The usage is quite simple, just add the NuGet to your solution, then, your page just:
Reference the assembly namespace
xmlns:customControl="clr-namespace:EntryAutoComplete;assembly=EntryAutoComplete"

And then,
<customControl:EntryAutoComplete
            VerticalOptions="CenterAndExpand"
            Placeholder="Enter country..."
            ItemsSource="{Binding Countries}"
            SearchText="{Binding SearchCountry}"
            SearchMode="{Binding SearchMode}"
            MaximumVisibleElements="5"/>


text:
Q: Why isn't my javascript function working My function is pulling information from an api and then putting it into the table. for some reason this function is not working.
this is my function:
function getPayInfo(socCode) {
    var apiurl = "http://api.lmiforall.org.uk/api/v1/ashe/estimatePay?soc=";
    var apicall = apiurl + socCode;
    $.get(apicall, function(data) {
        $("#Pay tbody").html("");
        $.each(data.years, function(i, e) {
            var tablerow = $("

");
            tablerow.append("" + e.year + "	");
            tablerow.append("" + e.estpay + "	");
            $("#Pay tbody").append(tablerow);
        });
    });
}

and this is the table i am putting it into:

Pay Information

Pounds per Week

                Year
                Estimate Pay

i expected it to return a year and data value into the table. if you take the url in the function and add a certain 4 fuigure value(the socCode) to the end it will give the data online this should then be returned to the table body

A: You are not executing the function getPayInfo. So maybe that is why the code is not giving you any output.
You can try to get the errors from the Inspector of your browser in the Networks tab.
If the event is trigerring, and the request is being sent, it will be logged there and there you can see the HTTP message of the page, whether it is a 404 or the 500 which is causing this error.
Otherwise, I think that the element selectors aren't properly selected.


text:
Q: Delay showing div I have a floating/static toolbar that I would like to delay until the visitor has scrolled down the page some distance. I have tried using delay() and scroll() functions, but without success. It's possible I'm on the right trail, but incorrect syntax.
Say, for example, this is my toolbar (below)...what would I need in the script to delay showing it (javascript/jquery)? And, while we're at it, any way to fade it open?

A: The JQuery script below would reveal the toolbar div when the user scrolls the page.
NOTE: The page must be scrollable for the event to fire so the page content must be higher taller than the window.

This script would fade the toolbar div in after a pre-set delay.

Place either of the scripts directly above the closing  tag of your page and ensure you have a link to the JQuery library in your  section


text:
Q: Lightning Experience configuration converter doesnt show VF pages after Scanning org Its shows this message after scan is complete instead of showing list of vf pages.
Your org doesn't have any Visualforce pages, or none of your Visualforce pages fit the criteria for this list view. Try a different list view. Or, if you ran your scan in a sandbox org, try running it again in your production org.

A: The visualforce reports look for those visualforce pages which have been used by any user in your org in the last 90 days. If you have any visualforce page which has not been used in the last 90 days, the tool will not consider them.
To get the correct report, Run it for your production org. Also, you will get the report in CSV format to your mail.


text:
Q: Passing stdout twice to the same command Hello I am interested in how to pass stdout twice to the same command...
For instance, If I run the following:
seq 5 >a
tac a >b
paste a b

then I get:
1       5
2       4
3       3
4       2
5       1

The following also deliver the same result:
paste <(seq 5) <(seq 5 |tac)

or
seq 5 | paste - <(seq 5 |tac)

I want to use seq 5 only once - perhaps similar to these attempts, which do not work:
seq 5 | paste - <(tac -)

or
seq 5 | tee >(tac 1>&3) | paste - >(3>&1 cat)

I expect some kind of file descriptor manipulation or further process substitution magic will do the trick but I am having trouble getting there.

A: There is no way to duplicate a single stream, short of using a tool such as tee. A common arrangement is to use a temporary file.
#!/bin/bash
t=$(mktemp -t pastepaste.XXXXXXXXXX) || exit
trap 'rm -f "$t"' ERR EXIT
tee "$t" |
paste - <(tac "$t")

A: You could do something like this:
rootdir=$(mktemp -d)  # Strictly speaking not needed, but we create us a tempdir
mkfifo "$rootdir/pipe"  # create a named pipe
seq 5 | tee "$rootdir/pipe" | paste - <(tac "$rootdir/pipe")
# We could now tee (split) output into that pipe
rm -Rf "$rootdir"  # cleanup

You could also have extra file descriptor involved, but you'd still need something to underpin it with to connect both ends of the stream. Problem is, while you could multiplex the output, on a newly created problem you would still only have one input stream (when piping commands connected to stdout of the preceding process at that). A second transmission path must be added.
tmpfile=$(mktemp); exec 3<>"$tmpfile"; rm "$tmpfile"

Creates a temporary file and opens fd 3 for reading/writing. Once we have a file descriptor, we no longer need name for that file in the file system.
seq 5 | tee /proc/self/fd/3 | paste - <(tac </proc/self/fd/3)

We still use tee to split the output between stdout and fd 3. File descriptors are inherited by child process, so we can refer to them with /proc/self/ (also from perspective of tee and tac).

A: The problem you're facing is that each element in a pipeline is executed in a separate subshell, so any newly-redirected FDs by the elements aren't reflected in the parent shell, which is doing all the I/O coordination.
Some other guru might come up with a magic redirect incantation to solve this problem at the parent level, but for clarity, I'd suggest named pipes (a.k.a. FIFOs) instead. Since they exist outside of the shell environment, they're visible to all pipeline elements at all times.
More importantly, with proper naming, "connecting the pipes" becomes a relatively bug-free process, especially as your pipeline "network" gets more complex. No guessing games about which FD carries which output.
For your example, this works seamlessly:
#!/bin/bash
# Make a temp dir...
tmpd=$(mktemp -d)
# ...and clean it up automatically
trap 'rm -fr $tmpd' EXIT

# Create the FIFO...
mkfifo $tmpd/tac.fifo
# ...and PROFIT!
seq 5 | tee >(tac >$tmpd/tac.fifo) | paste - $tmpd/tac.fifo

Further Reading:

*

*mkfifo(1)

*mktemp(1)

A: A simple, symmetrical example would be to use two named pipes.
 trap 'rm p1 p2' ERR EXIT
 mkfifo p1 p2

Then you can have tac filter the output of tee into p2
 seq 5 | tee p1 <(tac > p2) > /dev/null &
 paste p1 p2

or filter the contents of p2 before passing to paste.
seq 5 | tee p1 p2 > /dev/null
paste p1 <(tac p2)


text:
Q: Creating a div box through javascript I am trying this code but it's not working.please help. in this I just want to create a div block and change its properties?
<html>
<head>
<script >
function create()
{
l=document.createElement('div');
l.id='10';
l.style.position='absolute';
l.style.top='100px';
l.style.left='200px';
l.style.height='100px';
l.style.width='100px';
l.style.backgroundColor='yellow';
l.style.zIndex='100';
}
</script>
</head>
<body>
<input type="submit" name="cssandcreate" id="cssandcreate" value="css"  onclick="create()"/>
</body>
</html>

A: You can't just create element and wait till it will appear, you should also add it to the DOM .
Example :
document.body.appendChild(l);

A: Try something like this
 function createDiv() {
        var divTag = document.createElement("div");
        divTag.id = "div1";
        divTag.className = "divdrag";

        par = document.getElementById('stage');

        par.insertBefore(divTag, par.firstChild);
    }

    createDiv();

CSS
.divdrag{
          width:688px;
          position:relative;
          margin-top:20px;
          display:inline-block;
          height:50px;
            border: 1px solid red;

         }
        .divdrag:hover{
        -webkit-box-shadow: 1px 1px 3px #999;
        box-shadow: 1px 1px 3px #999;
        border:0.7px dotted;
            }

Take a look at fiddle http://jsfiddle.net/3ZPEy/1/

A: HTML
<input type="button" name="cssandcreate" id="cssandcreate" value="css"  onclick="create()"/>

JS
function create() {
    var l = document.createElement('div');
    l.id = '10';
    l.style.position = 'absolute';
    l.style.top = '100px';
    l.style.left = '200px';
    l.style.height = '100px';
    l.style.width = '100px';
    l.style.backgroundColor = 'yellow';
    l.style.zIndex = '100';
    document.body.appendChild(l);
}


text:
Q: How can I call javascript functions and pass values from XAML/Silverlight? I'm creating silverlight without Visual Studio.  I just have raw html, XAML, and js (javascript).
What I want to do is pass values from the XAML to the javascript.  I can call and activate javascript functions from XAML.  See below.  The canvas element has a mouse left button up event that calls LandOnSpace in the javascript.
But how would I call ShowMsg?  Or more accurately, how would I pass values to that call?  Normally in javascript you can just go: ShowMsg(500, 700, "you owe us money");
But when I try that in the xaml code, it breaks something.  I believe it complains that the javascript function doesn't exist.

        <Canvas x:Name="btnLandOnSpace" Background="LightGreen" MouseLeftButtonUp="LandOnSpace"
            Cursor="Hand" Canvas.Top ="0"  Width="70" Height="50">
            <TextBlock Text="LandOnSpace"  />
            </Canvas>

function LandOnSpace(sender, e) {  //on server
if (!ShipAnimateActive && !blnWaitingOnServer) {
    blnWaitingOnServer = true;
    RunServerFunction("/sqgame/getJSLLandOnSpace");
        ShowWaitingBox();
        };
else {
    alert('Waiting on server.');
};
}

function ShowMsg(SintCost, SintRent , SstrChoiceText) {
blnPayChoice = true;
intCost = SintCost;
intRent = SintRent;
strChoiceText = SstrChoiceText;   }

A: If you want to call javascript functions from Silverlight 2.0 you can use HtmlPage in the System.Windows.Browser namespace.
var param = new object[] {"some parameter"};
HtmlPage.Window.Invoke("myfunc",param);

However based on your example above it seems that you are using Silverlight 1.0 where your event Handler is in Javascript and not in C# or VB.
You can move to Silverlight 2.0. The server that you use to server pages doesn't prevent you from using Silverlight 2.0 (or 3.0).
You can perfectly run a Silverlight 2.0 application on Google App Engine.
To start developing in 2.0 download the Silverlight 2 Tools here: http://www.microsoft.com/downloadS/details.aspx?familyid=C22D6A7B-546F-4407-8EF6-D60C8EE221ED&displaylang=en
And for some reference on how to communicate between the Silverlight managed code and the Javascript inside the browser you can check this page: http://msdn.microsoft.com/en-us/library/cc645076(VS.95).aspx

A: The right way to do this is to fire the js handler with the default parameters.  Then, from Javascript, use the Silverlight 1.0 model to navigate into the XAML.  See the Silverlight 1.0 docs.  See the FindName method.


text:
Q: Einstein notation • Cartesian reference frame • Cartan, theory of spinors I'm having a problem understanding Cartan's notation in theory of spinors §2. Here are the definitions:

Set x to $3 \\ 4$ so the length is 5, then set as a simple test basis $\eta_1$ to $1 \\ 1$ and $\eta_2$ to $0 \\ 1$.
$u^1$ I set to 3 and $u^2$ to 1. The scalar product of $\eta_1 . \eta_2$ is 1. If I run over the $u^i u^j$ successively and independently, that gives me $$3 \quad 3 \\ 3 \quad 1 \\ 1 \quad 3 \\ 1 \quad 1$$, which sum to 16, not 25.
If changing basis is supposed to change length, then I don't understand why Cartan's $$u^i u^j \eta_1 . \eta_2$$ is a good definition of fundamental form.

A: Let $x = (3, 4) = 3e_1 + 4 e_2$, with square length $3^2 + 4^2 = 25$. Now express $x$ in the new basis of $\eta_1 = (1, 1)$ and $\eta_2 = (0, 1)$, and we get that
$$ x = (3, 4) = (3, 3) + (0, 1) = 3 \eta_1 + \eta_2.$$
Therefore in the expression $x = u^i\eta_i$ we have $u^1 = 3$ and $u^2 = 1$, as you found.
Now consider the fundamental form $g_{ij} = \eta_i \cdot \eta_j$, which we can write as a matrix
$$ g = \begin{pmatrix} g_{11} & g_{12} \\ g_{21} & g_{22} \end{pmatrix} = \begin{pmatrix} 2 & 1 \\ 1 & 1\end{pmatrix}.$$
Evaluating $\Phi$ we get
$$ \begin{aligned}
\Phi
  &= g_{ij} u^i u^j\\
  &= g_{11} u^1 u^1 + g_{12} u^1 u^2 + g_{21} u^2 u^1 + g_{22} u^2 u^2 \\
  &= 2 \cdot 3 \cdot 3 + 1 \cdot 3 \cdot 1 + 1 \cdot 1 \cdot 3 + 1 \cdot 1 \cdot 1 \\
  &= 25.
\end{aligned}
$$


text:
Q: How do I reference the local ruby in a hash-bang executable? I have a Ruby executable (it's a bundler binstub) which starts with
#!/usr/bin/env ruby

On my server I have Ruby 193 installed via RVM.
$ which ruby
-> /home/dtuite/.rvm/rubies/ruby-1.9.3-p0/bin/ruby

On my local machine, I also have Ruby installed via RVM, but in a different location (obviously!)
$ which ruby
-> /Users/davidtuite/.rvm/rubies/ruby-1.9.3-p0/bin/ruby

When I try to run this executable on the server I get an error
/usr/bin/env: ruby: No such file or directory

Is there a way I can reference the locally available ruby in the hash-bang so that the same script will execute on both the server and the local machine?

A: Try rvm-auto-ruby - it is explained in a somewhat different context in RVM's Textmate documentation.


text:
Q: Defining strict_real_policies for reals with a comma decimal character I would like to create a custom policy derived from strict_real_policies that will parse reals, such as "3,14", i.e. with a comma decimal point as used e.g. in Germany.
That should be easy, right?

A: #include <iostream>
#include <string>

#include <boost/spirit/home/x3.hpp>

template <typename T>
struct decimal_comma_strict_real_policies:boost::spirit::x3::strict_real_policies<T>
{
    template <typename Iterator>
        static bool
        parse_dot(Iterator& first, Iterator const& last)
        {
            if (first == last || *first != ',')
                return false;
            ++first;
            return true;
        }

};

void parse(const std::string& input)
{
    namespace x3=boost::spirit::x3;

    std::cout << "Parsing '" << input << "'" << std::endl;

    std::string::const_iterator iter=std::begin(input),end=std::end(input);
    const auto parser = x3::real_parser<double, decimal_comma_strict_real_policies<double>>{};
    double parsed_num;

    bool result=x3::parse(iter,end,parser,parsed_num);
    if(result && iter==end)
    {
        std::cout << "Parsed: " << parsed_num << std::endl;
    }
    else
    {
        std::cout << "Something failed." << std::endl;
    }
}

int main()
{
    parse("3,14");
    parse("3.14");
}


text:
Q: Laravel Connection could not be established with host smtp.office365.com for outlook, it neither works in localhost nor in production server.
but for testing purpose, I used Gmail in localhost and it worked.
but again in production, it didn't work.
MAIL_DRIVER smtp
MAIL_HOST smtp.office365.com
MAIL_PORT 587,
MAIL_USERNAME ********,
MAIL_PASSWORD ********,
MAIL_ENCRYPTION tsl

A: Just set up correct Configuration:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.office365.com
MAIL_PORT=587
MAIL_USERNAME= //your username
MAIL_PASSWORD= //your password
MAIL_ENCRYPTION=tls

After .env edit must be clear cache: php artisan config:cache

A: in my case, change port 587 to 25 work fine.
Microsoft Documentation

A: Try
'driver' => env('MAIL_DRIVER', 'sendmail'),
'host' => env('MAIL_HOST', 'localhost'),

it works.


text:
Q: How to check if an entry already exists when posting in Dynamo DB with AWS Amplify In an Amplify w/ graphql project, I have a conversation schema which both members of the conversation saved in an array. When creating a conversation, I only want one conversation to exists between two users. So I want the creating of the conversation entry to fail when a conversation already exists.
When creating the mutation, I tried to use the condition input to let the query fail when the condition is false. But I have not found a solution to check the members array.
Any advice on using the conditions input is appreciated!
type Conversation
  @model {
  id: ID!
  members: [String!]!
  ...
}

const createConversationInput: CreateConversationInput = {
  members: [userOneId, userTwoId],
  ...
};

const createConversationMutation = (await API.graphql({
  query: createConversation,
  variables: {
    input: createConversationInput,
    condition: {
      and: [
        { not: { members: { contains: userOneId } } },
        { not: { members: { contains: userTwoId } } },
      ],
    },
  },
  ...
})) as { data: CreateConversationMutation };


text:
Q: CAUTION: provisional headers are shown Привет...
У меня проблема в Chrome.
Запрос вроде не отправляется и в консоли на этом пакете выводится это сообщение.
Что может означать это и по каким причинам:

*

*Запрос не отправляется?

*Ответ не приходит?

*Сервер не  генерирует ответ на вопрос?

A: Какое-то расширение блокирует запрос.
Попробуйте запустить Chrome в режиме Инкогнито (Ctrl + Shift + N). Дополнения будут отключены.

A: Ресурс может блокироваться расширением

Сообщение есть, потому что запрос на получение этого ресурса никогда
  не был выполнен, поэтому отображаемые заголовки не являются
  реальностью. Как пояснялось в проблеме, на которую вы ссылались,
  реальные заголовки обновляются, когда сервер отвечает, но нет ответа,
  если запрос был заблокирован.
Введите chrome://net-internals в адресную строку и нажмите enter.
  Откройте страницу с проблемами. Вернитесь к сетевым внутренним
  элементам, нажмите events (###) и используйте текстовое поле, чтобы
  найти событие, связанное с вашим ресурсом (используйте части
  URL-адреса). Наконец, нажмите на событие и посмотрите, подскажет ли
  вам информация.


text:
Q: Find and replace in Snowsight Does the new Snowsight (preview app) interface provide functionality to find/replace text in the query pane?
In the current interface I can use ctrl-F and ctrl-shift-f for find and replace respectively. They don't seem to work in Snowsight. The search box in the Results pane only works with returned results.

A: It is possible to enable Replace functionality in Snowsight by pressing CTRL + SHIFT + H:

This and more features are discoverable under Keyboard shortcuts:

Snowsight also provides keyboard shortcuts for faster navigation and editing of worksheets. To view the list of supported keyboard shortcuts, press [CMD]+[SHIFT]+[?] (Mac) or [CTRL]+[SHIFT]+[?] (Windows).

EDIT
New Find and Replace UI:

A: Quick answer: This is not supported by Snowsight.
Meanwhile just search will work as expected from the browser.

A: If anyone stumbles on this question like me, now there's a way.
On Mac, hit CMD + Option + f.
Guess you can replace CMD w/ Ctrl and Option w/ Alt if your'e on Windows.


text:
Q: When extracting HTM its doesnt save data to file I have problem in my code, that it only extracts data from variable id and doesn't extract the title. But if i remove extraction for id, title is saving,i guess that might be problem with my extraction for HTM.
Can somebody explain what I'm doing wrong?
var i = 1;

while(iimPlayCode('SET !TIMEOUT_STEP 1\nTAG POS='+i+' TYPE=A ATTR=CLASS:"pl-video-title-link*" CONTENT=EVENT:MOUSEOVER')>0) {

    iimPlayCode('TAG POS='+i+' TYPE=A ATTR=CLASS:"pl-video-title-link*" EXTRACT=TXT\n')
    var title = iimGetLastExtract();
    var title = title.replace(/\s+/g, '');
    iimSet('title',title);

    iimPlayCode('TAG POS='+i+' TYPE=TR ATTR=data-video-id:"*" EXTRACT=HTM\n')
    var id = iimGetLastExtract();
    var id = id.match(/data-video-id="(.+?)"/)[1];
    iimSet('id',id);

    iimPlayCode('SET !EXTRACT {{title}}\nSET !EXTRACT {{id}}\nSAVEAS TYPE=EXTRACT FOLDER=* FILE=Output_for_Youtube_Playlist.csv\n');
    i++;
}

A: Ok, i i figure it out, i forgot put space between single quotes for regex i think this was the issue and i remade structure of script
while(iimPlayCode('SET !TIMEOUT_STEP 1\nTAG POS='+i+' TYPE=A ATTR=CLASS:"pl-video-title-link*" CONTENT=EVENT:MOUSEOVER')>0) {

    iimPlay('Code:'
        + 'TAG POS='+i+' TYPE=A ATTR=CLASS:"pl-video-title-link*" EXTRACT=TXT\n'
        + 'TAG POS='+i+' TYPE=TR ATTR=data-video-id:"*" EXTRACT=HTM\n'
    )

    var title = iimGetExtract(1);
    title = title.replace(/\s+/g, ' ');

    var id = iimGetExtract(2);
    var id = id.match(/data-video-id="(.+?)"/)[1];

    saveRes = 'CODE:';
    saveRes += 'ADD !EXTRACT "'+title+'"' + '\n';
    saveRes += 'ADD !EXTRACT "'+id+'"' + '\n';
    saveRes += 'SAVEAS TYPE=EXTRACT FOLDER=* FILE=Output_for_Youtube_Playlist.csv\n';
    iimPlay(saveRes);
    i++;
}


text:
Q: What process is sending TCP SYNs on Solaris 10? Some process on my Solaris 10 machine is sending TCP SYNs to a remote machine.  The remote machine never responds, so the connection is not established.  How do I find out what process is initiating this?
I've been looking at DTrace scripts but a) I don't know Dtrace well enough to create my own, b) haven't found an existing script, and c) some that I have found use probes not available in my version.
Thanks for any insight.
Gary

A: If you know the destination IP and Port you could run:
pfiles $pid

for every process on your system to determine which one has a socket opened with attributes.  It might also be better to try using
lsof -i

as root to see if you can get the socket while it's still live.
Since the machine is external you might be able to try and see who it belongs to and what software you have from them to limit the processes you may have to look at.

A: Have a look at this Dtrace script: conntrack
# ./conntrack -h
USAGE: ./conntrack [-h] [-p port] [-c command] [-u user]
   -p port         # filter by port (incompatible with user and command)
   -c command      # filter by command (incompatible with port and user)
   -u user         # filter by user (incompatible with port and command)
  eg,
       ./conntrack -p 22    # snoop connections to port 22

A: For each process on your system, pause it with kill -STOP $pid, see if the connection attempts stop, and resume it with kill -CONT $pid.


text:
Q: Rank of a linear transformation on functions I have a mapping with is define as $T(u(t))x = E\Big(\sum_{i=1}^M \int_0^T u(t) \Delta_i(w,t)g_i(x) dt\Big) $ where $\Delta_i(w,t)$ is a stochastic process. Now I want to prove that the range of this mapping will have dimension $M$. First I integrated the mapping and $T(u(t))x = \sum_{i=1}^M Cg_i(x)$ which is a span of $g_i(x)$ which will have dimension at most $M$ if $g_i$'s are independent.
Now for the dimension of the range to be exactly $M$, I know I need to prove that each linearly independent $g_i$'s belong to the range of $T$. This is where I am having difficulties, I know that for the range of $T$ to be $g_i$, I need to use orthogonality so am thinking I can define $E(\Delta_i(w,t)) = h_i(t)$ and define say $w_i(t)$ to be an orthogonal function to $h_i$ (can this be done since $w_i(t)$ is arbitrary function on the domain) and do I just define their orthonrmals to get my results( am also confuse here since I have define $h_i$ to the expected function of $\Delta_i(w,t)$ so do I redefine it orthonormal and how do I incoporate the orthonormal in my mapping). That is can I do this
\begin{equation}
      \begin{split}
         T(w_{i'})x & = \sum_i^M \langle{w_{i'},\Delta_i(w,t)}\rangle g_i(x)\\
         & = E\Big(\int_0^T \sum_{i=1}^M w_{i'}(t)\Delta_i(w,t)g_i(x)dt\Big)\\
         & = \Big(g_i(x)\int_0^T \sum_{i=1}^M w_{i'}(t)E(\Delta_i'(w,t))dt\Big)\\
         & = \Big(g_i(x) \sum_{i=1}^M \int_0^T w_{i'}(t)h_i(t)dt\Big)\\
         & = g_i(x)
       \end{split}
     \end{equation}
where $w_{i'} $ is orthonormal of $w_i$ and $h_i$ is also orthonormal function such that if $i' = i$ the $(w_{i'} . h_i)$ = 1.
Please can someone help me? Also the domain of  my function is define on positive real line and the range is just real line. Thank you


text:
Q: The typical IR spectrometer broadband source emits all IR frequencies of interest simultaneously I am currently studying the textbook Infrared and Raman Spectroscopy, 2nd edition, by Peter Larkin. In a section entitled Infrared Absorption Process, the author says the following:

The typical IR spectrometer broadband source emits all IR frequencies of interest simultaneously where the near-IR region is 14,000 - 4000 cm$^{-1}$, the mid-IR region is 4000 - 400 cm$^{-1}$, and the far-IR region is 400 - 10 cm$^{-1}$.

I know that lasers are approximately, more or less, monochromatic. Obviously, wavelength is not the same thing as frequency, but the idea that a light source could simultaneously emit a broad range of frequencies made me uncomfortable, given the aforementioned fact about monochromaticity.
In doing research, I found the following explanation (see 10.6.2 Sensing Mechanisms):

Optical sensors are typically interfaced with an optical module, as shown in Figure 10.38. The module supplies the excitation light, which may be from a monochromatic source such as a diode laser or from a broadband source (e.g., quartz-halogen) that is filtered to provide a narrow bandwidth of excitation.

It seems to me that this explanation confuses the concepts of "broadband" and "monochromaticity", or it at least writes in such a way that makes it seem so:

The module supplies the excitation light, which may be from a monochromatic source such as a diode laser or from a broadband source (e.g., quartz-halogen) ...

I would greatly appreciate it if people would please take the time to explain how a light source can be "broadband" (that is, emit a broad range of frequencies), and clarify what the above explanation is saying

A: Thermal emission (often idealized as blackbody radiation) is broadband, i.e. emitting multiple frequencies at once. An incandescent lightbulb is like this. The references provided in the question make a proper distinction between monochromatic emission from lasers, and broadband emission from thermal sources.
The quoted sentence that mentions the quartz-halogen source indicates that its broadband emission must be filtered in order to make it behave more like a monochromatic source - without the filter, it doesn't have that property.

A: There are two possible routes to making a broadband light source.

*

*Incoherent sources
The first way is to make a source that emits light at a bunch of different frequencies without any coherence between those different frequency components. The easiest way to do this is via thermal sources (like the quartz-halogen lamps mentioned as examples in your quote) but there are also other mechanisms such as e.g. fluorescence.

*Coherent sources
Or, in other words, pulsed lasers. To be blunt, when you say

I know that lasers are approximately, more or less, monochromatic

you 'know' wrong. Lasers are indeed often described as producing light of only one frequency, but this is a misconception. Lasers come from the amplification of light via stimulated emission, and this amplification can happen for any frequency where the gain medium has available transitions. For solid-state systems, these transitions often occur over broad frequency bands, so those gain media can be used as 'tunable' lasers (where you use the cavity to select the frequency that gets amplified), but you can also set them up so that all of the frequencies are amplified at the same time, fixing their relative phase so that they are coherent with each other, which results in a series of (often very short) laser pulses.
Because of the added layers of technology, pulsed lasers are often more expensive than thermal sources (which can be extremely simple), so if you don't need the coherence (such as e.g. in a spectrometer) then you just use thermal sources when you need broadband light.


text:
Q: Validate 1 of the 2 fields with asp.net validators I've got a simple form with some textboxes. These textboxes all have a RequiredFieldValidator. If field 1 is filled in I need to disable the RequiredFieldValidator of field 2 because only one of these fields is required. What is the best way to accomplish this?

A: In this situation it's simpler to use CustomValidator with server side validating handler. You should add the custom validator to both controls:
<asp:TextBox runat="server" id="control1" />
<asp:CustomValidator runat="server" id="cusCustom1" controltovalidate="control1" onservervalidate="cusCustom_ServerValidate" errormessage="your message" />
<asp:TextBox runat="server" id="control2" />
<asp:CustomValidator runat="server" id="cusCustom2" controltovalidate="control2" onservervalidate="cusCustom_ServerValidate" errormessage="your message" />

and implement the handler like
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    e.IsValid = (!string.IsNullOrempty(control1.Text)) || (!string.IsNullOrempty(control2.Text))
}

A: Currently I've solved it with javascript and I can use normal validators.


text:
Q: function is not working when passing arguments to addEventListener Making simple slider with Js, when passing function with arguments to addEventListernet slider is not working but when putting onclick="slide(1)" to ID, it works fine. What i'm doing wrong?
var imgcount = 1;
var imgTotal = 5;

var left = document.querySelector(".left");
var right = document.querySelector(".right");

function slide(x) {
    var img = document.getElementById("img");
    imgcount = imgcount + x;
    img.src = "img/"+ imgcount +".jpg";
}

left.addEventListener('click', slide(-1));
right.addEventListener('click', slide(1))

);

A: in order to do it the way you've started, you need to return a function from slide:
function slide(x) {
   return function(){
      var img = document.getElementById("img");
      imgcount = imgcount + x;
      img.src = "img/"+ imgcount +".jpg";
   }
}


text:
Q: Spring-Boot - Error Handling I'm trying to write error handler in Spring-Boot for my controllers that would catch most possible errors (Spring, sql etc.). So far I'm able to get JSON response with Nulls however i'm unable to put any data inside. When I try to get error message in I just receive a blank page.
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

@RestController
public class BasicErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";

    @RequestMapping(value=ERROR_PATH)
    @ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class})
    public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) {
        ErrorBody eBody = new ErrorBody();
        eBody.setMessage(e.getCause().getMessage());
        return eBody;
    }
}

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ErrorBody {
    private String dateTime;
    private String exception;
    private String url;
    private String message;
}

A: Yo can do something like this:
 @ControllerAdvice
   public class ControllerExceptionTranslator {

    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    SimpleErrorMessage handleException(EntityNotFoundException exception){
        log.debug("Entity Not Found Exception {}",exception.getMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Entity not found","This resource was not found");
    }

    @ExceptionHandler({UsernameNotFoundException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    SimpleErrorMessage handleException(UsernameNotFoundException exception){
        log.debug("Username not found {}",exception.getLocalizedMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Unaouthorized"," ");
    }

}

A: I was able to get to data about errors and send them as json properly by using "HttpServletRequest request" and reading information from request.
@RequestMapping(value = ERROR_PATH)
    public ErrorBody defaultErrorHandler(HttpServletRequest request) {....}

A: Here this is an example of @ExceptionHandler(Exception.class)
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
You can use @ControllerAdvice
package demo.controller;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

@ControllerAdvice
public class ExceptionControllerAdvice {

 @InitBinder
 public void initBinder(WebDataBinder binder) {
    System.out.println("controller advice: init binder");
}

@ExceptionHandler(Exception.class)
public String exception(Exception e) {
    System.out.println("controller advice: exception Handler");
    System.out.println(e.getMessage());
    return "error";
}

@ModelAttribute
public void modelAttribute(){
    System.out.println("controller advice:model Attribute");
}
}


text:
Q: designing flexible page layout first see the image prepared in paint.

I want to design a flexible page which will have this type of four division. and hence change in monitor screen or browser size re-sizes window automatically. This all 4 box should fit 100% browser screen and any monitor size and avoiding scroll bar to appear ever. so can any one tell me how to code it in css stylesheet.
here is my code.
html:

css:
    *
    {
    margin: 0;
    padding: 0;
    }
    #wrapper
    {
    margin: 0px auto;
    height: 100%;
    width: 100%;
    }
    #bottomleft
    {
    position:relative;
    height: 50%;
    width: 50%;
    border: 1px solid black;
    float: left;
    }
    #topleft
    {
    position:relative;
    height: 50%;
    width: 50%;
    border: 1px solid black;
    float: right;
    }
    #topright
    {
    position:relative;
    height: 50%;
    width: 50%;
    border: 1px solid black;
    float: left;
    }
    #bottomright
    {
    position:relative;
    height: 50%;
    width: 50%;
    border: 1px solid black;
    float: right;
    }

A: Demo
HI now define your body, html height 100%; in css as like this
and define box-sizing in your id
body, html{
height:100%;
}
#bottomleft, #bottomright, #topright, #topleft{
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}

Demo

A: You use this meta in head tag for all device and use other css for any window width
this meta use for any devic and link tag for load css with min-width شrbitrary
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" media="print and (min-width: 25cm)" href="http://…" />

best regards


text:
Q: Center element relative to wrapping inline span How can i show a number in center underneath a underlined text?
My code works for simple cases, but when the text wraps, the number is no longer centered under the text:

I want something like this instead:

This is my code that is have written so far.

p {
  line-height: 28px;
}
.bottom_bullet_spn {
  position: relative;
  display: inline;
  vertical-align: top;
  padding: 0 0 20px;
}
.bottom_bullet {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  font-size: 9px !important;
  top: 13px;
  text-align: center;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore mag1na
        aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
        cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.2

JSfiddle
The number 2 is centered correctly  but number 1 is not centered.
Javascript solution will also work

A: If window resizing is not your concern, then you may try this:
.bottom_bullet {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    font-size: 9px !important;
    top: 0;
    margin:10px auto 0 auto; //you can also use margin:0 auto; But text will overlap.
    width:20px;
}

Demo:
http://jsfiddle.net/grLe7snj/2/
But if you are worried about resizing, then I would suggest you to place that small number at the end of the underlined text. In that way, you will solve your problems and also it will be good on user part too. Generally you place such numbers at the end of the text or rarely at the start(refer wikipedia)
In this case:
.bottom_bullet {
    position: absolute;
    bottom: 0;
    left: 100%;
    right: 0;
    font-size: 9px !important;
    top: 0;
    margin:10px auto 0 auto;
    width:20px;
}

Demo: http://jsfiddle.net/grLe7snj/3/


text:
Q: Will having three proxies like below tunnel similar to tor? If I connect to a VPN on Windows, then I open a virtual machine and connect to a second VPN, and then I go to my browser in the Virtual Machine and connect to a proxy.
Will the connection now have 3 layers like this, VPN > VPN 2 > Proxy,
or do I need to do something else to get that configuration?

A: It depends on the VM host machine configuration. If your VM has raw access to your host machines network adapter connection it may not work as intended. You can test your idea by first connecting the host operating system (windows) to the first VPN. Then run your browser on the VM and go to "canyouseeme.org". Is the IP that this website is showing you the VPN IP number from your host operating system? Or is it your actual WAN IP number? If it's your VPN IP number, you then connect the VM to the second VPN connection and redo the test from the first step. If not you have configuration issues on the host machine. does canyouseeme.org show you the WAN IP, VM host VPN IP, or the second VPN connections IP? In theory this can work, it's going to add an incredible amount of latency to the machine that's connecting through it.  you can add an extra layer of security by connecting to a single VPN then using the Tor network through it BTW.

A: technically yes that should work, although depending on what you are using your proxies and VPNs for, as well as which proxies and VPNs you chose, it may or may not protect you the way you expect. If you are using the same VPN service for all three, then it would effectively work as a single VPN.
So... Whatcha planning on pirating?
EDIT: as a response to the second comment, that would honestly be the best method for most things. Use a single VPN and then a tor browser or tor similar browser that hides your browsing activities would be a great plan. It would be just as safe, and just as unlikely to be gotten through. If you really want as much security as possible, then go ahead and do your plan, follow his instructions to set it all up so that you get the VPNs in order, and the latency to a maximum and then use tor or something like it under all that. Youll never be found.. unless youre hacking the government... They always know.


text:
Q: How do you return the total value of two methods that each take in a value? My teacher wanted us to create program to compute the bills of our home. In java we were just going over objects and classes so I made
class Bills{
Bills... etc
The problem I am having is I dont know how to get a total of two methods that take in a value.
public double getWifepay(double x){
return x;
}

public double getHusbandpay(double y){
return y;
}

public double getTotalmoney(){
???
}

A: Create the previous two method (getwifepay, gethusbandpay) as static and call them in getTotalmoney function with class name. suppose class name is A so call as A.getwifePay(value)

A: Not sure I understand your model classes, but as you mention, for the "getTotalMoney" method to return the sum, the elements (the numbers in this case) should be given as parameters.
On the other hand, your "getWifepay" and "getHusbandpay" methods don't make much sense, as they are returning the same parameter which is given.
With all of this, you would need to have the method "getTotalmoney" call the other two and then make the sum, like this:
public double getWifepay(){
  return x;
}

public double getHusbandpay(){
  return y;
}

public double getTotalmoney(){
  getWifepay() + getHusbandpay();
}

Finally, I suppose that these methods are within a given class (you mentioned Bill), making it maybe something like this:
class Bill {
  private double x;
  private double y;

  private double getWifepay(){
    return x;
  }

  private double getHusbandpay(){
    return y;
  }

  public double getTotalmoney(){
    getWifepay() + getHusbandpay();
  }
}

Hope that solves your problem.

A: Your methods should probably just return some value that is stored within the object. So you would have something like:
public double getWifePay(){
    return wifePay;
}

public double getHusbandPay(){
    return husbandPay;
}

And
public double getTotalmoney(){
    return getWifePay() + getHusbandPay();
}

and then you probably would want to write some setter methods like:
public void setWifePay(double wifePay) {
    this.wifePay = wifePay;
}

public void setHusbandPay(double husbandPay) {
    this.husbandPay = husbandPay;
}

And in your class definition you should have declared these fields:
public class Bills {
    double wifePay;
    double husbandPay;

    // And then the methods from above
}


text:
Q: Java Robot class not working with installation Robot r = new Robot();

String command = "C:\\Users\\xyz xyz\\Desktop\\JavaProg\\kmp.exe";

         //Run setup file
Process run =  Runtime.getRuntime().exec("cmd /c \"" + command+ "\"");

    r.delay(4000);
    r.mouseMove(0, 0); //not working if I run kmp.exe but work with notepad.exe
    r.delay(2000);
    r.keyPress(KeyEvent.VK_R); //It should chose Russian language but not
    r.keyRelease(KeyEvent.VK_R);

I am using Robot class to automate a installation package.Code is opening the kmp setup, the default security warning of win 8 as I have disabled, but then mouse should move to 0, 0 coordinate yet it is not moving. Same time if instead of "kmp.exe" I run "Notepad" then notepad will open and mouse will also move to 0, 0.
Does it have anything to do with kmp.exe installation package as it is fetching the control from java program or something like this.


text:
Q: Stuck with MacbookPro when booting a bootable USB containing MACOS Installation image I've got a MacBook Pro (2012 or 2013 model) with no Mac partition, I've tried to install Mac using recovery mode but It always downloads 'MacOS Lion Mountain' which is outdated so my mac keeps crashing each 10 minutes.
I've tried to create a bootable usb using Windows in order to install Mojave or Sierra, I used TransMAC and AnyBoot to write the .dmg image on the usb. The problem is that my MAC doesn't detect the usb as bootable device (formatted and converted as a GPT Partition), it's either disabled or doesn't show up at all. Despite, it works fine with FAT32 and NTFS Partitions when I was trying to install Ubuntu.
What can I do in order to install an non-outdated MACOS (such as Sierra) on my MacBook?
Thanks in advance.


text:
Q: Multiple outputs based on each if statement being true. Java I am trying to make both of these if statements output if true.
Like if I am enter:
cat
car

I want it to output:
Cat and Car are both the same length.
Cat and Car both start with C.

Right now I am only getting the First output
Here is the code:
import java.util.Scanner;  // Import the Scanner class

public class Main
{
    public static void main(String[] args) {
        System.out.println("input words");

        String myObj, myObj1;

         Scanner sc = new Scanner(System.in);  // Create a Scanner object
         myObj = sc.nextLine();  // String Input
         myObj1 = sc.nextLine(); // String Input

         if(myObj.length() == myObj1.length()){  // System check for String Length
             System.out.println( myObj + " and " + myObj1 + " are the
            same length.");

         }
         if ((myObj1.charAt(0) == 'C') && (myObj.charAt(0) == 'C')){

            System.out.println(myObj + " and " + myObj1 + " start with C." );
            } // Output if both start with C

A: if ((myObj1.charAt(0) == 'C') && (myObj.charAt(0) == 'C')){
will not be true for the input car ot cat as
c does not equal C
After reading the values add this code
myObj = myObj.toUpperCase();
myObj1 = myObj1.toUpperCase();


text:
Q: Excel - Convert String with if condition to a formula I'd like to use something like the EVALUATE-Function in Excel for if-statements.
I've got the following issue: I'd like to use Excel to validate my data. I've got three sheets:

*

*the real data I'd like to check. Each row represents a customer and each column some data. The columns have specific names like "age", "name", …

*the description of the checks I'd like to perform. Each row represents one check and I've got 3 columns: 1 check_id – an identifier of each check; 2 check_desc – a description of the check that every normal person can understand like "Age below 18"; 3 rule – the Excel Formula as a string like If(age<18, "error", "no error")

*the place where sheet 1 and 2 should come together. Each row should represent one customer and each column one check.

Now, if I've got for example check_1 "If(age<18, "error", "no error")" and the customer data 10 and 20, then the check for the first customer should fire and the check for the second shouldn't.
If the data is changed, and the age is set from 10 to 18, then everything should be fine, or if the rule is changes to "If(age<21, "error", "no error")" then the new condition should be applied to all data.
Is something like this possible?
With the evaluate function only 'simple' formulas work.
Thanks in advance,
Martin
Attached you can find the
Excel-Sample File

A: You will definitely need some VBA here. Make a custom EVAL function:
Public Function EVAL(ByRef Rng As Range, Formula As String) As Variant
    Dim RngAddress As String
    RngAddress = "'" & Rng.Parent.Name & "'!" & Rng.Address(External:=False)
    EVAL = Evaluate(Replace(Formula, "$", RngAddress))
End Function

Then you can easily evaluate your values with formulas passed as text ($ is for parameter):
=EVAL(A1, "IF($<21,""error"",""no error"")")

(note the escaped double quotes). But you would rather pass formula from another cell - then you can specify formula in cell with single quotes:
IF($<21,"error","no error")
=EVAL(A1, B1)

A: I personally would rename check_desc!B2 to "Check_1" (named range) and then refer to that. You can use the INDIRECT function as well once you've renamed your column header "Check_1" as well.
Note: the value in this case should be "18" instead of "age below 18". You can of course change the number format to "age below "0.
If the relations are changing too I would insert a table that would have uniform formulae changing in each cell when changed in one cell.
The only issue you would then face is the non-expanding nature of your table. You can use VBA for this, but maintaining formulae increases your accountability even if it would be slightly easier not to deal with nasty nested functions.


text:
Q: JQuery - setting an "active" class for image-scroll I have content loading dynamically (using new WP_query loop in WordPress) for a jQuery carousel or image-scroll function -- where the image-scroll is a li list of images, styled to look like a strip of images.
When the image-scroll works properly, one of the images in the li tag has a class of active, which expands the image and makes it look like it's in front of the other images,
... and as the user clicks through this strip of images, the active class changes/moves to the targeted li tag, expanding that image.
What's happening is that none of the li tags are active when the page loads - since the content is dynamic through the WP loop (I didn't want all of the li tags to start with the active class, so I didn't add it to the loop),
...and so the images are just lined up in a consistent strip w/o one of the images being expanded (or having that active class).
It is only if the user happens to click on one of the images that it expands,
...but i need one of the images to be expanded (to have the class of active) before the user clicks so I need the active class added as/after the page loads.
I have tried through the jQuery code to target one of the li tags to add the active class, using filter() or closest() after the page loads, but that didn't work.
Or maybe I should write a new script to add the active class?
Any help much appreciated!
I have the abbreviated html and the jQuery function below.
_Cindy
ps as the code indicates, I also have corresponding article titles that scroll with the images, so perhaps I need to adjust the jQuery there, too.

    jQuery(".images-scroll li a").click(function() {
    jQuery(this).parent().parent().find("li").removeClass("active");
// tried the following instruction as well as on next line, but no go
// jQuery(this).parent().parent().closest("li").addClass("active");
    jQuery(this).parent().addClass("active");
    jQuery(this).parent().parent().parent().find(".images-content > li").removeClass("active");
    jQuery(this).parent().parent().parent().find(".images-content > li").eq(jQuery(this).parent().index()).addClass("active");
    var step = ((-250)*(jQuery(this).parent().index()-1))-60;
    //alert(step);
    jQuery(this).parent().parent().css("margin-left", step+"px");
    return false;
});

A: The reason why the code you wrote didn't work is that you have it inside a click handler, so nothing happens until you click one of the targeted elements. If you want something to happen on page load you can use $(document).ready() (can be shortened as $()) or $(window).load(). Just add the following lines below or above your existing code.
jQuery(function(){
    var $listItems = jQuery('.images-scroll li');
    $listItems.first().addClass('active');
    // Second list item
    $listItems.eq(1).addClass('active');
    // Third list item
    $listItems.eq(2).addClass('active');
});

Also, please note that (unless it conflicts with a different plugin), writing $ is shorter than jQuery, and it should do the same.


text:
Q: how to resolve issue to use ngModel i am trying to bind ngModel form input text but it's not working here is my
regi.component.html.
in my html part i use input tag with ngModel  but this ngModel not print my string value
<input id="name" name="name" [(ngModel)]="hero"  >

here is my regi.component.ts code
import { Component, OnInit, } from '@angular/core';

@Component({
  selector: 'app-regi',
  templateUrl: './regi.component.html',
  styleUrls: ['./regi.component.scss']
})
export class RegiComponent implements OnInit {
hero:String ;
  constructor() { }
  ngOnInit(): void {
this.hero = 'hello world';
}

}

that's it
i want only print my value in html
but when i save my files then
this error show in terminal

here is my regi.module.ts
import { NgModule } from '@angular/core';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RegiRoutingModule } from "./regi-routing.module";

@NgModule({
  declarations: [ ],
  imports: [CommonModule,
            FormsModule,ReactiveFormsModule,
            RegiRoutingModule],
},
)
export class RegiModule { }

and when save and look into then vs code terminal
and here is my project stracture

A: If you want to bind a form field with an input it is not need to use the NgModel, you can set this way:
<input id="name" name="name" class="form-control"
      required minlength="4" appForbiddenName="bob"
      formControlName="name" >

<div *ngIf="name.invalid && (name.dirty || name.touched)"
    class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors.forbiddenName">
    Name cannot be Bob.
  </div>

</div>

Also, you have to declare this inside a formGroup that bind the form you created before:
<form [formGroup]="heroForm">
  // your form info here
</form>

A:
try to import formsModule in your app.module.ts

 import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { ReactiveFormsModule } from '@angular/forms';

    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: []
      }
    )


text:
Q: digitalOcean meteor js mup deploy i've deployed my meteor application on digitalOcean 512Mo droplet , and it is stuck in the first step "uploading bundle" it takes so long without any response no error also, mup setup works fine. This is not the first deployment i've deployed before few times it was working fine. i've tried to disable the firewall and it doesn't work. i have also a local staging server i've tried to deploy and it works fine but its 2G Ram , shall i upgrate the droplet.
Thanks.


text:
Q: /usr/include/x86_64-linux-gnu/bits/string_fortified.h:106:10: error: '__builtin_strncpy' I'm trying to Build Qemu & Xen for XenGT on Ubuntu 20.04 following this tutorial :
https://github.com/intel/gvt-linux/wiki/GVTg_Setup_Guide#332-build-qemu--xen-for-xengt
because I want to share the integrated GPU with a xen VM.
The main hardware components of my PC are the following :
CPU I9-9900k
Intel Corporation UHD Graphics 630 (Desktop 9 Series) (rev 02)
IVIDIA Corporation TU102 [GeForce RTX 2080 Ti] (rev a1)
The compilation gave no errors until this point :
root@ziomario-z390aoruspro:/etc/xen/igvtg-xen# make install-tools

......

make libs
make[5]: ingresso nella directory «/etc/xen/igvtg-xen/tools/libxc»
rm -f _paths.h.tmp; echo "#define sbindir "/usr/sbin"" >>_paths.h.tmp; echo "#define bindir "/usr/bin"" >>_paths.h.tmp; echo "#define LIBEXEC "/usr/lib/xen"" >>_paths.h.tmp; echo "#define LIBEXEC_BIN "/usr/lib/xen/bin"" >>_paths.h.tmp; echo "#define libdir "/usr/lib"" >>_paths.h.tmp; echo "#define SHAREDIR "/usr/share"" >>_paths.h.tmp; echo "#define XENFIRMWAREDIR "/usr/lib/xen/boot"" >>_paths.h.tmp; echo "#define XEN_CONFIG_DIR "/etc/xen"" >>_paths.h.tmp; echo "#define XEN_SCRIPT_DIR "/etc/xen/scripts"" >>_paths.h.tmp; echo "#define XEN_LOCK_DIR "/var/lock"" >>_paths.h.tmp; echo "#define XEN_RUN_DIR "/var/run/xen"" >>_paths.h.tmp; echo "#define XEN_PAGING_DIR "/var/lib/xen/xenpaging"" >>_paths.h.tmp; echo "#define XEN_DUMP_DIR "/var/lib/xen/dump"" >>_paths.h.tmp; echo "#define XEN_LOG_DIR "/var/log/xen"" >>_paths.h.tmp; echo "#define XEN_LIB_DIR "/var/lib/xen"" >>_paths.h.tmp; echo "#define XEN_RUN_STORED "/var/run/xenstored"" >>_paths.h.tmp; if ! cmp -s _paths.h.tmp paths.h; then mv -f paths.h.tmp paths.h; else rm -f paths.h.tmp; fi
gcc -m64 -DBUILD_ID -fno-strict-aliasing -std=gnu99 -Wall -Wstrict-prototypes -Wdeclaration-after-statement -Wno-unused-but-set-variable -Wno-unused-local-typedefs -O2 -fomit-frame-pointer -D__XEN_INTERFACE_VERSION=XEN_LATEST_INTERFACE_VERSION -MMD -MF .xc_pm.o.d -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_GNU_SOURCE -I../../xen/common/libelf -Werror -Wmissing-prototypes -I. -I./include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/include -D__XEN_TOOLS -pthread -I/etc/xen/igvtg-xen/tools/libxc/../../tools/libs/toollog/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/libs/evtchn/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/libs/devicemodel/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/include -include /etc/xen/igvtg-xen/tools/libxc/../../tools/config.h -I/etc/xen/igvtg-xen/tools/libxc/../../tools/libs/call/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/libs/foreignmemory/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/libs/gnttab/include -I/etc/xen/igvtg-xen/tools/libxc/../../tools/include -c -o xc_pm.o xc_pm.c
In file included from /usr/include/string.h:495,
from xc_private.h:24,
from xc_pm.c:22:
In function 'strncpy',
inlined from 'xc_set_cpufreq_gov' at xc_pm.c:308:5:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:106:10: error: '__builtin_strncpy' specified bound 16 equals destination size [-Werror=stringop-truncation]
106 | return __builtin___strncpy_chk (__dest, __src, __len, __bos (__dest));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
make[5]: *** [/etc/xen/igvtg-xen/tools/libxc/../../tools/Rules.mk:222: xc_pm.o] Errore 1
make[5]: uscita dalla directory «/etc/xen/igvtg-xen/tools/libxc»
make[4]: *** [Makefile:184: build] Errore 2
make[4]: uscita dalla directory «/etc/xen/igvtg-xen/tools/libxc»
make[3]: *** [/etc/xen/igvtg-xen/tools/../tools/Rules.mk:246: subdir-install-libxc] Errore 2
make[3]: uscita dalla directory «/etc/xen/igvtg-xen/tools»
make[2]: *** [/etc/xen/igvtg-xen/tools/../tools/Rules.mk:241: subdirs-install] Errore 2
make[2]: uscita dalla directory «/etc/xen/igvtg-xen/tools»
make[1]: *** [Makefile:74: install] Errore 2
make[1]: uscita dalla directory «/etc/xen/igvtg-xen/tools»
make: *** [Makefile:127: install-tools] Errore 2

I see that this bug is widespread. How can I fix it ? Im not so skilled. I didn't find any solution. Can someone help me ? thanks.

A: Look at this:
"cc1: all warnings being treated as errors"
And you can find these in build.html:
"By default, the JDK has a strict approach where warnings from the compiler is considered errors which fail the build. For very new or very old compiler versions, this can trigger new classes of warnings, which thus fails the build. Run configure with --disable-warnings-as-errors to turn of this behavior. (The warnings will still show, but not make the build fail.)"
so we know that the JDK treats the warning as an error and terminates the building. you just need "make clean" and "bash configure --disable-warnings-as-errors" to regenerate the configuration


text:
Q: Hi resolution in virtual consoles with nvidia legacy driver on Debian 10.1 I have installed nvidia-legacy-340xx-driver from contrib repository in Debian 10.1. The driver is working but I have low resolution in virtual consoles. With nouveau driver the resolution was the monitor native resolution 1920x1080.
I want that resolution with nvidia legacy driver.
I have found some articles about uvesafb, but the maximum supported resolution is 800x600.
Is it possibly to have hi resolution with nvidia legacy driver and how?


text:
Q: Ansible : Use regex replace for items in list and assign it back I tried using regex_replace option this way:
Here groups[group_names[0]] is list of node names
 "groups[group_names[0]]": [
        "node1.in.labs.corp.netin",
        "node2.in.labs.corp.netin"
    ]

- set_fact:
      groups[group_names[0]]={{ groups[group_names[0]] |
                   map('regex_replace', _regex, _replace)|list }}
  vars:
    _regex: '^(.*?)\.(.*)$'
    _replace: '-n \1'

Hitting the following error:
{"changed": false, "msg": "The variable name 'groups[group_names[0]]' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."}

Can i assign back to same list ? after replacing the regex ?
Also -n option is using so that my expected output should be
-n node1 -n node2


text:
Q: Can you not reference 2d array by a double pointer? I think my understanding of arrays and pointers is a little vague. The bigger goal is to swap pointers to two arrays. In the following example,  I first create a temporary pointer b that points to the static array a. Then i insert into a an element 1. I thought since b is pointing to a, b[0][0] would access the array but it gives me segmentation fault. Why is that so?
#include <iostream>

using namespace std;

int main()
{

    int a[10][10];

    int ** b = (int **) a;

    a[0][0] = 1;

    cout << b[0][0] << endl;

   return 0;
}

A: You can change int ** b = (int **) a; to int(*b)[10] = a;, you will success.
You should know that the type of a is int (*a)[10].


text:
Q: How to call singleton here? ios7 If I create an instance of singleton class in MyViewController, how then to call singleton from MyViewController? Like class method or like instance?

A: To create a singleton in objective-C you need to to this:
@interface gaSharedData : NSObject
+ (gaSharedData *)sharedInstance;
@end

in the .h file of the singleton class. In the .m file you need:
static gaSharedData *sharedObject = nil;

+ (gaSharedData *)sharedInstance
{
   static dispatch_once_t _singletonPredicate;

    dispatch_once(&_singletonPredicate, ^{
       sharedObject = [[self alloc] init];
    });

    return sharedObject;
}

- (id)init {
    return self;
}

Now if you want to get an instance of the class gaSharedData, you need to call this like that:
gaSharedData *data = [gaSharedData sharedInstance];

I hope this helps you :)


text:
Q: How do you get log4net's SmtpPickupDirAppender to use the IIS pickup directory? Due to the nature of the live server I deploy to, my mail settings are using deliveryMethod="PickupDirectoryFromIis". I'm using log4net to send logs via email and I need find a way of getting it to do the same thing.
I can see from the docs that there is an SmtpPickupDirAppender, which has a pickupDir setting. If I set this to whatever pickup directory IIS uses, I'm sure everything will work OK. However what I really want is to just tell log4net to use IIS's setting and leave it there. That way if it ever changes we won't have to change the log4net config too, something we're likely to forget. Is there a way to do this?

A: AFAIK, that's not possible. Although it sounds like a good idea.
One of the greatest things about log4net is that you can change your configuration without having to restart or recompile the application (check the FAQ), so you don't need to worry about having a downtime in your logging.
I don't know if you can query the IIS for the SMTP pick up directory, maybe if this is possible you can add some background job that queries the IIS for this information?

A: It is a shame because the SmtpClient.DeliveryMethod property supports a value of PickupDirectoryFromIis.


text:
Q: Easiest way to migrate aliases from bash to zsh I want to start using zsh as recommended by Apple for Mac OS Catalina. How do I migrate my aliases that I have defined in the ~/.bash_profile to the new shell?

A: If until now you've been using ~/.bash_profile for the loading the aliases, here are some of the ways you can migrate your aliases:

 1. Copy the contents:
The most assiduous and obvious way is to copy the contents of your ~/.bash_profile  to ~/.zshrc. It works particularly when you are moving on from bash to zsh for good.

 2. Pull out aliases and then source them:
Another *way is:

*

*Create a new file that will contain the aliases (let's call it ~/.aliases);

*Copy the contents of ~/.bash_profile to the new aliases file;

*Modify the ~/.bash_profile and ~/.zshrc to source the new file.

Put the following in ~/.bash_profile:
if [ -f ~/.aliases ]; then
   . ~/.aliases
fi

and put the following in ~/.zshrc:
source $HOME/.aliases

This way the aliases will be available for both shells. More importantly, if you make changes to the aliases, the changes will cascade to both shells automatically.

* Taken from here


text:
Q: c++ telegram bot. new line in sendMessage using cURL library I didn't find something helping me  in the web so i'll ask you for help.
I try sending a Message with several line breaks.
e.g.:
Hey!
Welcome to the channel!
So my code:
int main(){

   CURL *handle
   handle = curl_easy_init();

   string url = "https://api.telegram.org/<bottoken>/sendMessage?chat_id-idnbr&text=Hey\nwhatsup"

   curl_easy_setopt(handle , CURLOPT_URL, url.c_str());

   curl_easy_perform(handle);
}

Now if i set it like this i get the CURLcode 3 CURL_URL_MALFORMAT (URL not formatted right)
Any idea what to do?


text:
Q: Как сохранить значение переменной в JavaScript? Как это сделать?
Куки не предлагать, т.к. с интернетом...
localStorage, хорошая функция, но после загрузки он(JS) думает, что загрузил переменные типа char/string и выполнять математические операции с загруженным числом невозможно, можно ли как-то это исправить?
Если нет, то как тогда работать с window.name?
Просто видал, что можно как-то сохранить с помощью window.name.

A: Можно взяв из localStorage преобразовать строчку в численый тип.
Положить значение по ключу "myNumber"
localStorage.setItem("myNumber","111");

Получить с использование парсинга можно так
var number = parseInt(localStorage.getItem("myNumber"));

или синтаксис покороче
var number = +localStorage.getItem("myNumber");

достаточно распространённая ситуация хранения в localStorage комплексных объектов.
//создадим объект
var obj = {
    item1: 1,
    item2: [123, "two", 3.0],
    item3:"hello"
};

var serialObj = JSON.stringify(obj); //сериализуем его в строчку

localStorage.setItem("myKey", serialObj); //запишем его в хранилище по ключу "myKey"

var returnObj = JSON.parse(localStorage.getItem("myKey")) //спарсим его обратно объект

после JSON.parse мы уже имеем нормальный объект в том числе и с целочисленными переменными.
Почитать про localStorage:

*

*tproger.ru - LocalStorage на пальцах

*metanit.com - Web Storage


text:
Q: Javascript Regex for Employee Code prefix validation I want a single line regex that will check that a string starts with alphanumeric characters followed by a special character ( ) -_ /, and within these special character there can be any alphanumeric characters.
I need this kind of validation for Employee Code prefix in my system for example I want to allow these kind of string A12(6) or H3(G) or H4-C, 840D_CODE.
I am jquery validator method and currently I am using the following code :
$.validator.addMethod("Prefix", function(code_prefix, element) {
    return this.optional(element) ||    code_prefix.match( /^[a-zA-Z0-9]+[\(\)\-\_\/]*[a-zA-Z0-9]*$/);
}, "Please specify a valid prefix");

A: Try this one out:
^[A-Za-z0-9]*([( ) -_ /][A-Za-z0-9]*[( ) -_ /])

Parts of the regex:
^[A-Za-z0-9]* //starts with alphanumeric characters
(
[( ) -_ /] // first bracket/dash/underscore..
[A-Za-z0-9]* // another set of alphanumeric characters
[( ) -_ /] // second bracket/dash/underscore..
)


text:
Q: Pytest testing: celery timed event triggered by post_save signals I use celery+sqs to perform timed tasks.
Flow is like this:
Object is created -> post_save signal received -> celery task executed based on the date
Here is the case:
I have a model
SmartStorage:
 ...
 execution_date: datetime

And a signal:
@receiver(post_save, sender="storage.SmartStorage")
def _notify_smart_storage_execution(
sender: ModelBase, created: bool, instance: SmartStorage, **kwargs
) -> None:
     if created:
        buffer = instance.execution_date - timedelta(minutes=5)
        celery_notify_smart_storage_execution_task.apply_async(
            kwargs={"storage_id": instance.id}, eta=buffer
        )

And a task:
@shared_task()
def celery_notify_smart_storage_execution_task(storage_id: uuid.UUID) -> None:

    instance = SmartStorage.objects.get(id=storage_id)
    SqsUtils.send_sqs_queue_message(
        sqs_queue_name=SqsUtils.SmartStorage,
        message_body=f"Storage {instance.name} is available in 5 minutes",
    )

I want to perform endpoint testing via pytest, where only one instance sends a message to sqs:
@pytest.mark.django_db
class TestSmartStorageTasks:

    @pytest.fixture(autouse=True)
    def _setup(self) -> None:
        SqsUtils.delete_sqs_queue_messages("celery")

    def test_storage_is_starting(self):
        # This is the only one to send a message to sqs
        test_storage = test_smart_storage_factory(
            execution_date=timezone.now() + datetime.timedelta(minutes=5, seconds=1)
        )
        # Bunch of other storage models, those should not be sending messages to sqs
        for _ in range(10):
            test_smart_storage_factory()

        time.sleep(10)

        sqs_messages = SqsUtils.list_sqs_queue_messages("celery")
        received_messages = sqs_messages["Messages"]
        assert len(received_messages) == 1

I always get 11, although if I do manual testing, which I am not a fan of, everything works fine. I would appreciate help guys!