text:
Q: How to set image height within script I'm currently trying to create a banner that displays random images on each refresh. I've managed to get that working but I need to change the height of the images to 139px, rather than have them displayed at full size.
How can I set the height of the images within the script that loads the images at random?
I learnt code 15 years ago at school, so my understanding of it now is basically 0, so I'm easily lost! There is probably a better way of loading random images to start with, but this was the only one I've been able to get to work.

A: You can try this:
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
var img = new Image();
img.src = path;

After this you can add:
img.style.height = '139px';

And then set it to html:
$("div.banner3").html(img);

A: use document.createElement instead of image, like this:
var randomImage = {
    paths: [
      "c1.png",
      "c2.png",
      "c3.png",
      "c4.png",
      "c5.png",
      "c6.png",
      "c7.png",
    ],
    generate: function(){
      var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
      var img = document.createElement('img');
      img.src = path;

      img.height = DESIRED HEIGHT

      $("div.banner3").html(img);

    }
  }
  randomImage.generate();

A: You can do it in CSS:

var randomImage = {
  paths: [ "https://picsum.photos/id/1/300/300",
          "https://picsum.photos/id/2/300/300",
          "https://picsum.photos/id/3/300/300",
          "https://picsum.photos/id/4/300/300",
          "https://picsum.photos/id/5/300/300",
          "https://picsum.photos/id/6/300/300",
          "https://picsum.photos/id/7/300/300" ],
  generate: function(){
    var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
    var img = new Image();
    img.src = path;
    $("div.banner3").html(img);
  }
}

randomImage.generate();
.banner3 {
  position: absolute;
  top: 0;
  left: 0;
  height: 139px;
  overflow: hidden
}
.banner3 img {
  height: 139px
}


text:
Q: Change encryption for an existing s3 object I am looking for a way to change server side encryption of an existing s3 object using AWS SDK.
CopyObject seems to be one of the way to change the encryption type (S3 or AWS KMS) . This does provide way to avoid download of object by having same bucket name as source and destination. However it takes time proportional to size of the file.
Is there an efficient way to change encryption of an existing s3 object?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook API object likes limitations, likes count and shares count I have website page where I put Facebook Like plugin - so that people can see and press this button on my website's page

I also want to get list of people who liked/recommended my website's page (not facebook page) using Facebook API.
For example: on my website page i see this button and text that 3 of my friends and other 20 people liked this. So if I open this URL
https://graph.facebook.com/v2.8/?id=MY_WEBSITE_PAGE_URL

I will get JSON file like
og_object: {
id: "11******038",
description: "some text",
title: "some title",
type: "article",
updated_time: "2017-03-23T06:29:16+0000"
},
share: {
 comment_count: 0,
 share_count: 23
},
id: "MY_WEBSITE_PAGE_URL"

So there are 23 people who liked this page on my website. And it seems to be fine but I don't understand what happens when I try to get list of this 23 people.
As now I have og_object->id I can get list of likers for this object from URL
https://graph.facebook.com/v2.8/og_object->id/likes?access_token=MY_ACCESS_TOKEN&summary=true

And I see JSON where is list of 13 users with names and their ID's and also block
summary: {
total_count: 13,
can_like: false,
has_liked: false
}

So as you can see - there is only 13 people but there was 23. This numbers are changing from page to page - so it can be 40 shares count but only 15 people in likers list.
Why is it happening? Maybe there are some limitations that facebook users enables so that their likes can't be seen?

A: According to Jonathan Dean this is not possible due to privacy reasons
See the full answer here: https://stackoverflow.com/a/6737579/695046

A: The short answer is that you are already correctly requesting and receiving the names of all 13 people who have clicked your "recommend" button (liking the web page), but the share count of 23 you are seeing is an aggregate of shares, likes, and comments, not just the likes.
Here's a more detailed explanation.
As moonvader commented, Jonathan Dean's answer to this previous question (How to list facebook users who like a page or interest) is incorrect or outdated. You can, in fact, retrieve a list of names and user IDs of people who like a specific Open Graph object.
However, to start addressing moonvader's question, the share count and the like count are measuring different things.
The Facebook Graph API page on URLs has this to say about share count,

This number is an aggregation of shares, likes, and comments for the URL. This number is approximate.

And Facebook's Graph API page on sharedposts says that in order to access user information about people who have shared an Open Graph object in a post you'll need:

A user access token with user_posts permission, for someone who is able to view the post after privacy settings are taken into account.

That means to view the user id for shared posts, you would need permission access to the posts of everyone who shared it, which isn't feasible in the real world.
Although the 10 shares and comments are inaccessible, clicking a "recommend" button on a web page triggers a like on the object. This means moonvader is already correctly accessing all 13 users who clicked the "recommend" button.


text:
Q: How to present overlap of related sets I have extracted URL links from a number of webpages and many of the webpages contain the same set of links (or subsets) as other webpages. I have ~1000 webpages and ~10 links per webpage.
What is an efficient way to find the minimum set of webpages that will still cover the complete set of links?

A: Let me try a preliminary answer to see if I've understood what you're after.
You have, let's say, 1000 web pages, each containing some outbound links.  You might define a 1000x1000 matrix D by
$$
D_{ij} = \mbox{number of links in common between the }i\mbox{th and }j\mbox{th pages}.
$$
Then you want to extract from $D$ a single number, the 'level of overlap', which broadly speaking will be large if most entries of $D$ are large, and small if most entries of $D$ are small.
I can think of some ways of doing that, but before I go into it, let me check: is that the kind of thing you want?

A: One approach is to represent your data as a graph, and use a network diagram tool to draw it. Variant 1: nodes are websites, weighted edges represent number of common links. Variant 2: a bipartite graph with nodes being either web sites or links, and unweighted edges indicating "web site A contains link B." The magic google phrase to find examples related to your example is "citation visualization".
The problem with this technique is that big graphs sometimes turn into hairballs in a graph layout tool, so you may need to prune or filter your data set for it to be intelligible.
There are other techniques: you could draw a grid where rows correspond to web pages, and columns to links they contain, and fill in cells (X,Y) where link X appears in web site Y. If you reorder the rows and columns to put related pages near each other and related links near each other this can be an effective analytic tool, but it might not be right for non-technical readers.
A lot of this depends on the details of your data. If you have any kind of metadata (a categorization of web pages or links) that could suggest other approaches--feel free to add details in your question. About the only thing you can say for sure is a big Venn diagram is going to be a mess!


text:
Q: how to convert a ASN1_object to readable format using openssl library .? X509_extension  structure have a variable of ASN1_object . i want to read what is the content in that  .
Can any one tell me how to do that

A: An ASN1_OBJECT is just OpenSSL's representation of an OID, an object identifier. If you only want to know it's OID, then:
ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex); // ex is your X509_EXTENSION *
char buff[1024];
OBJ_obj2txt(buff, 1024, obj, 0); // 0 means it will prefer a textual representation (if available) rather than the numerical one

Then buf will contain a C string with the OID.
Regards.

A: You can access the data value of the object as int the code fragment below:
ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex);
char *dt_value = (char *)ext->value->data
printf("Object Value: %s\n", dt_value);


text:
Q: The trait bound `(): futures::Future` is not satisfied when using TcpConnectionNew I am trying to write a simple TCP client in Rust using Tokio crate. My code is pretty close to this example minus the TLS:
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;

use futures::Future;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_io::io;

fn main() {
    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let connection = TcpStream::connect(&"127.0.0.1:8080".parse().unwrap(), &handle);

    let server = connection.and_then(|stream| {
        io::write_all(stream, b"hello");
    });

    core.run(server).unwrap();
}

However, compilation fails with the error:
error[E0277]: the trait bound `(): futures::Future` is not satisfied
  --> src/main.rs:16:29
   |
16 |     let server = connection.and_then(|stream| {
   |                             ^^^^^^^^ the trait `futures::Future` is not implemented for `()`
   |
   = note: required because of the requirements on the impl of `futures::IntoFuture` for `()`

error[E0277]: the trait bound `(): futures::Future` is not satisfied
  --> src/main.rs:20:10
   |
20 |     core.run(server).unwrap();
   |          ^^^ the trait `futures::Future` is not implemented for `()`
   |
   = note: required because of the requirements on the impl of `futures::IntoFuture` for `()`

I find it strange because according to the documentation it should be implemented.
I'm using

*

*Rust 1.19.0

*futures 0.1.16

*tokio-core 0.1.10

*tokio-io 0.1.3

What am I missing?

A: TL;DR: remove the semicolon after io::write_all.

Review the definition of and_then:
fn and_then<F, B>(self, f: F) -> AndThen<Self, B, F>
where
    F: FnOnce(Self::Item) -> B,
    B: IntoFuture<Error = Self::Error>,
    Self: Sized,

The closure (F) has to return some type (B) that can be converted into a future (B: IntoFuture) with an error type that matches the starting closure (Error = Self::Error).
What does your closure return? (). Why is that? Because you've placed a semicolon (;) at the end of your line. () does not implement the trait IntoFuture, which is indicated by the error message part "on the impl of futures::IntoFuture for ()":
impl<F: Future> IntoFuture for F {
    type Future = F;
    type Item = F::Item;
    type Error = F::Error;
}

Removing the semicolon will cause the Future returned by io::write_all to be returned back to and_then and the program will compile.
In general, futures work by combining together smaller components which are themselves futures. All of this works together to build a single large future which is essentially a state machine. It's good to keep this in mind, as you will almost always need to return a future when using such combinators.

A: Unfortunately the answer here is quite specific, but the question turns up for any kind of search for:

the trait futures::Future is not implemented for ()

A typical scenario for this kind of error is:
foo.then(|stream| {
    // ... Do random things here
    final_statement();
});

This causes an error because the majority of the extension functions require the return type to implement IntoFuture. However, () does not implement IntoFuture, and by terminating the block with a ; the implicit return type is ().
However, IntoFuture is implemented for Option and Result.
Rather than just randomly removing semicolons vaguely in the hope this will somehow magically make your code compile, consider:
You should be returning something that can be converted into a Future using IntoFuture.
If you don't have a specific promise that you're returning, consider returning Ok(()) to say simply 'this is done' from your callback:
foo.then(|stream| {
    // ... Do random things here
    final_statement();
    return Ok(()); // <-- Result(()) implements `IntoFuture`.
});

Note specifically I terminate this block with an explicit return statement; this is deliberate. This is a typical example of how the ergonomics of 'can omit semicolon to implicitly return object' is tangibly harmful; terminating the block with Ok(()); will continue to fail with the same error.


text:
Q: windows 7 desktop icons: new icon placement When moving/saving/etc a new file on the desktop, the icon appears second (just after "Computer"). I find it annoying, since I want my "special" icons to be first (such as the recycle bin, "Network", etc.).
Can this behavior be changed?

A: No.
Even on Eastern installs of Windows the icons fill the screen top-to-bottom left-to-right.
If you want a specific layout you'll have to reposition them.
You may want to consider desktop fences:

A: It should be posible to put icons wherever you want, like this:

*

*Right click on your Desktop.

*In the context menu, mouse over 'View' to expand it.

*Disable the 'Auto arrange icons' option.

Also, in Windows 7, you can also "pin" frequently used applications to the Taskbar! I find this a very handy feature which enables me to easily access the application I use the most.

*

*Right click on a running applications icon in the Task Bar.

*Click 'Pin this program to taskbar'.

Alternative solution:
If your goal it to keep your Desktop clean, you could also use Launchy. It gives you easy access to all your files and applications. Triggered by a hotkey, you just start typing the name of the file or the application you wish to access, and hit enter when you get the match you want. It's very nice for those of us to wish the Desktop clean! I use this, and I've disabled all Desktop icons.


text:
Q: ASP.NET: Built-in Gridview Sorting of Generic.List(Of T) The question is whether built-in sorting of a Generic.List(Of T) is possible. We have a custom gridview that is compiled into its own DLL along with a compiled DLL of classes. Right now, I'm able to get the count by casting a Generic.List to iCollection for paging purposes, but can I create some sort of Sort function that will accept any Generic.List(Of AnyType) and sort accordingly.
I've been able to cast a Generic.List(Of AnyType) to a Generic.List(Of Object), and I think I can cast the objects within that collection to the same type and sort, but I'm not sure if that's possible. My concern now is that I won't be able to cast the objects back to their original type due to the classes being in a compiled state.
Is this a safe assumption, or is it possible to do this? Is it more favorable to simply skip the control sorting for Generic Lists and simply allow the developer to do the sorting in the event via LINQ or other means.

A: Generic lists already have Sort (and Count too since it implements ICollection)
    public void Sort();
    public void Sort(IComparer<T> comparer);
    public void Sort(int index, int count, IComparer<T> comparer);
    public void Sort(Comparison<T> comparison);

Why not use those?
public class SomeGridViewWrapper<T>
{
    private List<T> _dataSource;

    public void Sort(Comparison<T> comparison)
    {
        _dataSource.Sort(comparison);
    }
}


text:
Q: Angular 2+ - ngModel doesn't bind initial values to selects made in ngFor loop If I create select inputs in ngFor loop, and then bind values by ngModel to some array - these selects don't get their initial values from this array (like it creates only a one-way binding). Here is quick example in plunker:
https://plnkr.co/edit/LX7XyrHcMGH8avZYA0pv?p=preview
@Component({
  selector: 'my-app',
  template: `
    <div *ngFor="let select of test; let i = index" >
      <select name="test" [(ngModel)]="vals[i]">
        <option *ngFor="let item of select" [ngValue]="item">{{item.lol}}</option>
      </select>
    </div>
    <div style="display: flex">
      <div *ngFor="let val of vals; let last = last;">
        {{val.lol}}{{last? '' : ','}}
      </div>
    </div>
  `,
})
export class App {
  test: any = [
    [{ lol: '1' }, { lol: '2' }, { lol: '3' }],
    [{ lol: '4' }, { lol: '5' }, { lol: '6' }],
    [{ lol: '7' }, { lol: '8' }, { lol: '9' }],
  ];
  vals: any[] = [{ lol: '1' }, { lol: '4' }, { lol: '7' }];
  constructor() {}
}

A: Using [compareWith] in this example solves this issue
UPDATE:
While it fixed the example, in my code ngModel was updating value of only one select input, generated by ngFor. For me setting [ngModelOptions]="{standalone: true}" has solved the issue. Hope it helps someone...


text:
Q: Query to get top 2 and 3 rd Records from a Table I have a table list of Student:
Student         SECTION
student1        A
student2        A
student3        A
student4        A
student5        B
student6        B
student7        B
student8        B

I want to get total Randomly 5 Students
3 A Section Students and
2 B Section Students
Done any once a Suggest a Simple SQL Query
Example : I want to club the below queries Randomly
select * from student where SECTION='A' LIMIT 3
select * from student where SECTION='B' LIMIT 2

A: You are pretty close:
(select * from student where SECTION = 'A' order by rand() LIMIT 3
) union all
(select * from student where SECTION = 'B' order by rand() LIMIT 2
)
order by rand();

The subqueries use order by rand() to get random students with each grade.  The outer order by rand() randomizes the five students.
Note:  This is the simplest way to accomplish what you want.  If the students table is even moderately large and performance is an issue, there are alternative solutions.

A: You can use UNION along order by like
(select * from student where SECTION='A' ORDER BY RAND() LIMIT 3)
UNION
(select * from student where SECTION='B' ORDER BY RAND() LIMIT 2)


text:
Q: FreeBSD: mariadb55 conflicts mysql55 I'm trying to install percona-toolkit as package/port on my system:
[root@alexus ~]# uname -a
FreeBSD alexus.org 9.2-RELEASE-p5 FreeBSD 9.2-RELEASE-p5 #0 r265974: Wed May 14 07:57:04 PDT 2014     root@jj3.myibay.com:/usr/obj/usr/src/sys/R610  amd64
[root@alexus ~]# pkg install percona-toolkit
Updating FreeBSD repository catalogue...
FreeBSD repository is up-to-date.
All repositories are up-to-date.
Checking integrity... done (1 conflicting)
Checking integrity... done (0 conflicting)
The following 7 packages will be affected (of 0 checked):

Installed packages to be REMOVED:
    mariadb55-client-5.5.39
    mariadb55-server-5.5.39

New packages to be INSTALLED:
    percona-toolkit: 2.2.11
    p5-Term-ReadKey: 2.32
    p5-DBI: 1.631
    p5-DBD-mysql: 4.028
    mysql55-client: 5.5.40

The operation will free 100 MB.

Proceed with this action? [y/N]: n
[root@alexus ~]# cd /usr/ports/databases/percona-toolkit/ && make config
===> No options to configure
[root@alexus /usr/ports/databases/percona-toolkit]#

I do NOT wish to remove and/or replace my existing mariadb55-client and/or mariadb55-server with mysql55-client.
What should I do?

A: Looks like p5-DBD-mysql was the one at "fault":
[root@alexus /usr/ports/databases/percona-toolkit]# pkg install p5-DBD-mysql
Updating FreeBSD repository catalogue...
FreeBSD repository is up-to-date.
All repositories are up-to-date.
Checking integrity... done (1 conflicting)
Checking integrity... done (0 conflicting)
The following 4 packages will be affected (of 0 checked):

Installed packages to be REMOVED:
    mariadb55-client-5.5.39
    mariadb55-server-5.5.39

New packages to be INSTALLED:
    p5-DBD-mysql: 4.028
    mysql55-client: 5.5.40

The operation will free 107 MB.

Proceed with this action? [y/N]: n
[root@alexus /usr/ports/databases/percona-toolkit]#

yet I was able to install it anyway using:
[root@alexus /usr/ports/databases/percona-toolkit]# make -C WITH_MYSQL_VER=55m install
...
...
...
===>  Installing for percona-toolkit-2.2.11
===>  Checking if percona-toolkit already installed
===>   Registering installation for percona-toolkit-2.2.11
[root@alexus /usr/ports/databases/percona-toolkit]# echo "WITH_MYSQL_VER=55m" >> /etc/make.conf
[root@alexus /usr/ports/databases/percona-toolkit]#


text:
Q: Payslip in multiple currency in Odoo I want to generate two types of payslip in Odoo, one for employee who belongs to USA and one for employee who belongs to India. My Base / default currency is INR. Now I when I try to generate payslip for USA employees, I want USD currency in payslip, but I am getting payslip in INR. Please tell me how to handle this scenario
Please Note I have already set configuration for Multiple currency in settings.

A: ّ know the question is a while ago but maybe can help.
You can set currency in account of net salary rule, by that your journal Entries will post in this currency but payslip stay working with company main currency
You will have two net salary rule and two salary structure for employees group, each one has rule with different currency

A: One of friend help me on this issue. To handle this situation, I have to create two company with two different currency and while creating employee I have set respective company. This way it will generate payslip in different currency. I hope this answer will help others.


text:
Q: how to edit a form in react using formik var fname,
  gender,
  city = "";

this.props.data.map((row, index) => {
  // console.log(index);
  if (this.props.selectedVal === index) {
    gender = row[0];
    fname = row[1];
    city = row[2];
  }
  return [];
});

return (

    <Dialog
      open={this.props.open}
      onClose={this.handleClose}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
    >

Edit User

      <DialogContent>
        <DialogContentText id="alert-dialog-description" />
        <form onSubmit={handleSubmit}>
          <TextField
            type="text"
            margin="dense"
            id="firstname"
            label="Name"
            onChange={handleChange}
            value={fname}
            {...props}
          />

          <TextField
            type="text"
            margin="dense"
            id="gender"
            label="gender"
            onChange={handleChange}
            value={gender}
            {...props}
          />

          <TextField
            type="text"
            margin="dense"
            id="city"
            label="city"
            onChange={handleChange}
            value={city}
            {...props}
          />
        </form>
      </DialogContent>
      <DialogActions>
        <Button onClick={this.handleClose} color="primary">
          RESET
        </Button>
        <Button onClick={this.handleClose} color="primary" autoFocus>
          SUBMIT
        </Button>
      </DialogActions>
    </Dialog>

);
};
render() {
return (

    <Formik
      initialValues={{
        name: this.props.fname,
        gender: this.props.gender,
        city: this.props.city
      }}
      onSubmit={initialValues => console.log("values" + initialValues.name)}
      render={this.form}
    />

);
}
}

Here i am getting the values from table while click on a specific row. I'm getting these values in a dialog using formik. Now i want to edit this formik form. I faced a problem. These values are not edited. How to edit these readonly values.
I added my codesandbox link codesandbox

A: The way you are doing things is not correct. Some of the functions which you are using never exist.
Here is the working demo of your code Codesandbox demo
Please take a look at the code and understand how it is transformed between two components and feel free to ask me if you have any queries/get stuck understanding the code.


text:
Q: Thread Pool performance I'm trying to understand the advantage of using thread pools, i wrote this code to see the time improvement of fixed thread pool.
First, i set the number of threads in the pool to 1 and it took approximately 920 ms, then i changed the number of threads in the pool to 2(and 3,4,5,6,7...) and it took 1200 ms, shouldn't it be faster when the threads are running concurrently?
When i changed it to cached thread pool it also took 1200 ms
package threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Example3 {

public static void main(String[] args) {

    new Example3();

}

public Example3() {

    try {
        testFixedPool(1);
      //testFixedPool(2);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

public void testFixedPool(int numberOfThreads) throws InterruptedException {

    ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);

    long start = System.currentTimeMillis();

    executor.execute(new TaskPrintInteger(0, 10000));
    executor.execute(new TaskPrintInteger(1, 10000));
    executor.execute(new TaskPrintInteger(2, 10000));
    executor.execute(new TaskPrintInteger(3, 10000));
    executor.execute(new TaskPrintInteger(4, 10000));
    executor.execute(new TaskPrintInteger(5, 10000));
    executor.execute(new TaskPrintInteger(6, 10000));
    executor.execute(new TaskPrintInteger(7, 10000));
    executor.execute(new TaskPrintInteger(8, 10000));
    executor.execute(new TaskPrintInteger(9, 10000));
    executor.shutdown();

    while(!executor.isTerminated()){
    }

    System.out.println();
    System.out.println((System.currentTimeMillis()) - start);
}

private class TaskPrintInteger implements Runnable {

    private int number, times;

    public TaskPrintInteger(int number, int times) {

        this.number = number;
        this.times = times;
    }

    @Override
    public void run() {

        for (int i = 0; i < times; i++) {
            System.out.println(number);
        }

    }

}

}

A: You are asking many threads to all carry out one activity, that is most likely (although not guaranteed to be) synchronized:
System.out.println(number);

Lets imagine that you have one person, and you ask her to write "one" 10 times on a piece of paper, one word on each line.
Now, you need to write "one" and "two" each 10 times on a piece of paper with one word on each line; which will be faster?

*

*use the same one person you used above

*ask that the person to bring a friend to write the "two"s. Except that the rules are that they start at one end of a hall, and both run to the paper. The one who gets there first, writes their word.  Now they run back to the other end of the hall and repeat the process until all the words are written.

I would hazard a guess that the first alternative would be faster.
Imagine the same scenario with 5 people all trying to write their word 10,000 times? Chaos? Yes!
If you want to see real improvements from threading, tasks should be completely isolated with no synchronization. And especially no IO!

A: When you have a contented resources, the optimal number of threads can be 1. Writing to the console is expensive and single threaded, so when you use multiple threads you are increasing the overhead, rather than making your program faster. Threads work best when they run independently.


text:
Q: NodeJs DataPumps with PostgreSQL: Process Hangs Hi I started learning node.js three days ago and i have been trying  to use datapumps. So far I am running node js with Express and the problem is that my process function never runs. I see this console.log("Ready To Pump");  in the logs so I am able to tell that the function is called. However it seems like the process hangs. (not sure). The process function is not called because console.log("We are in the Process"); part of the code does not show in the logs. Where have i gone wrong here. I also know my connection string works because i have onother function that uses the same query and logs the data to the console. I intend to transfer data from one postgre database to another. And certainly i cant do that if my process function is never called. I do not get any errors in the console either. I believe it hangs because console.log("Done"); does not show either
var dpumps =require('datapumps');
Pump = dpumps.Pump;
PostgresqlMixin= dpumps.mixin.PostgresqlMixin;
QueryStream = require('pg-query-stream');
Client = require('pg').Client;

var con = {
    host: 'localhost',
    port: 5432,
    database: 'mydatabase',
    user: 'myuser',
    password: 'mypass'
};

postgresqlClient = new Client(con) ;

exports.pump = function () {
    console.log("Ready To Pump"); //This logs so i know the function is called.
    postgresqlCopy = new Pump()
        .from(postgresqlClient.query(new QueryStream("SELECT $1~, $2~, $3~ FROM $4~ LIMIT 10",["RowId", "Company", "ArticleNo", "Article"])))
        .mixin(PostgresqlMixin(postgresqlClient))
        .process(function(data) {
            console.log("We are in the Process");
            return postgresqlCopy.log(data) ;
        })
        .logErrorsToConsole()
        .run()
        .then(function() {
            console.log("Done");
            console.log(postgresqlClient)
        });

};

I am referring to this I think there are some syntax errors there though

A: Add .catch(console.error) after then() so you will see if the is some error that is unhandled


text:
Q: 220v to 12v circuit problem good afternoon i bulid a circuit to convert 220v ac to 12v dc so i can power a 12v dc relay. once i attach the output to the relay the voltage drop to 2v once i disconnect it and attach the positive 12v to the relay it work but then i have the disconnect it again if i want to powr it again.

A: Although your circuit may produce 12 V for your relay in principle, I suspect that the impedance of your R-C network is too high at your load current. I have no calculations to back that up, though.
The issue that I see is danger, in the case of a component failure. In your circuit, a diode failing to short-circuit could put mains onto your low-voltage relay and risk a fire. Unless it is critical to your application to save space or parts cost, I would strongly recommend using a step-down mains transformer and bridge rectifier instead.
As a component, the reliability of a transformer will be extremely high and it will ensure that your load circuit cannot receive a dangerously high voltage. Otherwise you are avoiding a fire or similar damage only if every component works well for the lifetime of the circuit. The cost savings will look very unimportant in that light.
As I imagine you know, electronics and circuit design are only a part of engineering. Electrical safety and reliability are just as important, as are cost, environmental safety, suitability for test, suitability for servicing and a good few more.
I have designed equipment for approval to worldwide electrical standards, and before CE marking made it much easier. We used to export my designs of office equipment into 45 countries. To meet many of these approvals, our mains circuitry (PSUs, cabling) had to stay safe and protected under Single Point Of Failure (SPOF) conditions. This means that an engineer from an approving body would visit and open-circuit any single PSU/mains component or solder a short-circuit across it. The equipment would be switched on and operated and was required to not suffer a fire or present any safety hazard to the user.
In that environment, designing mains circuitry with SPOF protection becomes a lifelong discipline that you always follow. Unfortunately, your circuit is far from safe under such testing. I hope this information helps.

A: I think the coupling C is too small, or the resistance is too high. simple calculation. R1 + R2. If R1 is too big, most voltage will be on R1.


text:
Q: How to filter one pandas dataframe dates on the basis of other dataframe I have one dataframe, I need to filter the dates on the basis of start and end date of the other dataframe
example set is given below. What is the best way in pandas to achieve that?
Considering sample dataframes as below, I have included the expected result set
df1

ID all_date   clicks
1  2019-08-21   5
1  2019-08-22   4
2  2019-07-18   5
2  2019-07-21   5
2  2019-07-23   6

df2

ID start_date  end_date
1  2019-08-21 2019-08-21
2  2019-07-18 2019-08-21

expected output:
df1

ID all_date   clicks
1  2019-08-21   5
2  2019-07-18   5
2  2019-07-21   5

A: You can melt and then merge:
First better to convert dates as datetimes just incase they are strings:
df1.all_date=pd.to_datetime(df1.all_date)
df2[['start_date','end_date']]=df2[['start_date','end_date']].apply(pd.to_datetime)

df1.merge(df2.melt('ID',value_name='all_date').drop('variable',1),on=['ID','all_date'])

   ID   all_date  clicks
0   1 2019-08-21       5
1   1 2019-08-21       5
2   2 2019-07-18       5

Details, after melt you get:
df2.melt('ID',value_name='all_date').drop('variable',1)

   ID   all_date
0   1 2019-08-21
1   2 2019-07-18
2   1 2019-08-21
3   2 2019-08-21

Then join on 'ID','all_date' on both the dataframes


text:
Q: Finding the strut length for 2 poses of Stewart Platform Goal 1: Find a strut length p2, with the parameters x1 = 5, (x2, y2) = (0,6), L1 = L3 = 3, L2 = 3√2, γ = π/4, p1 = 5, p3 = 3, for which there are only two poses.
Goal 2: Calculate the intervals in p2, with the same parameters, for which there are 0, 2, 4, and 6 poses respectively.
All needs to be done using python.
I am extremely new to python. This is supposed to be a group project but half my group has ghosted.
I have some code for a function that gives me x and y and graphs the function. I am fairly certain that for the first part p2 is 4 from some previous problems. I feel like I need to find the roots of the function with p2 = 4, to prove there are only two poses? Also my plot looks like crap. I can't figure out how to use plt.plot properly.
Here's the code I've written so far.
import math
import sympy
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from sympy import symbols
from sympy.plotting import plot
from scipy.optimize import fsolve

def function_file_out(theta, x1, x2, y2):
    L1 = 3
    L2 = 3*sympy.sqrt(2)
    L3 = 3
    p1 = 5
    p2 = 4
    p3 = 3
    yVal = sympy.pi/2

    A2 = L3*sympy.cos(theta)-x1
    B2 = L3*sympy.sin(theta)
    A3 = L2*sympy.cos(theta+yVal)-x2
    B3 = L2*sympy.sin(theta+yVal)-y2

    first = B3*((p2**2) - (p1**2) - (A2**2) - (B2**2))
    second = -B2*((p3**2) -( p1**2) - (A3**2) - (B3**2))
    N1 =  first + second
    third = -A3*((p2**2) - (p1**2) - (A2**2) - (B2**2))
    fourth = A2*((p3**2) - (p1**2) - (A3**2) - (B3**2))
    N2 = third + fourth
    D = 2*(A2*B3 - B2*A3)

    out = (N1**2) + (N2**2) - (p1**2) * (D**2)
    x = N1 / D
    y = N2 / D

    return out

x = symbols('x')
plot(function_file_out(x, 5, 0, 6), (x,-sympy.pi,sympy.pi))

I'm not really very sure about the second part at all. Any and all assistance is greatly appreciated.


text:
Q: Why does the Send-Email Program Freeze? I made a small program in which I can basically send an email through the yahoo smtp server. My Code:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

                try
                {

                    MailMessage message = new MailMessage();
                    message.From = new MailAddress("myid@yahoo.com");
                    message.To.Add("anotherid@yahoo.com");
                    message.Subject = "afdasdfasfg";
                    message.Body = "Hgfk4564267862738I";
                    message.IsBodyHtml = true;
                    message.Priority = MailPriority.High;
                    SmtpClient sC = new SmtpClient("smtp.mail.yahoo.com");
                    sC.Port = 587;
                    sC.Credentials = new NetworkCredential("myid", "mypassword");
                    //sC.EnableSsl = true;
                    sC.Send(message);
                    MessageBox .Show ("Mail Send Successfully");

                }
                catch (Exception ex)
                {
                    MessageBox .Show (ex + "Mail Sending Fail's") ;

                }
            }

        }
    }

The bizarre thing is that it worked for the first week. I could send messages with no problem. Then just yesterday, the program just starts freezing and doesn't respond( I didn't change the code). Why did this happen? How can I mend my program?
Edit:  @Andreas Niedermair Right now I just tried the program and left it for a whole minute then an error showed:ContextSwitchDeadlock was detected
Message: The CLR has been unable to transition from COM context 0x21eb78 to COM context 0x21ece8 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.
Thanks for your help!

A: does your catch ever get reached?
i assume, that you are not patient enough to reach the default value of the Timeout property (100seconds)...
you could decrease the value to get an earlier completion.
as long as you are not working with an async-pattern, your UI-thread gets blocked anyway. an alternative would be to use the SendAsync method (there are sample implementations in the msdn-entries for the specific methods).
Edit:
as the author mentioned a possible fu**ed port: yes, it could be. but you would have to read the specification paper, which tells us:

*

*SMTP server: plus.smtp.mail.yahoo.com

*Use SSL

*Port: 465

*Use authentication

*Account Name/Login Name: Your Yahoo! Mail ID (your email address without the "@yahoo.com", for example, "testing80")

*Email Address: Your Yahoo! Mail address (for example, testing80@yahoo.com)

*Password: Your Yahoo! Mail password

*[...] try setting the SMTP port number to 587 when sending email via Yahoo!'s SMTP server.

but even if you meet the specifications: you should really go for the async-pattern :)
Edit:
the mentioned exception is related to COM ... a bit googeling, and i've found this:

What's probably happening is that you
  have a COM object in a form, and
  you're doing work on the UI thread. If
  your UI gets blocked by the processing
  for >60 seconds, the COM component can
  complain.

Edit:
otherwise: did you change anything within the exceptions-dialog of visual studio? then this could be your solution, or this one (with some basic explanation)...

A: As per Andreas Niedermair edit the issue is you are blocking the main thread for more than 60 secconds. The best thing to do is put this operation on a background thread.
using System;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;

namespace Sandbox_Form
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            bw = new BackgroundWorker();
            bw.DoWork +=new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if(e.Error != null)
                MessageBox.Show(e.Error.ToString() + "Mail Sending Fail's") ;
            else
                MessageBox.Show("Mail Send Successfully");
        }

        BackgroundWorker bw;

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            using(MailMessage message = new MailMessage())
            {
                message.From = new MailAddress("myid@yahoo.com");
                message.To.Add("anotherid@yahoo.com");
                message.Subject = "afdasdfasfg";
                message.Body = "Hgfk4564267862738I";
                message.IsBodyHtml = true;
                message.Priority = MailPriority.High;
                using(SmtpClient sC = new SmtpClient("smtp.mail.yahoo.com"))
                {
                    sC.Port = 587;
                    sC.Credentials = new NetworkCredential("myid", "mypassword");
                    //sC.EnableSsl = true;
                    sC.Send(message);
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            bw.RunWorkerAsync();
        }
    }

}

EDIT:
per  Andreas Niedermair suggestion, here is a version using the async method instead.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {

            MailMessage message = new MailMessage();
            message.From = new MailAddress("myid@yahoo.com");
            message.To.Add("anotherid@yahoo.com");
            message.Subject = "afdasdfasfg";
            message.Body = "Hgfk4564267862738I";
            message.IsBodyHtml = true;
            message.Priority = MailPriority.High;
            SmtpClient sC = new SmtpClient("smtp.mail.yahoo.com");
            sC.Port = 587;
            sC.Credentials = new NetworkCredential("myid", "mypassword");
            //sC.EnableSsl = true;
            //sC.Send(message);
            sC.SendCompleted += new SendCompletedEventHandler(sC_SendCompleted);
            sC.SendAsync(message, null);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex + "Mail Sending Fail's");
        }

    }

    void sC_SendCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if(e.Error != null)
            MessageBox.Show(ex + "Mail Sending Fail's");
        else
            MessageBox.Show("Mail Send Successfully");
    }
}


text:
Q: S3 PutObject Doubling in size when saving to bucket (Java / Spring Webflux) I have a problem similar in uploading to S3 like this one but in Java:
S3 PutObject in AWS Lambda (via Node) is doubling filesize when saving to bucket
I'm trying to get binary input from postman and setup the Content-Type to application/octet-stream.
Here is my input in postman:

Here is my code in the handler:
public Mono<ServerResponse> upload(ServerRequest serverRequest) {
        return serverRequest
            .bodyToMono(ByteArrayResource.class)
            .flatMap(resource -> build(Mono.just(resource.contentLength()), Long.class, HttpStatus.OK));}

I tried checking the size of the ByteArrayResource, upon running on my local the size is equal to 368348 (the correct one) but on aws lambda the size is doubled 708233.
I can upload without a problem when running the app using gradle bootRun, but on aws lambda the file is corrupted.
Are there any setup that I need to make? I've tried adding / in Api Gateway but it didn't work either. Thanks!


text:
Q: How do i alter the step for time input for IOS? I want to have a time input using html5 in ios. I have tried using the step="900" attribute to allow only intervals of 15 minutes, which works when running it in the browser, but not on my ipad which is what im developing for.
<input type="time" id="deliveryTime" value="09:00:00"  step="900">

However in IOS this still displays every minute 00-59.
Can anyone help?

A: Right now, iOS Safari does not support the min, max, or step attributes for time input fields.
See: http://caniuse.com/#feat=input-datetime

A: For some reason iOS Chrome is not mentioned on caniuse.com but it does not handle "step" either.


text:
Q: Excel formula countif for 3rd condition I am having working formula for 2 conditions and I need 3 condition to be added
IF(COUNTIF(M12:M34,"FAIL")>0,"FAIL","PASS")
Now I need to look at cells from M12 to M34 and if all the cells are blank, then add 3rd condition "NOTRUN"
Your help is much appreciated. Thanks in advance

A: You can add another IF Formula at the beginning to add your 3rd condition.
So you would end up with:
=IF(COUNTIF(M12:M34,"")=ROWS(M12:M34),"NOTRUN",IF(COUNTIF(M12:M34,"FAIL")>0,"FAIL","PASS"))

In general when you need to add several conditions, you can always simply add an If condition in the "Value if True" or "Value if False" from your first If formula which would give you something as below:
If(A=1,"Result A",If(A=2,"Result B", IF(A=3,"Result C","No Result")))


text:
Q: Possible lenghts in an irreducible root system
If a root system $R$ is irreducible (not a product of two root systems) then $R$ does not contain three vectors of pairwise different lengths.

To show this do we need just to compute all the angles and the ratios between the root lenghts as explained (1) in the following post:
Two questions on roots of finite, simple, complex lie algebra
Howeber how the fact that $R$ is irreducible is involved here?

A: This is proven e.g. in Bourbaki, Lie Groups and Algebras vol. VI §1 no.4 Proposition 12; or in Humphreys, Introduction to Lie Algebras and Representation Theory, §10.4, Lemma C.
We have (see e.g. Dietrich Burde's answer to Two questions on roots of finite, simple, complex lie algebra):

(*) If $\alpha, \beta$ are two roots which are not perpendicular to each other, and w.l.o.g. $(\alpha, \alpha) \le (\beta, \beta)$, then
$$\dfrac{(\beta, \beta)}{(\alpha, \alpha)} \in \{1,2,3\}.$$

Now assume an irreducible root system $\Phi$ (in its Euclidean space $E$) contains three roots $\alpha, \beta, \gamma$ of mutually different lengths. W.l.o.g. $(\alpha, \alpha)=1$. Now the obvious idea is that if e.g. $(\beta, \beta) = 2$ and $(\gamma, \gamma)=3$, we would have $\dfrac{(\gamma, \gamma)}{(\beta, \beta)} =\frac32 \notin \{1,2,3\}$ in contradiction to the above. The problem is that a priori, some or all of our three roots could be perpendicular to each other. And indeed one can easily construct such examples if the root system is not irreducible, e.g. in $A_1 \times A_1 \times A_1$, which is made up of three mutually orthogonal roots (and their negatives), each of them can have any positive length you want.
To exclude that, we need to move our roots around a bit until they are not orthogonal to each other. We do that with the Weyl group $W$ of our root system
Fact: $\{w(\alpha): w \in W\}$ spans $E$. (And for this we need irreducibility.)
This implies that for any root $\phi$, there is some $w \in W$ such that $w(\alpha)$ is not perpendicular to $\phi$ (because if they all were, so would be their span $E$, but that contains $\phi \in \Phi$).
In particular, there is a $w_1\in W$ such that $\alpha':=w_1(\alpha)$ is not perpendicular to $\beta$, and a $w_2\in W$ such that $\alpha'' := w_2(\alpha)$ is not perpendicular to $\gamma$. Since it's clear or easily proven that for any $w \in W$, $(w(\phi),w(\phi))= (\phi, \phi)$, this allows us to use (*) for the first time and infer w.l.o.g. that $(\beta, \beta) = 2$ and $(\gamma, \gamma)=3$. But then we apply the fact again to find $w_3$ with $w_3(\beta)$ not perpendicular to $\gamma$, and can conclude as wanted.


text:
Q: Iterate over individual bytes in Python 3 When iterating over a bytes object in Python 3, one gets the individual bytes as ints:
>>> [b for b in b'123']
[49, 50, 51]

How to get 1-length bytes objects instead?
The following is possible, but not very obvious for the reader and most likely performs bad:
>>> [bytes([b]) for b in b'123']
[b'1', b'2', b'3']

A: A trio of map(), bytes() and zip() does the trick:
>>> list(map(bytes, zip(b'123')))
[b'1', b'2', b'3']

However I don't think that it is any more readable than [bytes([b]) for b in b'123'] or performs better.

A: I use this helper method:
def iter_bytes(my_bytes):
    for i in range(len(my_bytes)):
        yield my_bytes[i:i+1]

Works for Python2 and Python3.

A: If you are concerned about performance of this code and an int as a byte is not suitable interface in your case then you should probably reconsider data structures that you use e.g., use str objects instead.
You could slice the bytes object to get 1-length bytes objects:
L = [bytes_obj[i:i+1] for i in range(len(bytes_obj))]

There is PEP 0467 -- Minor API improvements for binary sequences that proposes bytes.iterbytes() method:
>>> list(b'123'.iterbytes())
[b'1', b'2', b'3']

A: int.to_bytes
int objects have a to_bytes method which can be used to convert an int to its corresponding byte:
>>> import sys
>>> [i.to_bytes(1, sys.byteorder) for i in b'123']
[b'1', b'2', b'3']

As with some other other answers, it's not clear that this is more readable than the OP's original solution: the length and byteorder arguments make it noisier I think.
struct.unpack
Another approach would be to use struct.unpack, though this might also be considered difficult to read, unless you are familiar with the struct module:
>>> import struct
>>> struct.unpack('3c', b'123')
(b'1', b'2', b'3')

(As jfs observes in the comments, the format string for struct.unpack can be constructed dynamically; in this case we know the number of individual bytes in the result must equal the number of bytes in the original bytestring, so struct.unpack(str(len(bytestring)) + 'c', bytestring) is possible.)
Performance
>>> import random, timeit
>>> bs = bytes(random.randint(0, 255) for i in range(100))

>>> # OP's solution
>>> timeit.timeit(setup="from __main__ import bs",
                  stmt="[bytes([b]) for b in bs]")
46.49886950897053

>>> # Accepted answer from jfs
>>> timeit.timeit(setup="from __main__ import bs",
                  stmt="[bs[i:i+1] for i in range(len(bs))]")
20.91463226894848

>>>  # Leon's answer
>>> timeit.timeit(setup="from __main__ import bs",
                  stmt="list(map(bytes, zip(bs)))")
27.476876026019454

>>> # guettli's answer
>>> timeit.timeit(setup="from __main__ import iter_bytes, bs",
                  stmt="list(iter_bytes(bs))")
24.107485140906647

>>> # user38's answer (with Leon's suggested fix)
>>> timeit.timeit(setup="from __main__ import bs",
                  stmt="[chr(i).encode('latin-1') for i in bs]")
45.937552741961554

>>> # Using int.to_bytes
>>> timeit.timeit(setup="from __main__ import bs;from sys import byteorder",
                  stmt="[x.to_bytes(1, byteorder) for x in bs]")
32.197659170022234

>>> # Using struct.unpack, converting the resulting tuple to list
>>> # to be fair to other methods
>>> timeit.timeit(setup="from __main__ import bs;from struct import unpack",
                  stmt="list(unpack('100c', bs))")
1.902243083808571

struct.unpack seems to be at least an order of magnitude faster than other methods, presumably because it operates at the byte level.  int.to_bytes, on the other hand, performs worse than most of the "obvious" approaches.

A: I thought it might be useful to compare the runtimes of the different approaches so I made a benchmark (using my library simple_benchmark):

Probably unsurprisingly the NumPy solution is by far the fastest solution for large bytes object.
But if a resulting list is desired then both the NumPy solution (with the tolist()) and the struct solution are much faster than the other alternatives.
I didn't include guettlis answer because it's almost identical to jfs solution just instead of a comprehension a generator function is used.
import numpy as np
import struct
import sys

from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()

@b.add_function()
def jfs(bytes_obj):
    return [bytes_obj[i:i+1] for i in range(len(bytes_obj))]

@b.add_function()
def snakecharmerb_tobytes(bytes_obj):
    return [i.to_bytes(1, sys.byteorder) for i in bytes_obj]

@b.add_function()
def snakecharmerb_struct(bytes_obj):
    return struct.unpack(str(len(bytes_obj)) + 'c', bytes_obj)

@b.add_function()
def Leon(bytes_obj):
    return list(map(bytes, zip(bytes_obj)))

@b.add_function()
def rusu_ro1_format(bytes_obj):
    return [b'%c' % i for i in bytes_obj]

@b.add_function()
def rusu_ro1_numpy(bytes_obj):
    return np.frombuffer(bytes_obj, dtype='S1')

@b.add_function()
def rusu_ro1_numpy_tolist(bytes_obj):
    return np.frombuffer(bytes_obj, dtype='S1').tolist()

@b.add_function()
def User38(bytes_obj):
    return [chr(i).encode() for i in bytes_obj]

@b.add_arguments('byte object length')
def argument_provider():
    for exp in range(2, 18):
        size = 2**exp
        yield size, b'a' * size

r = b.run()
r.plot()

A: since python 3.5 you can use % formatting to bytes and bytearray:
[b'%c' % i for i in b'123']

output:
[b'1', b'2', b'3']

the above solution is 2-3 times faster than your initial approach, if you want a more fast solution I will suggest to use numpy.frombuffer:
import numpy as np
np.frombuffer(b'123', dtype='S1')

output:
array([b'1', b'2', b'3'],
      dtype='|S1')

The second solution is ~10% faster than struct.unpack (I have used the same  performance test as @snakecharmerb, against 100 random bytes)

A: A short way to do this:
[bytes([i]) for i in b'123\xaa\xbb\xcc\xff']


text:
Q: Disable and Enable Click event using Jquery Could you please advise how to disable /enable the click function using jquery api. Based on the role i have show the sports page to the user.
Using below bootstrap code for UI.
<div id="viewtest" class="btn-group btn-group-sm">
    <button id="C" class="btn btn-default" title="Cricket">Cricket</button>
    <button id="B" class="btn btn-default" autofocus="autofocus" autofocus title="BaseBall">BaseBall</button>
    <button id="T" class="btn btn-default disabled" title="Tennis">Tennis</button>
    <button id="G" class="btn btn-default disabled " title="Monthly">Golf</button>
</div>

I am using below function to handle the above buttons click events.
$(".btn-group > .btn").click(function () {
    $(this).addClass("btn-primary").siblings().removeClass("btn-primary");
    viewtype = this.id;
    $(this).blur();
    showPage();
});

For some criteria , i am disabling the click event using below function
var disableOptionsTabs=["C","T"];
        disableButtons(disableOptionsTabs);

function disableButtons(mybuttons) {
    $.each(mybuttons, function (key, value) {
        $("#" + value).off();
    });
}

Please advise how to enable the click event? or how to bind the click function for button.
I am using below method ,bind the click event for the specify buttons based on given advise . but it's not working.
 var enableOptionsTabs=["C","T"];
            enableButtons(enableOptionsTabs);
    function enableButtons(mybuttons){
           $.each( mybuttons, function( key,value )
           { $( "#" + value ).on("click",myOnClick);  }
          );

    }

A: If you are going to continually remove and add the event I would move the click functionality to a function you can reuse.
function myOnClick () {
    $(this).addClass("btn-primary").siblings().removeClass("btn-primary");
    viewtype = this.id;
    $(this).blur();
    showPage();
}

Then you can attach it like so:
$(".btn-group > .btn").on('click', myOnClick);

And remove it like so:
$(".btn-group > .btn").off('click');

As for the disabling loop if mybuttons is a list of elements you can just do this:
function disableButtons(mybuttons) {
    $.each(mybuttons, function () {
        $(this).off('click');
    });
}

You can because of how jQuery calls the function you pass it to each. It sets the context of that function for every element so you can just reference it using this.

A: I got answer from the below link ,
Best way to disable button in Twitter's Bootstrap
function disableButtons(mybuttons){
             $.each( mybuttons, function( key,value )
      {         $("#" + value).prop('disabled', true)     }
      );

    }
    function enableButtons(mybuttons){
       $.each( mybuttons, function( key,value )
       {

       $("#" + value).prop('disabled', false);
       $("#" + value).removeClass("disabled");

       }
      );

    }


text:
Q: Cannot find .NET SDK 6.0 on Rocky Linux 8 I have to build my .NET project on Rocky Linux 8 machine, but I cannot find dotnet-sdk-6.0 package from package manager. It seems that recent .NET version is 5. How can I find .NET 6 on Rocky Linux 8?

A: I found this article, which installs dotnet-sdk-6.0 on Rocky Linux 8 manually.


text:
Q: Error Attaching IAM Role to an Instance Profile I am trying to attach an IAM role to an instance profile for aws karpenter to be able to provision nodes on my behalf. I have already created the role, role-karpenter, from the console.
Below is the terraform script:
data "aws_iam_role" "karpenter_node_group_role" {
  name = "role-karpenter"
}

resource "aws_iam_instance_profile" "karpenter" {
  name = "KarpenterNodeInstanceProfile"
  role = data.aws_iam_role.karpenter_node_group_role.name
}

This is the Error I am getting:
removing role arn:aws:iam::xxxx:role/role-karpenter from IAM instance profile KarpenterNodeInstanceProfile-cluster: ValidationError: The specified value for roleName is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-
│   status code: 400, request id: 7e631745-e7cb-4542-b19f-2b3872c8cbc3

Options I have tried:
I have used all these different terraform attribute references for the role
# name attribute
role = data.aws_iam_role.karpenter_node_group_role.name

# id attribute
role = data.aws_iam_role.karpenter_node_group_role.id

# arn attribute
role = data.aws_iam_role.karpenter_node_group_role.arn

A: The fix for me was to remove the resource from the state file and rerun it again
terraform state rm module.eks.aws_iam_instance_profile.karpenter

Then
terraform plan && terraform apply


text:
Q: HLS streaming, advices about segment size configuration we are developing a mobile application which will need to play 10 seconds videos.
The first version will only support iOS (iPhone & iPad). To have a good quality on all devices we will use Adaptive Streaming.
I thorougly read the Apple HLS documentation and it seems that 10 seconds is a good tradeoff for the size of the HLS segments.
So if we use the default 10 seconds in our case segmentation is not really useful.
As we are on a Mobile app with very small videos I'm wondering if for some devices / network conditions changing this 10s "default" to a smaller value could be better ?
Is it possible to speed-up the starting of the video by lowering this value ?
I suppose the 10 seconds "default" we find everywhere is a good choice and advice for videos which have to be played "everywhere" (Desktop, Smartphone, Tablet), but perhaps an other value would be more appropriate for Smartphones only ?
Finally do you think that in our case HLS is not a good choice and that simply using progressive download of an MP4 video is better?
Thanks in advance for your responses.

A: Mp4 will be better. Adaptive streaming works well for long content, but very poorly for short videos. The player will not have enough time to to adapt, and your viewers you almost always just see the default quality.
Apple only requires HLS for videos that are longer than X seconds (I cant remember exactly what X is, but it is larger than 10)


text:
Q: Re-Sign unsigned ipa using AirSign issue I am using AirSign to sign an unsigned ipa.
Under Code Signing tab->Re-Signing configuration->Provisioning Profile NONE is the only option available and I am not able to select any provisioning profile. "CodeSign Application" option is disabled.
Anyone who has worked on this and faced same issue?


text:
Q: Lightning-map is not getting updated as I am updating the map-marker through JS in LWC On a click of a button I am setting the latitude and longitude in the map-marker but lightning-map is updating/refreshing.
Here is the code:
HTML:
<template>
<lightning-button label='Click' onclick={handleClick}></lightning-button>
    <lightning-map
        map-markers={mapMarkers}
    >
  </lightning-map>
</template>

JS:
import { LightningElement, track } from 'lwc';

export default class Lwc_map extends LightningElement {

    @track mapMarkers=[];

    handleClick(event){
        this.mapMarkers={
            location: {
                Latitude: '28.535517',
                Longitude: '77.39103',

            }

        }
        window.console.log('Set'+ JSON.stringify(this.mapMarkers));
    }
}

Pls,suggest me method how i can update lightning-map on a click in lwc.

A: mapMarkers is an array so you should put the content like this
 this.mapMarkers = [...this.mapMarkers, {
            location: {
                Latitude: '28.535517',
                Longitude: '77.39103',

            }

        }];


text:
Q: Get Variable from String Parameter MySQL PHP I am having some trouble implementing a RecordResults for a specified event id. It needs to be able to do - the event entry listed at the bottom of the page should include a
hyperlink that will take the administrator to a new web form for recording results for that event. The
EventID is passed via a query string parameter, e.g. RecordResults.php?EventID=4.
At the current time I have this code to show:
Records Data into Database
   <?php
mysql_connect("localhost", "root", "") or die(mysql_error());

mysql_select_db("clubresults") or die(mysql_error());

if (isset($_POST['submit'])) {
$EventDate = date('D-m-y', $EventDate);
$sql="INSERT INTO events (EventName, EventDate, Location)
VALUES
('".$_POST['EventName']."', '".$EventDate."', '".$_POST['EventLocation']."')";

$add_event = mysql_query($sql);

echo "Successfully Added 1 Event";
}
?>

HTML Form + Generate Table from MySQL Database -

 Add Event To Database

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Event Name: <input type="text" name="EventName" />

Event Date: <input type="text" name="EventDate" />

Event Location: <input type="text" name="EventLocation" />

<input type="submit" name="submit" value="Add Event" />
</form>

<?php

$query = "SELECT * FROM events";
$result = mysql_query($query) or die ('Error in Query');

echo '
';

echo '
Event ID	Event Name	Event Date	Event Location	 Record Results
';

while ($row=mysql_fetch_row($result))

{

echo '
';

echo ''.$row[0].'	';

echo ''.$row[1].'	';

echo ''.$row[2].'	';

echo ''.$row[3].'	';

echo '
';

}

echo '
';

mysql_free_result($result);

?>

I have also been working on this however am not sure how to use this to make a add results hyperlink for each row in the table which passes the URL String.
    // Get id from URL
$id = mysql_real_escape_string( $_GET['EventID'] );

// If id is number
if( (int)$id== $id && (int)$id> 0 ) {

     // Get record from database
     $sql = 'SELECT * FROM Evernts WHERE EventID=' . $id;
     $result = mysql_query( $sql, $link );
     $row = mysql_fetch_array( $result );

     // Show record with HTML here - Need to show it in the table!
     print_r( $row );

} else {

   echo "Record not found";
}

Any help would be appreciated!
Thanks :D

A: Here is an answer with some advice.

*

*Try to be consistent when you name things. You have variables that start with a capital letter such as $EventDate, some not like $result and some with underscores $add_event. Use camelCase to name your variables. The same goes with you table column names in your database : you have EventName, EventDate and then Location...

*Try to understand what you do. PHP is kind of permissive and won't complain with instructions like $EventDate = date('D-m-y', $EventDate);. You don't need to declare variable so it will evaluate $EventDate to 0 ($EventDate = date('D-m-y', 0)). Read the manual if you don't know what a function do or how to use it.

*Do not use the star character in your select queries. Name explicitly all the columns you want to retrieve.

*You have to learn outdated ways of doing things in PHP and it's a shame for you teacher. So be aware of better solutions such as PDO and prepared or quoted statements.

From what I understand you want to display all the events from the database in a HTML table.
And have the possibility to add an event via a form.
You also want to link the event to a record results page passing the event id as a parameter in the URL (you are not clear on this). index.php

    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("clubresults") or die(mysql_error());

    if (isset($_POST['submit']))
    {
        $eventName = mysql_real_escape_string($_POST['EventName']);
        $eventLocation = mysql_real_escape_string($_POST['EventLocation']);
                    // if you want to retrieve the date via the form
                    // you have to check the format so that it corresponds to
                    // what your date column expects (default format is Y-m-d)
        $eventDate = date('Y-m-d');

        $sql = "
            INSERT INTO events (EventName, EventDate, EventLocation)
            VALUES (
                '" . $eventName . "',
                '" . $eventDate . "',
                '" . $eventLocation . "'
            )";

        $addEventQueryResult = mysql_query($sql);

        if ($addEventQueryResult)
        {
            echo "Successfully added 1 event";
        }
        else
        {
            echo "Error adding the event";
        }
    }
    ?>

Add Event To Database

    <form action="index.php" method="post">
        Event Name: <input type="text" name="EventName" />

        Event Date: <input type="text" name="EventDate" />

        Event Location: <input type="text" name="EventLocation" />

        <input type="submit" name="submit" value="Add Event" />
    </form>

    <?php

    $query = "
        SELECT EventId, EventName, EventDate, EventLocation
        FROM events";

    $result = mysql_query($query) or die ('Error in Query');

    echo '
';

    echo '

            Event ID
            Event Name
            Event Date
            Event Location
            Record Results

';

    while ($row = mysql_fetch_assoc($result))
    {
        $addResultLink =
                'Add Results';

        echo '
'
                . '' . $row['EventId'] . '	'
                . '' . $row['EventName'] . '	'
                . '' . $row['EventDate'] . '	'
                . '' . $row['EventLocation'] . '	'
                . '' . $addResultLink . '	'
           . '
';
    }

    echo '
';

    mysql_free_result($result);
    ?>

Here is the recordResults.php which retrieve an event based on the event id in the URL and display the event with the same HTML table than above. Do whatever you want next. Note: this code should be refactor so you don't write the same HTML table twice.
<?php

    date_default_timezone_set('Europe/Paris');

    mysql_connect("localhost", "root", "sqlflo54") or die(mysql_error());
    mysql_select_db("clubresults") or die(mysql_error());

    // Get id from URL
    $id = mysql_real_escape_string($_GET['EventId']);

    // If id is number
    if ($id > 0)
    {
         // Get record from database
         $sql = "
            SELECT EventId, EventName, EventDate, EventLocation
            FROM events
            WHERE EventId = " . $id;
         $result = mysql_query($sql);

         echo '
';

         echo '

                Event ID
                Event Name
                Event Date
                Event Location

';

         while ($row = mysql_fetch_assoc($result))
         {
            echo '
'
                    . '' . $row['EventId'] . '	'
                    . '' . $row['EventName'] . '	'
                    . '' . $row['EventDate'] . '	'
                    . '' . $row['EventLocation'] . '	'
               . '
';
         }

         echo '
';

         mysql_free_result($result);
    }
    else
    {
       echo "Record not found";
    }
?>

I hope this will eventually help you understand what you want to do.
Don't copy and paste this code because I changed some of the variable names to stick with the above advice.


text:
Q: Ensuring asyncronous '.then()' execution in compound promises I am using Typescript to write JS promises. I have a compound promise, i.e. promise which returns a promise
I have:
test() {
    addElement("first")
        .then(
            function (val){
                addElement("second");
                console.log("second*);
            })
            .then(
            function (val){
                addElement("third");
                console.log("third*");
            });
}

export function addElement(elementText){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            resolve();
        }, Math.random() * 2000);
    })
    .then(console.log(elementText));
}

I would like these functions to print out, first, second*, second, third*, third. However, I get:

JS: first
  JS: second*
  JS: third*
  JS: third
  JS: second

How do I get the then to execute after the called promises' then has completed?

A: You're not returning your promise in the then block. If you don't return the promise, then the then block will return undefined immediately, and nothing will wait for it. If you return a promise instead, then execution of the promise chain will pause until the promise you return has been satisfied.
test() {
    addElement("first")
        .then(
            function (val){
                console.log("second*");
                return addElement("second");
            })
            .then(
            function (val){
                console.log("third*");
                return addElement("third");
            });
}

Though I don't personally consider it a "rookie mistake", your description matches "Rookie Mistake #5" in Nolan Lawson's "We have a problem with promises"; read on for a more in-depth explanation.


text:
Q: Spring - List required headers for each controller We have a requirement to list all request mappings with their parameters and their headers (both mandatory and optional).
I did manage to log all the request mappings with their parameters like this.
But how can I have a list of what headers are processed for any address?
I think there might be some way to read this information from the configurations (preferably on the runtime).
For example, I want the result to indicate that for a request to /app/foo the required headers are Content-type, Cookie, and referer. But for /app/bar the only required header is Content-type.


text:
Q: Theoretically if you passed the speed of light in a medium, would there be a sonic boom equivalent? I know that it is technically impossible to reach the speed of light in vacuum since the mass of the object travelling would reach infinity. However in a medium, would there be some sort of theoretical equivalent to a sonic boom that would occur? Since sonic booms are formed when sound waves can't catch up with an object, could the same happen with light waves? Would it look like an immense burst of light in the sky?

A: To leave an answer that addresses the question, which was answered in comments but comments are not permanent here:

in a medium, would there be some sort of theoretical equivalent to a sonic boom that would occur?

It is called Cerenkov radiation and it is continually utilized in high energy physics detectors and cosmic ray experiments.

It is  the electromagnetic radiation emitted when a charged particle (such as an electron) passes through a dielectric medium at a speed greater than the phase velocity of light in that medium. The characteristic blue glow of an underwater nuclear reactor is due to Cherenkov radiation.

You ask:

Since sonic booms are formed when sound waves can't catch up with an object, could the same happen with light waves? Would it look like an immense burst of light in the sky?

Light waves are built up in synchrony by a large number of photons. Cerenkov radiation is radiation from one elementary point particle one photon at a time, and the build up into light one sees here :

NRC photo of Cherenkov effect in the Reed Research Reactor.

comes from innumerable electrons with random directions exceeding the speed of light in the medium.
The sonic boom comes from one airplane , a single electron emits Cerenkov radiation  practically continuously on its path, similar to the energy dissipation of the sonic boom, but the electron "boom" is a whisper as far as detectors go.
An interesting aside: a veteran particle physicist of the first days of creating beams and experiments, told me that he centered the beam by the Cerenkov light in his eyes.


text:
Q: How to remove body.onload when we click a link I want to do a browser redirect using this function:
<script type="text/javascript">
window.onload=function(){
    window.setTimeout(function(){
        window.location.href = "mypage.html";
    }, 20000);
}
</script>

But I want to give user a way to stop the onload when click stop link, below is my code:
(<a href="javascript:void()" style="text-decoration:underline; color:#FFFF00" onclick="window.onload()=null" id="stop"> stop </a>)
but, onload function still not stopped, I am just a beginner student in javascript, plz help me how to stop onload function when we click stop

A: To unset the event handler, you have to assign null to window.onload
window.onload = null;

However, this will not fix your problem as you have started a timer at that point. That's what you need to remove.
Firstly, store a reference to your timeout in a variable:
var redirectTimeout = window.setTimeout(function() {
    window.location.href = "mypage.html";
}, 20000);

And then use clearTimeout to stop the timer:
window.clearTimeout(redirectTimeout);


text:
Q: Dynamic routes with static parts on express js I'm trying to do a path for express like that catches this types of url:
/events/0.json

What I've tried is... (and It's not correct):
router.put('/events.json/:id.json', isLogged, events.update);

Is it possible to do it with express?

A: Yes, that will catch the pattern x.json where x is 1 or more characters.
So /events/0.json will save '0' in req.params.id.  Note that id is string, not number.  You have to convert if you want that as a number to do number arithmetic or to put it in database as number/int type


text:
Q: qtserialport... error: 'Q_NULLPTR' was not declared in this scope Am trying to install qt creator following these sequences suggested by a hardware provider...
sudo apt-get install libudev-dev
git clone git://code.qt.io/qt/qtserialport.git && cd qtserialport
git checkout origin/old/5.2
cd ..
mkdir qtserialport-build && cd qtserialport-build
qmake ../qtserialport/qtserialport.pro
make && sudo make install

cd ../qtserialport/ && git checkout origin/5.3
cd ../qtserialport-build/
make

But am getting errors at the last make:
In file included from /home/polar/soft/lib/qt/qtserialport/src/serialport/qserialport.cpp:45:0:
/home/polar/soft/lib/qt/qtserialport/src/serialport/qserialport.h:190:44:

error: 'Q_NULLPTR' was not declared in this scope
     explicit QSerialPort(QObject *parent = Q_NULLPTR);
                                            ^

On stackoverflow some suggested to add QMAKE_CXXFLAGS += -std=c++0x, others CONFIG += c++11 to the .pro file. These did not work for me.... In fact there are at least two .pro files... which one I need amendment?
Any suggestions please?

A: the Q_NULLPTR is declared int the header file qserialportglobal.h ,so you just need to do is  #include  in the qserialport.h file


text:
Q: jQuery Div Scrolling Function: Issue in IE I'm currently developing a website that that has a fixed banner div that is centered, and I'm using the jQuery below to ensure that it scrolls correctly even though it is a fixed positioned div.
jQuery:
$(window).scroll(function() {

    $('#top-content').css('left', -$(this).scrollLeft() + "px");

});

However, I have come across an issue within IE(version 9). The issue is that when the user scrolls the website (creating a minus left margin on the "top-content" div, to give the effect of scrolling) and then if they maximize the webpage, the left margin is still present causing the div to not be centered.
I have attempted to remedy this with the jQuery below, but as of yet no luck
$(window).resize(function() {

    if ($("#top-content").width() < $(window).width()) {

        $('#top-content').css('left:0px');

    }

});

Any ideas?

A: You better do
$('#top-content').css('left', '0px');

In your resize event.


text:
Q: famd/gamin timeout issue with courier-imap I'm running a mail server for about 200 users with courier-imap on Debian 7.  This server is running a linux kernel 2.6.38 inside a Xen guest having 2 cpu cores and 2 GB RAM.  The server accept incoming mail through postfix, but resources intensive checks (amavis, spamassassin) are delegated to another server.
Lately I'm running into IMAP performance issues with client connections being dropped randomly.  The load on the server is not low, but it is also not that high, even at times when those connection drops are happening.  At peak times, I have about 120 simultaneous imap clients and 5 min load is < 1.
I've noticed the connection drops appear at the same time as the following log lines on my server:
imapd: FAMPending: timeout

I guess that when FAM is timing out, the imap server returns some kind of error and, depending on the client, the error is dealt with gracefully or not (some webmail clients do not like that).
The regular Debian courier-imap package requires a fam implementation, I have the choice of using famd or gamin.  I've tried both and both are running into those timeouts.  It seems to me gamin produces a lower load on the server, but still timeouts are occurring.
I'm wondering if there is anything I can tune to improve the fam/gamin performance and to avoid the timeout messages.  There is not much to configure in the daemons.  However, could it be that I'm running out of file descriptors or inotify resources?  How could I check that?
Or do you think a better choice would be to upgrade my Xen guest or to move away from courier-imap?


text:
Q: What is the best practice for cleaning up unused fields or fields that haven't been used in a long time? I have been tasked with cleaning up fields across our org that are not in use or haven't been used in some time period. For each field of an object, I want to know when the last time its value was updated on a record (NOT when the configuration of the field was updated). I have tried apps like FieldTrip and FieldPro, but these only show me the last date when the config of the field was changed. I am currently tracking a subset of fields, then manually checking field history for the last update date, but I am limited to 20/object at a time and this doesn't seem very efficient. Does anyone have better recommendations or an easier way that I can determine unused fields?

A: One native way is to run Salesforce Optimizer from setup
Salesforce Optimizer analyzes a suite of features and sends you a personalized report about how you can improve your implementation. You can run Optimizer for both sandbox and production environments.
You will get a personalized report on your instance. Specific to your requirement you will get fields related statistics.
For more information, refer this link :- Find fields that are not in use


text:
Q: XSLT - Combining Information from different Elements/Nodes I have a project that I'm working on to learn XML and after trying multiple times and searching for answers online I reached a dead-end.
I have this XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" version ="1.0" href='Information Management Project 2.xsl'?>
<task1>
    <normlist>
        <norm>
            <normID>1</normID>
            <name>EN ISO 13857</name>
            <keywords>Security</keywords>
            <keywords>Engines</keywords>
            <replacement />
        </norm>
        <norm>
            <normID>2</normID>
            <name>EN ISO 13849-1</name>
            <keywords>Security</keywords>
            <keywords>Engines</keywords>
            <keywords>Controlling</keywords>
            <replacement>1</replacement>
        </norm>
    </normlist>
    <puplicationlist>
        <title>
            <name>Norms for Engine Security</name>
            <filename>caise2011sgln.pfd</filename>
            <normIDREFS>1 2</normIDREFS>
        </title>
        <title>
            <name>Setting up Complex Engines</name>
            <filename>coopis2012sln.pdf</filename>
            <normIDREFS>2</normIDREFS>
        </title>
    </puplicationlist>
</task1>

Now I need to come up with an XSLT that shows the following:
The first column contains the norm name, the second column contains the file names of the publications referring to the norm.
Something like that:
I tried it with different approaches but non of them worked and in the end I always get displayed just the norm names:

Example attempt with Key():
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name='norm2publication' match='task1/normlist/norm' use= 'normID'/>
<xsl:template match="/">

                Norm
                Publications

             <xsl:for-each select='task1/normlist/norm'>

                <xsl:value-of select='name'/>
                <xsl:for-each select="key('norm2publication', 'task1/publicationlist/title/normIDREFS')/filename">
                    <xsl:value-of select='task1/publicationlist/title/filename'/>
                </xsl:for-each>

             </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

For reasons of space I paste the other attempts as an image:
normID=normIDREFS:
variable:
What do I need to change in the XSLT to get the expected result?

A: The format of your input XML is very inconvenient for what you want to do (at least in pure XSLT 1.0). Apparently, the authors intended to take advantage of the  ID/IDREFS  feature - however, this can work only if the XML document has a DTD and the XSLT processor knows how to read it.
Without this, you need to find a way to match a normID to a normIDREFS which may contain multiple values in a space-delimited string. You cannot use a key for this, unless you tokenize the string first. Since XSLT 1.0 does not have a tokenize() function (though some processors support extension functions for this), I suggest you try this primitive approach instead:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/task1">

                    Norm
                    Publications

                <xsl:for-each select="normlist/norm">

                            <xsl:value-of select="name"/>

                            <xsl:for-each select="//puplicationlist/title[contains(concat(' ', normIDREFS, ' '), concat(' ', current()/normID, ' '))]" >
                                <xsl:value-of select="filename"/>

                            </xsl:for-each>

                </xsl:for-each>

</xsl:template>

</xsl:stylesheet>

Applied to your input example, this will produce:
Result

            Norm
            Publications

            EN ISO 13857
            caise2011sgln.pfd

            EN ISO 13849-1
            caise2011sgln.pfd
coopis2012sln.pdf

Rendered as:


text:
Q: Bash script, ask for user input, to change a directory, sub directorys, and file's mtime atime linux recursively Using
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
I am a bash scripting novice, not sure where to begin except at shebang #!.
The following command.

*

*touch -a -m -t 201501010000.00 somefile.txt, will modify "somefile.txt" access time and modification time.

*Is there a way to have a bash script?

*

*Operating within the directory "/mnt/harddrive/BASE/"

*Prompt user input for. "somefilename.txt", or "somedirectoryname".

*Prompt user input for. "datetime sequence". Instead of using the current time-stamp, explicitly specify the time/date using -t and -d options.

*Recursively change/modify. "atime", "mtime" on "sub-directory's" within the BASE directory and "files" within that "sub-directory".
AND

*Change/modify. "atime", "mtime" of "somefilename.txt" located in the "/mnt/hardrive/BASE/" directory.

Optional 6. Append "mtime" to "somefilename" and "somedirectoryname" before the file extension. ie: "somefilename-01-01-2015.txt" or "somedirectoryname-01-01-2015". Prompt user: do you want to append "mtime" to "somefilename.txt" "YES/NO" if "YES/NO" continue.

*stat the directory and file output to the console or "/tmp" directory text file and display with cat then delete the "sometmpfile" rm -r.

A: It could look like this:
#!/bin/bash

# 1. change directory
cd "/mnt/harddrive/BASE/"

# 2. prompt for name of file or directory
echo -n "file or directory name: "
# ...  and read it
read HANDLE

# 2. b - check if it exists and is readable
if [ ! -r "$HANDLE" ]
then
    echo "$HANDLE is not readable";
    # if not, exit with an exit code != 0
    exit 2;
fi

# 3. prompt for datetime
echo -n "datetime of file/directory: "
# ... and read it
read TIMESTAMP

# 4. set datetime for HANDLE (file or directory + files)
find $HANDLE | xargs touch -a -m -t "$TIMESTAMP"

# 5. ask, if the name should be changed
echo -n "change name of file by appending mtime to the name (y/n)?: "
# ... and read it
read YES_NO
if [ "$YES_NO" == "y" ]
then
    # get yyyy-mm-dd of modification time
    SUFFIX_TS=$(stat -c "%y" $HANDLE  | cut -f 1 -d" ")
    # rename, supposed, the suffix is always .txt
    mv $HANDLE $(basename $HANDLE txt)-$SUFFIX_TS.txt
    # let HANDLE hold the name for further processing
    HANDLE=$HANDLE-$TIMESTAMP.$SUFFIX
fi

# 7. stat to console
stat $HANDLE

This is just partly tested, but should be a start.
To get a an understanding of what is happening here, you should look up the following commands:
echo, read, test, cut, touch, find, xargs
Besides you should understand several basic bash concepts, i.e. parameter substitution, command substitution and pipes.


text:
Q: Windows 11 taskbar very tall in one out of three monitors I have 3 monitors. In one of the monitor the taskbar is very tall. I am not able to figure out how to make it normal.
See screenshot
Tall

Normal


text:
Q: How do you created a shared folder within Xcode? I'm studying a code sample from a reference book. The author assumes I know how to create a shared folder.

I don't.

How do I create a share folder within the Project Navigator where I can share resources/codes amongst targets?

A: Naturally, all the files in your Xcode project can be shared amongst targets.
You don't need to do anything specific. The folder name Shared is a little bit misleading here.
You need to look for the target membership panel in this view:

To do it, just select a file inside code navigator, then press cmd-alt-1 and inside this menu, you will have file based settings for target memberships that look like this:

You can also choose multiple files to change their target settings accordingly.


text:
Q: How to immediately kill a thread which is waiting for network operations? So, I'm creating a download manager, and I've designed every bit specifically so that it can be shut down at any second without giving it the time to clean up. However, I can't seem to find a way to kill my downloader threads. I tried using Thread.Abort (actually, that's my way of giving them time to clean up: they catch the ThreadAbortException and handle it themselves), but as you can already guess, it's no good. I'd use a flag or something, but when a thread is waiting for a network operation to complete, it's pretty much blocked completely. Any ideas on how to at least interrupt the network operation so I can shut down without waiting a noticeable amount of time?
Here's the relevant piece of code:
try
{
    Request.AddRange(StartPosition, EndPosition);
    Owner.SetDefaultRequestParameters(Request);

    Response = Request.GetResponse() as HttpWebResponse;
    ResponseStream = Response.GetResponseStream();

    var Buffer = new Byte[Downloader.BUFFER_SIZE];

    while (true)
    {
        Paused.Wait();

        if (bStopRequested)
            break;

        int Count = ResponseStream.Read(Buffer, 0, Buffer.Length); //gets stuck here
        if (Count == 0)
            break;

        MemoryStream.Write(Buffer, 0, Count);
        Downloaded += Count;
        CurrentStreak += Count;

        if (StartPosition + Downloaded >= EndPosition)
            break;

        if (MemoryStream.Capacity - CurrentStreak < Buffer.Length)
        {
            Owner.WriteToFile(MemoryStream, StartPosition + Downloaded - CurrentStreak, CurrentStreak);
            MemoryStream.Seek(0, SeekOrigin.Begin);
            CurrentStreak = 0;
        }
    }
}
catch (ThreadAbortException)
{
    try
    {
        Response.Close();
    }
    catch { }

    return; //fastest way I have found to shut the thread down, yet
}

EDIT: So, here's how I did it:
if (Request != null)
    Request.Abort();
if (Response != null)
    Response.Close();
ExecutionThread.Abort();

With this, no matter where the thread is stuck (getting a response or reading from the response stream) it will get cancelled and stop immediately.

A: You could Dispose the ResponseStream and then catch an ObjectDisposedException.
While this may work i suggest you design your application using CancellationToken to allow it to gracefully close instead of abruptedly aborting threads. You also might consider using async-await to make your application more scalable and non-blocking.

A: Not sure what the underlying socket does but if all fails you can directly bind to a socket in non blocking mode und use the Socket.BeginReceive method which will call your call back when data has arrived. If you do want to cancel the current operation you can call close simply the socket and thats it.
See MSDN

The asynchronous BeginReceive operation must be completed by calling
  the EndReceive method. Typically, the method is invoked by the
  callback delegate.
This method does not block until the operation is complete. To block
  until the operation is complete, use one of the Receive method
  overloads.
To cancel a pending BeginReceive, call the Close method.

You should check if you can get your hands on the underlying socket and try to close it.


text:
Q: Design pattern for accessing static data I have a scenario where I have a set of credentials for each environment
e.g. for dev env username1/pwd1, for qa env username2/pwd2, for staging username3/pwd3 and so on.
Now I want to create a class which will return me a set of credentials based on the env I feed to it.
All the data has to go within code (as per my brilliant boss, no xml files and all), what design pattern I could use so that the code will be elegant and data can be made extensible in future?

A: Personally, I am used to create a channel attribute:
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyChannelAttribute : Attribute
{
    public ChannelType Type { get; private set; }

    public AssemblyChannelAttribute(ChannelType type)
    {
        this.Type = type;
    }
}

public enum ChannelType
{
    Dev,
    Beta,
    PreProd,
    Prod
}

This attribute is set on the Assembly:
#if DEBUG
// In release mode, this attribute is set by the MSBuild script
[assembly: AssemblyChannel(ChannelType.Dev)]
#else

As the comment said, the value of the attribute is set on compile time by my MSBuild script (too tied to my project to show you this part).
Once you have setup all of this, you can create a simple singleton like this:
public class Credentials
{
    private static readonly Lazy<Credentials> instanceHolder =
        new Lazy<Credentials>(() => new Credentials());

    public IReadOnlyDictionary<string, string> Passwords { get; private set; }

    public Credentials Instance { get { return instanceHolder.Value; } }

    private Credentials()
    {
        var channel = typeof(Credentials).Assembly
            .GetCustomAttributes<AssemblyChannelAttribute>()
            .ElementAt(0)
            .Type;

        switch (channel)
        {
            case ChannelType.Dev:
                this.Passwords = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>
                {
                    ["User1"] = "Pwd1",
                    ["User2"] = "Pwd2",
                    // etc
                });
                break;
            case ChannelType.Beta:
                // etc
                break;
            case ChannelType.PreProd:
                // etc
                break;
            case ChannelType.Prod:
                // etc
                break;
        }
    }
}

Then you can access your credentials like this:
var password = Credentials.Instance.Passwords["User1"];

A: If you use .Net core, you could use the configuration techniques.
They are very powerful and work in asp .net as well as console programs
They are very configurable and composable (pass in config via cmd and json for example)
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration

A: What you're after is the Multiton design pattern.


text:
Q: std::enable_if - how to use own function as template argument I have class ModeSessions and 2 derived classes : ReadModeSessions and WriteModeSessions;
ModeSessions has a unique Mode type;
In Logic I collect in container every session with own unique type.
But now I stuck on template method to return proper session by given mode.
#include <QVector>
#include <QSharedPointer>
namespace states {
    enum class Mode{ read1, read2, write1, write2};
    constexpr bool modeIsReadType(Mode m){ return (m == Mode::read1 || m == Mode::read2)? true: false;}
    constexpr bool modeIsWriteType(Mode m){ return (m == Mode::write1 || m == Mode::write2)? true: false;}
}

class ModeSession{
public:
    states::Mode type;
};
using namespace states;
class ReadModeSession: public ModeSession{
public:
    ReadModeSession(Mode m){ModeSession::type = m;}
};
class WriteModeSession : public ModeSession{
public:
    WriteModeSession(Mode m){ModeSession::type = m;}
};
class Logic
{
public:
    Logic(){
        allModeSessions << QSharedPointer<ReadModeSession>(new ReadModeSession(Mode::read1));
        allModeSessions << QSharedPointer<ReadModeSession>(new ReadModeSession(Mode::read2));
        allModeSessions << QSharedPointer<WriteModeSession>(new WriteModeSession(Mode::write1));
        allModeSessions << QSharedPointer<WriteModeSession>(new WriteModeSession(Mode::write2));
    }
    QVector<QSharedPointer<ModeSession>> allModeSessions;
    template<class Tm> QSharedPointer<ReadModeSession>
        getMs(Tm m, typename std::enable_if<states::modeIsReadType(m), Tm>::type){
        for (QSharedPointer<ModeSession> ms: allModeSessions){
            if (ms->type == m) return ms.dynamicCast<ReadModeSession>();
        }
        return nullptr;
    }
    template<class Tm> QSharedPointer<WriteModeSession>
        getMs(Tm m, typename std::enable_if<states::modeIsWriteType(m), Tm>::type){ //to stack overflow....
        for (QSharedPointer<ModeSession> ms: allModeSessions){
            if (ms->type == m) return ms.dynamicCast<WriteModeSession>();
        }
        return nullptr;
    }
};

both template methods have
In file included from ..\enableIf\logic.cpp:1:0:
..\enableIf\logic.h:35:74: error: template argument 1 is invalid
         getMs(Tm m, typename std::enable_if<states::modeIsReadType(m), Tm>::type){
                                                                          ^
..\enableIf\logic.h:35:74: error: template argument 1 is invalid
..\enableIf\logic.h:35:74: error: template argument 1 is invalid
..\enableIf\logic.h:35:74: error: template argument 1 is invalid
..\enableIf\logic.h:35:35: error: invalid use of template-name 'std::enable_if' without an argument list
         getMs(Tm m, typename std::enable_if<states::modeIsReadType(m), Tm>::type){
                                   ^
..\enableIf\logic.h:35:44: error: expected ',' or '...' before '<' token
         getMs(Tm m, typename std::enable_if<states::modeIsReadType(m), Tm>::type){
                                            ^
..\enableIf\logic.h:42:75: error: template argument 1 is invalid
         getMs(Tm m, typename std::enable_if<states::modeIsWriteType(m), Tm>::type){ //to stack overflow....
                                                                           ^
..\enableIf\logic.h:42:75: error: template argument 1 is invalid
..\enableIf\logic.h:42:75: error: template argument 1 is invalid
..\enableIf\logic.h:42:75: error: template argument 1 is invalid
..\enableIf\logic.h:42:35: error: invalid use of template-name 'std::enable_if' without an argument list
         getMs(Tm m, typename std::enable_if<states::modeIsWriteType(m), Tm>::type){ //to stack overflow....
                                   ^
..\enableIf\logic.h:42:44: error: expected ',' or '...' before '<' token
         getMs(Tm m, typename std::enable_if<states::modeIsWriteType(m), Tm>::type){ //to stack overflow....

I am not sure if I am doing right, trying to put my constexpr function inside , but there should be bool argument as I understand, and examples I follow have std::base_of or std::is_integer that use bool as return, so what's the difference?
I might consider another approaches, but the point is, that I need to care the sessions that have some common methods and unique for each type;
(Maybe taking out those methods to implement it in different new sessionManager class)