text:
Q: Calculating percentage based on python dictionaries I need help calculating each dict of dict date values to percentage.
raw_data = [{'name':'AB', 'date':datetime.date(2012, 10, 2), 'price': 23.80}, {'name':'AB', 'date':datetime.date(2012, 10, 3), 'price': 23.72}]

i have formarted above dictionary to below format using collection.
import collections
res = collections.defaultdict(dict)

for row in raw_data:
  row_col = res[row['name']]
  row_col[row['date']] = row['price']

  {'AB': {datetime.date(2012, 10, 2): 23.80,
  datetime.date(2012, 10, 3): 23.72,
  datetime.date(2012, 10, 4): 25.90,
  datetime.date(2012, 10, 5): 29.95}

Now i need to calculate above data into below format.
Calculation formula :
last price will dividend for all the top values
   Date                               Price   Percentage
   datetime.date(2012, 10, 5)         29.95      26%
   datetime.date(2012, 10, 4)         25.90      9%
   datetime.date(2012, 10, 3)         23.72      0%
   datetime.date(2012, 10, 2)         23.80      0

calculation goes like this
(23.72/23.80-1) * 100 = 0%
(25.90/23.80-1) * 100 = 9%
(29.95/23.80-1) * 100 = 26%

Any help really appreciate it.

A: You can grab a list of all the values in your dictionary with something like value_list =  res.values(). This will be iterable, and you can grab your price values with a for loop and list slicing. value_list[0] will then contain your lowest price that you're dividing everything by. Then depending on what you plan on doing with the data, you can use a for loop to calculate all the percentages or wrap it in a function and run it as needed.
Referenced: Python: Index a Dictionary?

A: import datetime
import collections

raw_data = [
{'name':'AB', 'date':datetime.date(2012, 10, 2), 'price': 23.80},
{'name':'AB', 'date':datetime.date(2012, 10, 3), 'price': 23.72},
{'name':'AB', 'date':datetime.date(2012, 10, 4), 'price': 25.90},
{'name':'AB', 'date':datetime.date(2012, 10, 5), 'price': 29.95}
]

#all unique names in raw_data
names = set(row["name"] for row in raw_data)
#lowest prices, keyed by name
lowestPrices = {name: min(row["price"] for row in raw_data) for name in names}

for row in raw_data:
    name = row["name"]
    lowestPrice = lowestPrices[name]
    price = row["price"]
    percentage = ((price/lowestPrice)-1)*100
    row["percentage"] = percentage

print raw_data

Output (newlines added by me):
[
{'date': datetime.date(2012, 10, 5), 'price': 29.95, 'percentage': 26.264755480607093, 'name': 'AB'},
{'date': datetime.date(2012, 10, 4), 'price': 25.9, 'percentage': 9.190556492411472, 'name': 'AB'},
{'date': datetime.date(2012, 10, 2), 'price': 23.8, 'percentage': 0.337268128161905, 'name': 'AB'},
{'date': datetime.date(2012, 10, 3), 'price': 23.72, 'percentage': 0, 'name': 'AB'}
]


text:
Q: Repeatable Code generation It is awfully often required to write repeatable pieces of code.
Consider the following example from Java (although, it may not be the best example, but I hope you get the general idea...)
String X = rs.getString("X");
Where X will have values: 'name','surname' ... and 20-30 other values.
(Another example would be an HTML code and any other code - you need to create for X)
The end result should be:
String name=rs.getString("name");
String surname=rs.getString("surname");
....

String whatever = rs.getString("whatever");

Here is another example with  html table and some scriplets, in this case string to replicate would be X	 and <%=myBean.getX()%>	 the end result would be:

    name
    surname
    ..
    whatever

    <%=myBean.getName()%>
    <%=myBean.getSurname()%>
    ..
    <%=myBean.getWhatever()%>

So, apart form copy-pasting the above for 30 times and then editing, the the only 'clever' way I found to deal with this is to use python, jinja2 library and write a small code generator.
But, in order to do that I had to install python, install the library, create a template, create a custom script to read values from a text file and then generate code for the values read.
I was wondering is there any easier way to achieve the above?
Any editor or plugin to support code generation?
I know that IDEs such as Netbeans, Eclipse can generate some code - like getters and setters ... etc, but it is not enough...
In a nutshell,
I want to regenerate some lines of code by altering only specific parts ... The question is how to achieve that easily? (I know the hard way to do this) ..I am seeking for ideas...

A: You can do that with a lightweight code generator like Telosys :

*

*http://www.telosys.org/

*https://modeling-languages.com/telosys-tools-the-concept-of-lightweight-model-for-code-generation/
In your case Telosys-CLI with a DSL model is probably the right choice, you'll just have to create your specific templates in Velocity language ( http://velocity.apache.org/ )

A: Probably I am looking for something that does not exist.
So, I'll just post my 'hard way' of achieving, what I have described in my question (in hope that this would be useful for somebody - sometime).
Here I will preset a small code generator I am using to generate java, html, jsp, xsd and other codes.
I am using Python27 and Jinja2-2.7.2
My Files:
InputData.txt
:This is field list
field1:field1 description
field2:field2 description
field3:field3 description
field4:field4 description
name:first name of the person
surname:last name of the person
whatever:whatever you need

CodeGenerator.py
import jinja2
import codecs
templateLoader = jinja2.FileSystemLoader( searchpath="." )
templateEnv    = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE  = "CodeGenerator.jinja"
template       = templateEnv.get_template( TEMPLATE_FILE )
COLUMNS        = [tuple(line.split(':')) for line in codecs.open( "InputData.txt", "r", "utf-8" )]
COLUMNS        = map(lambda s: (s[0],(s[0].strip().title(),s[1].strip())), COLUMNS)
#title() copy of the string in which first characters of all the words are capitalized.
#strip()  copy of the string, all chars have been stripped from the beginning and the end
#lambda s --> (field1,(Field1,field1 description))
#ignore the first line
COLUMNS.pop(0)
#add variables to work with
templateVars = { "table" : "MyTableName",
                 "description" : "A simple code generator",
                 "columns" : COLUMNS
               }

outputText = template.render( templateVars )
f = open('Generated.txt', 'w')
outputText = outputText.encode('utf-8')
f.write(outputText)
f.close()
print outputText

CodeGenerator.jinja
//------------------model------------------------
//Generated code for model
import java.io.Serializable;
public class {{table|capitalize}}_Model implements Serializable{
{%for columnName,columnTitle in columns%}
private String {{columnName|lower}};{%endfor%}

{% for columnName,columnTitle in columns %}
public void set{{columnName|capitalize}}(String {{columnName|lower}}){
  this.{{columnName|lower}}={{columnName|lower}};
}
public String get{{columnName|capitalize}}(){
  return this.{{columnName|lower}};
}
{% endfor %}
public {{table|capitalize}}_Model({% for columnName,columnTitle in columns %}String {{columnName|lower}}{% if not loop.last %},{% endif %}{% endfor %}){
        {% for columnName,columnTitle in columns %}
  this.{{columnName|lower}}={{columnName|lower}}; {% endfor %}
    }
public String toString(){

return {% for columnName,columnTitle in columns %}"{{columnName|lower}}:" + this.{{columnName|lower}}{% if not loop.last %}+{% endif %}{% endfor %};

}

}
//------------------model------------------------
//-----------------getStrings--------------------
{% for columnName,columnTitle in columns %}
 String {{columnName}}=rs.getString("{{columnName}}");
{% endfor %}
//----------------------------------------------
//------------------jsp example-----------------
{% for columnName,columnTitle in columns %}
<s:label  cssStyle ="margin-top:5px;color:blue;" value="{{columnTitle[1]}} :" id="{{columnName}}_label"/>
<s:textfield label="{{columnTitle[1]}}" name="myBean.{{columnName}}" />
{% endfor %}
//------------------jsp example-----------------

A: In such scenarios, the best thing you could do is to use a constant array together with a HashMap. The constant array will hold keynames for the hashmap whereas the hashmap will also hold the value for each one.
For instance:
String[] keys = {"name", "surname", "whatever" };
HashMap<String, String> elements = new HashMap<String, String>();
for (String key : keys)
{
    elements.put(key, rs.getString(key));
}

You just have to be careful that all the elements are from the same type. If they are not, you will have to either store them as Objects and then cast them.
EDIT: for using in a Scriptlet, a good idea would be:

    <% for (String key : keys)
       {
    %>
    <%= elements.get(key)%>
    <% } %>

A: In IntelliJ we have "Live Template" feature that you use to generate part of the code.
For example, when you type "sout" , IntelliJ suggests "System.out.println".
When you type "main" , Eclipse suggests "public static void main(String[] args)"
You can create something like that for pieces of code that are very commom.

A: If I understand your problem correctly, you have a ResultSet with a lot of columns. And you do not want to get them one by one.
It is possible to get all the columns from a ResultSet the following way:
ResultSetMetaData metaData = resultSet.getMetaData();
for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) {
    String columnName = metaData.getColumnName(columnIndex);
    String value = resultSet.getString(columnIndex);
}

Granted all the values will b e represented as strings in this example, but you can determine the type of the column also by using the same metaData object. Read more about it in the documentation: https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stage 301 redirect in .htaccess For a page relaunch I have to redirect some old urls.
Most of them work fine... expl:
Redirect 301 /en/agency/profile/ /agency

But some of them show a really strage results expl:
Redirect 301 /en/brands/name-of-project/ /en/projects/name-of-project/

-> leads to:
/en/projectsname-of-project/
So it somehow ignore one slash.
Any ideas what could be the problem here?
Here is the rest of the .htaccess (default stuff of Kirby CMS, comes before my redirects)
# Kirby .htaccess
# revision 2020-06-15

# rewrite rules
<IfModule mod_rewrite.c>

# enable awesome urls. i.e.:
# http://yourdomain.com/about-us/team
RewriteEngine on

# make sure to set the RewriteBase correctly
# if you are running the site in a subfolder;
# otherwise links or the entire site will break.
#
# If your homepage is http://yourdomain.com/mysite,
# set the RewriteBase to:
#
# RewriteBase /mysite

# In some environments it's necessary to
# set the RewriteBase to:
#
# RewriteBase /

# block files and folders beginning with a dot, such as .git
# except for the .well-known folder, which is used for Let's Encrypt and security.txt
RewriteRule (^|/)\.(?!well-known\/) index.php [L]

# block all files in the content folder from being accessed directly
RewriteRule ^content/(.*) index.php [L]

# block all files in the site folder from being accessed directly
RewriteRule ^site/(.*) index.php [L]

# block direct access to Kirby and the Panel sources
RewriteRule ^kirby/(.*) index.php [L]

# make site links work
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php [L]

</IfModule>

# pass the Authorization header to PHP
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

# compress text file responses
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>


text:
Q: Criteria API : finding entities in a tree with inherited user permissions I'm trying to use the criteria API to perform a rather complex search in a hierarchical structure of locations.
I'm only writing here the relevant entities and their relevant attributes
Entities
Location
- Location upperLocation (may be null)
- Set<Location> childrenLocation (may be empty)
- Set<User> managers (may be empty)
Alert
- Location originatedIn (may be null)
User
More details
The relation between User and Location is ManyToMany.
The locations representation is hierarchical. For example World is a location which contains the countries USA, England, France, which themselves contains cities, ...
There can be unlimited levels of sub locations in the trees.
The alerts are originated in a Location or not.
A user is considered manager of a location if he his effectively (in the database) manager of it or if he is manager of one of the location's parents in the tree. Basically if you are manager of USA, you are automatically considered manager of all the children locations in USA, and their children too, etc ...
The criteria I'm trying to build has to find alerts that are originated in a location for which the user is either a direct manager or an inherited manager.
Code
I have a DAO :
AlertRepository extends JpaRepository<Alert, Long>, JpaSpecificationExecutor<Alert>
on which I request the query, just passing the specifications.
List<Alert> alerts = dao.findAll(buildSpecificationForUser(user))
And the specification builder :
private Specification<Alert> buildSpecificationForUser(final User user) {
        return new Specification<Alert>() {
            @Override
            public Predicate toPredicate(Root<Alert> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

                query.distinct(true);

                Expression<Collection<User>> managersOfLocations = root.get("originatedIn").get("managers");
                return builder.isMember(user, managersOfLocations);
            }

        };

    }

With this function I only get the alerts of the locations for which the user is directly a manager of.
Question
How to make it so that it would find also the alerts in the locations for which the user is an inherited manager ?
Update
I've tried also this :
Join<Alert, User> managersOfLocation = root.join("originatedIn").join("upperLocation",JoinType.LEFT).join("managers",JoinType.LEFT);
return builder.equal(managersOfLocation.get("id"),user.getId());

But the result set return all the alerts event if the user is not manager in any of the locations

A: Since the representation of Location is hierarchical, you will need a hierarchical query to fetch the data that you need.  However, there is no direct hierarchical query support in JPA 2.1.  If you expect to have a lot of Locations, you'll have to update your data model to use materialized paths or nested sets.
If you're not going to have a huge number of Locations, or modifying your table structure is not an option right now, you could create a view that does the hierarchical SQL for you, and map to that.  For example:
If you create the following view manager_location_all (tested on PostgreSQL 9.4.4):
CREATE OR REPLACE VIEW manager_location_all AS
 WITH RECURSIVE ancestor_descendant(ancestor_id, descendant_id) AS (
         SELECT root.upper_location_id, root.location_id
           FROM location root
         UNION ALL
         SELECT l.upper_location_id, ad.descendant_id
           FROM location l
           JOIN ancestor_descendant ad ON l.location_id = ad.ancestor_id
        )
 SELECT manager_location.manager_id, ancestor_descendant.descendant_id AS location_id
   FROM ancestor_descendant
   JOIN manager_location ON ancestor_descendant.ancestor_id = manager_location.location_id
  UNION ALL
 SELECT manager_location.manager_id, manager_location.location_id
   FROM manager_location;

You could then add a Set<User> allManagers mapping to your Location object using that view then do root.get("originatedIn").get("allManagers") in your specification builder.  This approach is not going to be as scalable as updating your data model, however.


text:
Q: Android Textview ellipsize with multiple rows I am trying to get an ellips at the end of a textview that has multiple lines of text. The "..." is showing but its at the last space in the text and is other followed by other characters. How do I make sure the "..." is always at the end.
See example image
The XML Layout file is :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="5dp"
android:orientation="horizontal" >

<TextView
    android:id="@+id/nfDateMonth"
    android:layout_width="64dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/topsegment"
    android:gravity="center"
    android:text="APR"
    android:textAllCaps="true"
    android:textColor="#f2e606"
    android:textSize="22sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/nfDateDate"
    android:layout_width="64dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/nfDateMonth"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="8dp"
    android:background="@drawable/bottomsegment"
    android:gravity="center"
    android:text="28"
    android:textSize="22sp" />

<TextView
    android:id="@+id/nfTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dp"
    android:layout_marginTop="0dp"
    android:layout_toRightOf="@+id/nfDateMonth"
    android:text="Half Marathon"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textSize="16sp" />

<TextView
    android:id="@+id/nfContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/nfTitle"
    android:layout_gravity="left"
    android:layout_marginBottom="2dp"
    android:layout_marginRight="16dp"
    android:layout_marginTop="2dp"
    android:layout_toRightOf="@+id/nfDateDate"
    android:ellipsize="end"
    android:maxLines="2"
    android:text="Content\nline two line three sadsa dsd dsa dsd big big big sd sad sad sadsadsad asd sad as d asd as das das das das da sd asd asd one two three four five sixx seven"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textSize="12sp" />

</RelativeLayout>

A: I had same issue today. It's probably bug in TextView or TextUtils (method ellipsize).
In my case it's caused by text with new lines.
There are two solutions:

*

*Get first line only:

String longText = "...";
String body = new Scanner(longText).nextLine();
textView.setText(body);

2. Remove all new lines in text
String longText = "...";
String body = longText.replace("\n", "").replace("\r", "");
textView.setText(body);


text:
Q: C read values from text file I'm writing a c program to simulate FCFS scheduling algorithm. It will accept a command line argument as a file and calculate turnaround time and wait time for every process. However it can not read values from text file into variables successfully.
Here is the code
#include <stdio.h>
#define N 50

int main(int argc, char** argv)
{
    int i = 0;
    char line[20];
    int n=0;
    typedef struct
    {
            char name; //process name
            int at;  //arrive time
            int pt;  //process time
            int ft;  //finish time
            int rt;  //round time
            int wt;  //wait time
    } Process;
    Process pcs[N];

    FILE* file = fopen( argv[1], "r");
    while (fgets(line,sizeof(line),file) != NULL)
    {
            sscanf(line, "%s %d %d", pcs[i].name, pcs[i].at, pcs[i].pt);
            line[strlen(line)-1] = '\0';
            printf("%s %d %d\n",pcs[i].name, pcs[i].at, pcs[i].pt);
            i++;
    }
    fclose(file);
    pcs[0].ft=pcs[0].at+pcs[0].pt;
    pcs[0].rt=pcs[0].ft-pcs[0].at;
    pcs[0].wt=0;
    for (n;n<4;n++)
    {
            if (pcs[n].at<pcs[n-1].ft)
            {
                    pcs[n].ft=pcs[n-1].ft+pcs[n].pt;
                    pcs[n].rt=pcs[n].ft-pcs[n].at;
                    pcs[n].wt=pcs[n-1].ft-pcs[n].at;
            }
            else
            {
                    pcs[n].ft=pcs[n].at+pcs[n].pt;
                    pcs[n].rt=pcs[n].ft-pcs[n].at;
                    pcs[n].wt=pcs[n-1].ft-pcs[n].at;
            }
    }
            int x = 0;
    for (x;x<n;x++)
    {
            printf("process name: %s", pcs[x].name);
            printf("Turnaround Time: %d", pcs[x].rt);
            printf("Wait Time: %d\n", pcs[x].wt);
    }
    return(0);
}

Here is the input file

And the output is

Thanks for any help and advice.

A: As pointed by alk, you're doing some mistakes:

*

*In your struct declaration you have declared name as a single character, but in your file reading code(while loop containing fgets) you're passing %s which is for strings, so better change your declaration to a char name[SIZE] rather than char name. Bdw you should read the compiler warning and try to understand it, since that's what is creating problem.

*You are supposed to pass address of variables in sscanf and it's variants, so change line 26 to:
sscanf(line, "%s %d %d", pcs[i].name, &pcs[i].at, &pcs[i].pt);


text:
Q: How to access content of a fitnesse page? So some are confused about what exactly is the requirement. Here is a full description.
I have 2 machines.
Machine 1 - Server : A Virtual machine where Fitnesse is deployed.
Machine 2 - A local machine where I have to access all the information in a java project.
Now, I have 1 Test Page with the content in form of:
|Import|
|Fixtures|
|AdditionTestPageFixture|
|a|b|doAddition?|
|1|2|   4  |
in the server machine. I access this page from my machine using the URL : http://x.x.x.x:xxxx/FrontPage.ArithmeticSuite1.AdditionTestPage
Coming back to my local machine.
I have a JAVA project created where I need to know which class is being used in this Fixture so basically I want to read this content and extract word "AdditionTestPageFixture".
I can't go to server through putty and access files there, that should not be done. Whatever I can do, I should do through Fitnesse only. So,
1. I cant go to directory where the pages are stored on that server machine and extract content.
2. I can't use URLConnetion to send HTTP requests because the response is a HTML response and parsing that whole content will be tedious.

A: In the FitNesseRoot subfolder of your FitNesse installation, you will find a set of folders containing content.txt files.  These are the FitNesse pages and you can read these and process them as required.
On a remote FitNesse installation, you can issue an HTTP request that will return the page in raw wiki format, e.g.
http://remotehost:8090/MyPage?pageData

You can see the full set of options for accessing FitNesse at:
http://fitnesse.org/FitNesse.UserGuide.AdministeringFitNesse.RestfulServices

A: You can use a HttpURLConnection; Example:
public String getPage(URL url) {
    try {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


text:
Q: Is there a way to display recent work item activity? Jira has a feature called Activity Streams, which allows for a gadget to be displayed on dashboards to show what recent changes have been made to issues within a particular stream. This could show link changes, attachments added, fields updated, etc. Is there any way to do something like this with a TFS dashboard widget?
I've done some searching, but haven't come across anything similar.

A: You can install the Activity Feed extension.
With the activity feed, you can see what's happening in your team project within a glance. You can use it on your dashboard by putting a widget on it, or simply open the hub. The Activity Feed gives a summary of all recent changes of work items, commits, pull requests and builds. It tells who changed a task, who logged a bug and who made committed code.


text:
Q: Can copulas be used to measure dependence of $X$ and $Y$ when we are given a random sample $\mathbf{x}$ and $\mathbf{y}$? Trying to understand what copulas are, I am reading from Wiki that:
"In probability theory and statistics, a copula is a multivariate cumulative distribution function for which the marginal probability distribution of each variable is uniform on the interval $[0, 1]$. Copulas are used to describe the dependence between random variables."

For linear dependencies, the most famous measure is that of correlation:
If $X$ and $Y$ are random variables, then
\begin{equation}
\tag{1}
\rho(X,Y)=\frac{\text{Cov}(X,Y)}{\sqrt{\text{Cov}(X,X)}\sqrt{\text{Cov}(X,Y)}}
\end{equation}
When we have a random sample $\mathbf{x}=(x_1,...,x_n)$ from $X$ and $\mathbf{y}=(y_1,...,y_n)$ from $Y$, then we can estimate the correlation of $X$ and $Y$ by
\begin{equation}
\tag{2}
\hat{\rho}(X,Y)=
\frac
{\sum\limits_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y}) }
{
 \sqrt{
  \sum\limits_{i=1}^{n}(x_i-\bar{x} )^2
 }
 \sqrt{
  \sum\limits_{i=1}^{n}(y_i-\bar{y} )^2
 }
}
\end{equation}

Before diving to the mathematical details and definitions of copulas, I am wondering if copulas can be used as a measure of dependence when we are given a random sample  $\mathbf{x}=(x_1,...,x_n)$ from $X$ and $\mathbf{y}=(y_1,...,y_n)$ from $Y$ like Pearson correlation.
Pearson correlation can be used to measure liner dependencies both theoretically (1) and empirically (2). Do copulas have the same nice property? If so, which is the estimator?


text:
Q: Unable to add checkbox to ToolStrip I want to add some checkboxes along with standard toolstrip controls in my C# winform. There is no issue with standard controls provided by toolstrip but problem with my checkbox. In toolstrip, the first control is combobox(toolstrip combobox), second one is label(toolstrip label). There is no problem till now. I have to add two checkboxes and then tollstrip combobox.  I am adding first checkbox as below
    System.Windows.Forms.CheckBox c1 = new System.Windows.Forms.CheckBox();
    c1.CheckState = System.Windows.Forms.CheckState.Unchecked;
    System.Windows.Forms.ToolStripControlHost host = new
    System.Windows.Forms.ToolStripControlHost(c1);
    toolStrip1.Items.Add(host);

If I am running application then I am able to see this check box with toolstrip. Once I saved my form, everything lost. I could not find even c1 in my cs file. There are some additional entries with host in designer.cs file.
What I am missing here? How can I add these 2 checkboxes in toolstrip?

A: First of all
From the point of view of good UI Winforms practices, you should use a ToolStripButton with its Checked, CheckState and CheckOnClick properties instead.
Now about your issues
I suppose that you have write this code in the designer file ? That's really a bad idea, because the IDE is going to overwrite change in this file. The file being hidden (by default) and the warning comment are not here for nothing !
This kind of operation should be done on the code file, within the form  constructor (The New() Sub) just after the call to InitializeComponent().
Remarks You won't see the result in the designer but it will display on runtime. If you want designer support, it's another story and not a simple one !


text:
Q: Form element not setting the width correctly based on its contents I wanted to create a page similar to this, however the form width is not matching getting set to the required amount, but instead is spanning across the whole page:

I tried to do the following and cant get ahead.
https://jsfiddle.net/mrf3wL1q/
HTML:
<!DOCTYPE html>

    <title>Sign Up</title>
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="style.css">

        <form>

                <input type = "text" placeholder = "Your Name" id = "name"/>

                <input type = "email" placeholder = "Enter Your Email" id = "email"/>

                    <input type = "password" placeholder = "Password" id = "password"/>
                    <input type = "password" placeholder = "Confirm Password" id = "password"/>

<input id = "submit" type="submit" name= "formSubmit" value="CREATE A FREE ACCOUNT" class="btn"/>

        </form>

CSS:
body{
    background-image: url(images/bg.png);
    background-size: cover;
    background-repeat: no-repeat;
    font-family: 'Roboto', sans-serif;
}
.container{
    width: auto;
    background-color: #FFFFFF;
    height: 300px;
    padding: 30px;
    border-radius: 30px;
}
.forms{
    background-color: #FCFCFC;
}
input{
    font-family: 'Roboto', sans-serif;
    border-radius: 2px;
}
input#name{
    background-image: url(images/name.jpg);
    background-size: 10%;
    background-repeat: no-repeat;
    background-position: center left;
    border:none;
    padding-left: 50px;
    margin-top: 10px;
    width: 400px;
    height: 40px;
}
input#email{
    margin-top: 10px;
    background-image: url(images/mail.jpg);
    background-size: 7%;
    background-repeat: no-repeat;
    background-position: center left 6px;
    border:none;
    padding-left: 50px;
    width: 400px;
    height: 40px;
    font-size: :16px;
}
input#password{
    margin-top: 20px;
    background-image: url(images/pass.png);
    background-size: 7%;
    background-repeat: no-repeat;
    background-position: center left 6px;
    border:none;
    padding-left: 50px;
    width: 170px;
    height: 40px;
    margin-right: 4px;
}

input#submit{
    margin-top: 10px;
    background-color: #A5ABB0;
    border: none;
    height: 50px;
    width: 447px;
     cursor: pointer;
    font-weight: 400;
    font-size: 17px;
    color: white;

}

.group{
    margin: 18px auto;
    border-bottom: 2px solid #BEBEBE;
    overflow: hidden;
}

I have done the following changes here: https://jsfiddle.net/mrf3wL1q/
I've set the form container width to auto, however the form is not adjusting to its contents
Any help would be appreciated. Thanks :D

A: if your trying to apply css on input area, then write selector as...
input[type="text"]

or
input [type="password"]

or
input [type="submit"]

-- if you facing another problem on css, please describe properly.... thx.

A: You have almost got it. You just need to give width and margin for the <form>:
<!DOCTYPE html>

    <title>Sign Up</title>
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="style.css">

      <form>

          <input type = "text" placeholder = "Your Name" id = "name"/>

          <input type = "email" placeholder = "Enter Your Email" id = "email"/>

          <input type = "password" placeholder = "Password" id = "password"/>
          <input type = "password" placeholder = "Confirm Password" id = "password"/>

<input id = "submit" type="submit" name= "formSubmit" value="CREATE A FREE ACCOUNT" class="btn"/>

      </form>

And CSS
body{
  background-image: url(images/bg.png);
  background-size: cover;
  background-repeat: no-repeat;
  font-family: 'Roboto', sans-serif;
  background-color: #00f;
}
.container{
  width: 50%;
  margin: 125px auto 0;
  background-color: #FFFFFF;
  height: 300px;
  padding: 30px;
  border-radius: 30px;
}
.forms{
  background-color: #FCFCFC;
}
input{
  font-family: 'Roboto', sans-serif;
  border-radius: 2px;
}
input#name{
  background-image: url(images/name.jpg);
  background-size: 10%;
  background-repeat: no-repeat;
  background-position: center left;
  border:none;
  padding-left: 50px;
  margin-top: 10px;
  width: 400px;
  height: 40px;
}
input#email{
  margin-top: 10px;
  background-image: url(images/mail.jpg);
  background-size: 7%;
  background-repeat: no-repeat;
  background-position: center left 6px;
  border:none;
  padding-left: 50px;
  width: 400px;
  height: 40px;
  font-size: :16px;
}
input#password{
  margin-top: 20px;
  background-image: url(images/pass.png);
  background-size: 7%;
  background-repeat: no-repeat;
  background-position: center left 6px;
  border:none;
  padding-left: 50px;
  width: 170px;
  height: 40px;
  margin-right: 4px;
}

input#submit{
  margin-top: 10px;
  background-color: #A5ABB0;
  border: none;
  height: 50px;
  width: 447px;
  cursor: pointer;
  font-weight: 400;
  font-size: 17px;
  color: white;

}

.group{
  margin: 18px auto;
  border-bottom: 2px solid #BEBEBE;
  overflow: hidden;
}

Output: http://jsbin.com/zorelitema


text:
Q: Are sql dumps moved into docker container `docker-entrypoint-initdb.d` encrypted? I'm dumping a database into a sql dump:
docker exec mysql sh -c 'exec mysqldump --all-databases -uroot -ppassword' > all-databases.sql

Then I'm using a Dockerfile to build a mysql image and run as a container:
FROM mysql:5.6.41

# needed for intialization
ENV MYSQL_ROOT_PASSWORD=whateverPassword

ADD all-databases.sql /docker-entrypoint-initdb.d/

EXPOSE 3306

When I run the container if I exec into the container, can I access the all-databases.sql file and see the contents of my database in plaintext in the docker image?
Currently if I look into /docker-entrypoint-initdb.d/ it says all-databases.sql but I don't know where that file is stored/if it's encrypted.

A: If you docker exec into the container, the file will be unencrypted.  (It's just a text file and you can look at it with more on most image bases.)
However, if you can run any Docker command at all, then generally it's trivial to get unrestricted root access on the system.  (Consider using docker run -v /etc:/host-etc to add yourself to /etc/sudoers or to allow root logins with no password.)
Also remember that anyone who has the image can docker run it and see the file there, if that matters to your security concerns.  If you're looking for a single file with root access on the system anyways, you can find it without too much effort in /var/lib/docker.  They can also easily run docker history to see the database root password you've set.


text:
Q: Why are Nix programs not able to resolve mDNS names when native programs are? My native programs (on Fedora) are able to resolve mDNS / Avahi / zeroconf names, like so:
$ ping felonyspork.local -c 1
PING felonyspork.local (192.168.88.169) 56(84) bytes of data.
64 bytes from 192.168.88.169 (192.168.88.169): icmp_seq=1 ttl=64 time=1.73 ms

--- felonyspork.local ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 1.734/1.734/1.734/0.000 ms

$ ssh felonyspork.local
Last login: Mon Apr 25 16:05:34 2022 from 192.168.88.200

$ exit
Connection to felonyspork.local closed.

However, my Nix-installed programs are not:
$ nix-shell -p openssh ssh-tools

[nix-shell:~/src/nixconfig]$ ssh-ping -c 1 felonyspork.local
SSHPING felonyspork.local

--- felonyspork.local ping statistics ---
1 requests transmitted, 0 requests received, 100% request loss

[nix-shell:~/src/nixconfig]$ ssh felonyspork.local
ssh: Could not resolve hostname felonyspork.local: Name or service not known

I have mDNS configured in /etc/nsswitch.conf:
hosts:      files myhostname mdns4_minimal [NOTFOUND=return] resolve [!UNAVAIL=return] dns

And avahi-daemon is running on my system.
How can I get Nix programs to correctly resolve mDNS names? This is especially important, because deploying with Morph requires a working Nix SSH session.

A: The missing link here is nscd; simply installing nscd and starting the daemon makes the Nix-installed programs work.
$ sudo dnf install nscd
$ sudo systemctl start nscd.service
$ nix-shell -p ssh-tools

[nix-shell:~]$ ssh-ping felonyspork.local
SSHPING felonyspork.local
Pong from felonyspork.local: ssh_seq=1 time=2191 ms
Pong from felonyspork.local: ssh_seq=2 time=1310 ms
^C
--- felonyspork.local ping statistics ---
2 requests transmitted, 2 requests received, 0% request loss


text:
Q: Formatting DateTime in .NET Core React app I am new to .NET Core and am exploring creating applications with a React frontend and .NET back end. I am starting very simple and at the moment am just trying to format the DateTime. The relevant files are:
DateController.cs:
 public class DateController : Controller
    {
        [HttpGet, Route("GetDate")]
        public async Task<string> GetDate()
        {
            DateTime dt = DateTime.Now;
            string format = "MMM ddd d HH:mm yyyy";
            string info = $"Today is {dt.ToString(format)}";
            return info;
        }
    }

Date.js:

import React, { Component } from "react";

export class Date extends Component {
  constructor(props) {
    super(props);
    this.state = { date: "" };

    fetch("api/Date/GetDate")
      .then(response => response.text())
      .then(data => {
        this.setState({ date: data });
      });
  }

  render() {
    return <h1>{this.state.date} </h1>;
  }
}

However, the date doesn't seem to be formatted as I am expecting, as it displays in the browser like this (and even misses the "Today is..." part:
"Sun Aug 18 2019 21:30:24 GMT+0100 (British Summer Time)".
Can anyone please guide me as to where I have gone wrong?
Thank you!

A: here all patterns of the dateTime class, but I don't see your pattern among them

A: I still prefer to see the date in numbers is much easy to render in Client JS/React/Angular
        var currentTime = new DateTime(2019, 8, 19, 1, 0, 0, 100, DateTimeKind.Utc);
        var value = currentTime.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
        Console.WriteLine($"Unix Time With Milliseconds: {value.TotalMilliseconds}");


text:
Q: Multiple TortoiseHG Clients? I was able to run more than one TortoiseHG clients at the same time. This is quite handy specially when working on multple projects at the same time.
Since I've upgraded to windows8.1 (from7) this doesn't seem to be doable anymore. I don't really remember if I did a special setting to enable anything like this. Therefore, wanted to ask - how can I run multiple tortoisegh's at the same time?

A: You can configure TortoiseHg so that it opens a new Workbench instance for each repository instead of multiple tabs in one Workbench instance.
It's in the "Settings" dialog, under Workbench -> Single Workbench Window
Note that it was added in one of the newer TortoiseHg versions (don't know which one exactly) and that it's not visible on the screenshot of the "Settings" dialog in the docs I linked above (I guess the screenshot is too old).

EDIT:
Here's a screenshot from my machine:


text:
Q: AMPscript if statement not working correctly I am new to AMPscripts and need some help with the below. What I am trying to do is set up conditions that will populate BodyContent (using content block id) in an email with contact data (not journey data, that's why I used the Lookup) if the contact data attribute value returns true. If the value returns false or null I want to show something else. However, the part that checks for "false" doesn't work (last part) but I can't understand where my syntax is wrong. Also, it would be great to know if there is a shorter or better way to write this script?
SET @id = AttributeValue('SubscriberKey')
SET @Product1 = Lookup('Test_Journey','Product1','SubscriberKey',@id))
SET @Product2 = Lookup('Test_Journey','Product2','SubscriberKey',@id))

IF @Product1 == 'True' THEN
  SET @BodyContent = ContentBlockbyId("12345")

  IF @Product2 == 'True' THEN
    SET @BodyContent1 = ContentBlockbyId("54321")

    IF @Product1 == 'False' AND @Product2 == 'False' THEN
      SET @BodyContent = ContentBlockbyId("11111")

    ENDIF
  ENDIF
ENDIF

A: Code within an IF statement will execute if the statement resolves to true. By nesting your IF statements, they will only be evaluated if the first IF statement resolves true.
In your example you are checking to see if your variables are false after you've already established they are true, so your 3rd IF statement will never resolve to true. Don't nest if you don't need to.
%%[
IF @Product1 == 'True' THEN
    SET @BodyContent = ContentBlockbyId("12345")
ENDIF

IF @Product2 == 'True' THEN
    SET @BodyContent1 = ContentBlockbyId("54321")
ENDIF

IF @Product1 == 'False' AND @Product2 == 'False' THEN
    SET @BodyContent = ContentBlockbyId("11111")
ENDIF
]%%

A: Here's a leaner way to do it:
SET @id = AttributeValue('SubscriberKey')
SET @Product1 = Lookup('Test_Journey','Product1','SubscriberKey',@id)
SET @Product2 = Lookup('Test_Journey','Product2','SubscriberKey',@id)

IF @Product1 == 'True' THEN
SET @BodyContent = ContentBlockbyId("12345")
ELSEIF @Product2 == 'True' THEN
SET @BodyContent = ContentBlockbyId("54321")
ELSE
SET @BodyContent = ContentBlockbyId("11111")
ENDIF

A: To be honest both of the answers need to be commented or clearly described.
You can use this codeblock which is (nearly) the code of Josh de Blank IF you want to display the content Block when one value evaluates to true.
This can also mean that you display two content blocks(if both are true) or none (if none of the arguments result in true). If this is what you are searching for you gotta take Josh's.
This code has no default, which is sometimes risky (can produce no output or multiple). I would always encourage people to have all possible scenarios in their logic.
%%[
IF @Product1 == 'True' THEN
    SET @BodyContent = ContentBlockbyId("12345")
ENDIF

IF @Product2 == 'True' THEN
    SET @BodyContent1 = ContentBlockbyId("54321")
ENDIF

IF (EMPTY(@Product1) AND EMPTY(@Product2)) OR (@Product1 == 'False' AND @Product2 == 'False') THEN
    SET @BodyContent = ContentBlockbyId("11111")
ENDIF
]%%

You can use this codeblock if you only want to display definitely ONE ContentBlock, even if both Products have "true" in them.
This is something you have to keep in mind when you watch this code. When Product1 and Product2 have "true" values, the contentblock 54321 will never be displayed.
Why? Because the first IF clause evaluates to true and therefore the ELSEIF clause will never be run. Which maybe is not what you want.
%%[
SET @id = AttributeValue('SubscriberKey')
SET @Product1 = Lookup('Test_Journey','Product1','SubscriberKey',@id)
SET @Product2 = Lookup('Test_Journey','Product2','SubscriberKey',@id)

IF @Product1 == 'True' THEN
    SET @BodyContent = ContentBlockbyId("12345")
ELSEIF @Product2 == 'True' THEN
    SET @BodyContent1 = ContentBlockbyId("54321")
ELSE
    SET @BodyContent = ContentBlockbyId("11111")
ENDIF
]%%

This would be my approach:
I would encourage you to use something like this, which is only an addition to the one of CodeRage but maybe a really necessary one.
The first condition really needs to be thought of ==> what happens if both Product1 and Product2 have the value true?
In this example it takes ONE other unique block and inserts it.
And i would only use one variable which is BodyContent and not two BodyContent1 and BodyContent. If you want to display both i would have created either the 98765 content block which inherits both or make 2 variables which are better seperated like @BodyContent_top and @BodyContent_bot.
%%[
SET @id = AttributeValue('SubscriberKey')
SET @Product1 = Lookup('Test_Journey','Product1','SubscriberKey',@id)
SET @Product2 = Lookup('Test_Journey','Product2','SubscriberKey',@id)

IF @Product1 == 'True' AND @Product2 == 'True' THEN
    SET @BodyContent = ContentBlockbyId("98765")
ELSEIF @Product1 == 'True' THEN
    SET @BodyContent = ContentBlockbyId("12345")
ELSEIF @Product2 == 'True' THEN
    SET @BodyContent = ContentBlockbyId("54321")
ELSE
    SET @BodyContent = ContentBlockbyId("11111")
ENDIF
]%%

A: Thank you all!
this code solved what I am trying to achieve:
%%[
IF @Product1 == 'True' THEN
    SET @BodyContent = ContentBlockbyId("12345")
ENDIF

IF @Product2 == 'True' THEN
    SET @BodyContent1 = ContentBlockbyId("54321")
ENDIF

IF (EMPTY(@Product1) AND EMPTY(@Product2)) OR (@Product1 == 'False' AND @Product2 == 'False') THEN
    SET @BodyContent = ContentBlockbyId("11111")
ENDIF
]%%


text:
Q: Matlab error when executed clear command using mexCallMATLAB in mex file The code which executed prompts to  error is:
 void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
 {
    double p;
    p  =   (double)mxGetScalar(prhs[0]);
    mexCallMATLAB(0,NULL,1, prhs, "clear");

 }

Where I am trying to clear a variable which is in workspace pointed by prhs[0].
Please suggest what am I doing wrong.
Error message when executed this function with one argument. gives following error message:

callmatlabtest(10)
    ??? Error using ==> clear
    Argument must contain a string.

A: I believe you need to have &prhs[0] in your call:
mexCallMATLAB(0, NULL, 1, &prhs[0], "clear");

I've tested this code and it works (in a file named mextest.c):
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  mexCallMATLAB(0,NULL,1, &prhs[0], "clear");
}

and here is the result:
>> a = 10;
>> who
Your variables are:
a
>> mextest('a')
>> who
>>

A: Callmatlabtest(10) is the same as clear(10), since callmatlabtest just forwards its own inputs to clear (via mexCallMATLAB). The clear function expects a string input, and 10 is a double, hence the error message "argument must contain a string".


text:
Q: Amazon zombie story with a main character who loves Mountain Dew and Doritos A couple of years ago in junior high I read a book that I got off of the Amazon book store. It was at the time available exclusively at Amazon. The starting scene talked about the main character (I think his name was Nate) was injured and running from a zombie. He holed up in a store and the zombie started trying to beat its way in.
Nate rummaged around and found a bottle of Mountain Dew and figured the world was ending, the glass was cracking and he was about to be eaten alive by his (former) girlfriend and he would go out with Mountain Dew and Doritos. The glass broke as he opened the bottle of soda and the zombie charged him. Somehow its mouth ended up around the bottle and it drank the soda. The soda made the zombie passive and save Nate. He recorded this with his phone and saved the world.
Some years later he was a billionaire for saving humanity and somehow got involved in a conspiracy to bring about the zombie apocalypse (2.0, this time without the sugar dependency). He spent the story trying to stop this from happening. I think the story was set in 2006 - 2011. One last thing; there was a lot of chaos caused by the issue of what to do with the now harmless zombies. Some wanted to put them in medical facilities and others wanted to just kill them. Some of Nate's friends work as doctors in a similar facility. The bad guys unleashed their new zombies on that facility and only the blonde girl survived.

A: This is Zombie Day Care by Craig Halloran.
From one of the GoodReads reviews:

The book begins with the zombies taking over and one man, Nate, accidently discovering that "Fountain Dew" calms them. Thus, Fountain Dew becomes the zombie tamer and Nate becomes a hero. The book then jumps forward about 10 years when the zombies have all been either captured or killed. There are now "zombie day cares" which house zombie children and scientists experiment on them to find a cure. But not everyone is happy that the remainig zombies were saved. Many people still wish them dead.

And another one:

It starts out during the midst of the zombie take-over with one of the main characters running away from his zombie girlfriend. He can't stand to kill her so by accident he ends up giving her "Fountain Dew" and finds that she stops trying to kill him. With his last battery he tweets the discovery and saves the world. Fast forward a few years and they are trying to find a cure for zombies and controlling them with soft drinks.

I found this almost immediately by searching the web for "zombie story Nate mountain dew soda".


text:
Q: WCF Delphi7 method input parameters I've got wcf web-service(basicHttpBinding). Our Delphi7 clients couldn't correct consume it.
I've already flatten the WSDL with WCF extras. Ok. Delphi7 wsdl importer generate proxy correct.
Now I've got the problems with input parameters. they always have default values (empty for strings, 0 for int).
Output values from methods delphi7 gets ok.
for example:
        public string Test(string a)
        {
              return "Test"+a;
        }

This method always return "Test". My logging system fix that I've got empty a at method, so the problem is correct transfer input parameters.
I can't undersand what's wrong
EDIT
proxy:
ISyncer = interface(IInvokable)
  ['{D46862B0-BDD3-8B80-35A8-A2AC69F24713}']
    function  Test(const a: String): String; stdcall;
  end;

call:
Sync:=(dmMain.HTTPRIO1 as ISyncer);
test:=Sync.Test('5555');

dmMain.HTTPRIO1 has soLiteralParams  at options:
init:
InvRegistry.RegisterInvokeOptions(TypeInfo(ISyncer), ioLiteral);

After call I get exception with message:
Error deserializtion message body for operation Test.
Operation formatter detects ivalid message body. Expecting node type "Element"
with name "Test" and namespace "http://tempuri.org". Actually node type "Element"
with name "xsd:String" and namespace "http://w3.org/2001/XMLSchema"

wsdl fragment:
<xsd:element name="Test">
−
<xsd:complexType>
−
<xsd:sequence>
<xsd:element minOccurs="0" name="a" nillable="true" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
−
<xsd:element name="TestResponse">
−
<xsd:complexType>
−
<xsd:sequence>
<xsd:element minOccurs="0" name="TestResult" nillable="true" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

EDIT2
I research http requests:
.NET
<Test> xmlns="http://tempuri.org/">5555</Test>

works correct;
Delph7
<Test xmlns="http://tempuri.org/"><xsd:a>5555</xsd:a></Test>

null input parameter.
The problem is in prefix xsd

A: Delphi uses RPC/Encoded SOAP whereas WCF uses Document/Literal/Wrapped SOAP. So you need to tell Delphi to use the same format. You could do this by specifying soLiteralParams in the THttpRio.Converter.Options.

A: I've done it.
I fixed soap envelope at every service sonsume through event handler OnBeforeExecute of THttpRio.
I fix(remove namespace prefixes) and it works.
Thanks


text:
Q: Referencing variable in declarative jenkins pipeline I am using the groovy below to call a bat command, that no matter how i reference the LOCAL_WORKSPACE within the bat command it does not evaluate it.
What am i missing?
Error

nuget restore $env.LOCAL_WORKSPACE
  "Input file does not exist: $env.LOCAL_WORKSPACE"

Script
pipeline {
agent any
stages {
    stage('Clone repo') {
        steps {
            deleteDir()
            git branch: 'myBranch', changelog: false, credentialsId: 'myCreds', poll: false, url: 'http://myRepoURL'
        }
    }
    stage ("Set any variables") {
        steps{
            script{
                LOCAL_BUILD_PATH = "$env.WORKSPACE"
            }
        }
    }
    stage('Build It, yes we can') {
        parallel {
            stage("Build one") {
                steps {
                    echo LOCAL_BUILD_PATH
                    bat 'nuget restore %LOCAL_WORKSPACE%'
                }
            }
        }
    }
}

}

A: You cannot set variables to share data between stages. Basically each script has its own namespace.
What you can do is use an environment directive as described in the pipeline syntax docs. Those constants are globally available, but they are constants, so you cannot change them in any stage.
You can calculate the values though. For example I use an sh step to get the current number of commits on master like this:
pipeline {

    agent any

    environment {
        COMMITS_ON_MASTER = sh(script: "git rev-list HEAD --count", returnStdout: true).trim()
    }

    stages {

        stage("Print commits") {
            steps {
                echo "There are ${env.COMMITS_ON_MASTER} commits on master"
            }
        }
    }
}

A: You can use environment variables to store and access to/from stages. For example, if you define LOCAL_ENVR as Jenkins parameter, you can manipulate the variable from stages:
stage('Stage1') {
       steps {
           script{
                env.LOCAL_ENVR = '2'
           }
       }
    }
    stage('Stage2') {
         steps {
             echo "${env.LOCAL_ENVR}"
         }
    }


text:
Q: How to auto paginate depend on container height in angularjs I have a working app on JSFiddle.
$scope.pageSize = 5;

What I want is that when I change the div's height, how to do the pagination base on new height (calculate the new $scope.pageSize value).
For example: with height = 140px, pageSize = 5;
with height = 200px, pageSize should be another number. (how to calculate this number?)

A: JSFiddle link
Change variable pageSize to a function
var myApp = angular.module("myApp", []);
myApp.controller("dataCtrl", function($scope) {
  $scope.data = [];
  for (var i = 1; i <= 20; i++) {
    $scope.data.push("Item " + i);
  }
  $scope.currentPage = 0;
  $scope.pageSize = function(){
    /*edit here*/
    var pagesize = $scope.divHeight / 28;
    if(pagesize < 5) pagesize = 5;
    return pagesize;
  }
  $scope.divHeight = 140;
  $scope.numberOfPages = function() {
    return Math.ceil($scope.data.length / $scope.pageSize());
  }
});

It should now change due to divHeight changes.


text:
Q: Excel Table Column Reference by Referencing Second Table That's a terrible title, I know.

I have two tables.  The first is UseCases, which has columns for all the roles identified that apply, then a 1 or 0 in the Role column to indicate whether that role uses that use case, so:
ID | Description   | Worker | Manager | Executive
1  | Do stuff      |   1    |    1    |     1
2  | Manage People |   0    |    1    |     1
3  | Collect Bonus |   0    |    0    |     1

The second, Roles, lists the roles:
Role        | Use Case Count
Worker      |
Manager     |
Executive   |

In the Use Case Count column of the Roles table, I'm trying to count the number of use cases for that particular role, so Worker gets 1, Manager 2, and Executive 3.  If I'm explicit with the reference, I can use =SUM(UseCases[Worker]) in the cell and get the result I'm after.  But I can't use something like =SUM(UseCases[@[Role]]), which throws an error.  Similarly =SUM(UseCases[A2]) doesn't work.
How do I solve this problem in a manner that's dynamic enough that adding role names or updating them doesn't break things?  I'm open to alternate solutions.

A: This can be done with a Sumproduct formula. The formula in column I is
=SUMPRODUCT(UseCases[[Worker]:[Executive]]*(UseCases[[#Headers],[Worker]:[Executive]]=[@Role]))

When you add new roles to the UseCases table, just make sure to insert them BETWEEN Worker and Executive, not before or after. That way, the reference with the : operator will cover all columns starting from Worker to Executive.

Edit:
You can also define named ranges with the Name Manager and use the range names in the formula. When you add more role names, you just need to make sure that the range name refers to the correct range.
=SUMPRODUCT(RoleData*(RoleHeadings=[@Role]))


text:
Q: Catching errors from SQLite in Common Lisp I'm using the SQLite wrapper from Quicklisp, which is described here. I notice that, for example, execute-non-query, returns nothing, but will throw sqlite-errors. However, I'm not sure how to handle them - as far as I can tell, catch needs an explicit tag, and I'm not sure how the wrapper tags them.
Basically, I would like to do something like this:
(if (no-error (execute-non-query *db* query-string))
    (do-happy-thing)
    (report-error))

How would I go about doing this?

A: handler-case is  your friend.
(handler-case
    (progn
      (execute-non-query *db* query-string)
      (do-happy-thing))
  (sqlite-error (err) (report-error err))) ; err contains additional information


text:
Q: Como verificar se uma string é None? Tenho o seguinte código:
st = ""
if None == st:
   print True
else:
   print False

Existe forma de a string st ser igual a None de forma a escrever no ecrã o valor True?

A: Tecnicamente, não tem como "uma string ser None", pois são coisas diferentes. String (mais precisamente str) é uma classe, enquanto None é uma constante built-in que representa a ausência de valor (e cujo tipo é NoneType). São tipos diferentes, que você pode verificar assim:
print(type('')) # <class 'str'>
print(type(None)) # <class 'NoneType'>

O que provavelmente está te confundindo é o fato de que em Python uma variável pode assumir valores de tipos diferentes. Por exemplo, uma variável pode ser uma string e logo em seguida ela pode mudar seu valor para um número:
s = 'abc'
s = 1

Mas isso não quer dizer que a string 'abc' se transformou no número 1. Na verdade é o valor da variável s que mudou de uma string para um int.
Por isso, não tem como ver "se uma string é None". O que você pode verificar é se o valor da variável é uma string ou None (ou é uma coisa, ou outra). Ex:
s = None
if s is None:
    print(True)
else:
    print(False)

O código acima imprime True, pois o valor de s é None. Se bem que, se o objetivo é imprimir apenas True ou False, bastaria fazer print(s is None).
Agora se você quer testar se uma string é vazia, aí fica assim:
s = ''
if s == '':
    print(True)
else:
    print(False)

Que também imprime True (e que também pode ser simplificado para print(s == '')).

Existe ainda outra possibilidade (mas depende muito do que você quer fazer). Em um contexto booleano, muitos valores são considerados True ou False, de acordo com as regras do Truth Value Testing. Valores como None ou a string vazia, por exemplo, são considerados False, então você pode ao mesmo tempo testar se é uma string vazia ou None assim:
s = ''
if not s:
    print(True)
else:
    print(False)

s = None
if not s:
    print(True)
else:
    print(False)

O código acima imprime True duas vezes, já que tanto a string vazia quanto None são valores considerados "falsos", por isso ele entre no if not s (lembrando que neste caso ele também vai entrar no if se s for qualquer um dos valores "falseáveis" descritos na documentação, como listas vazias, etc).
Por fim, o if acima também pode ser encurtado para print(not bool(s)) em ambos os casos.

Outra opção é verificar o tipo da variável com isinstance. Neste caso, só estou verificando se a variável é uma string (mas não necessariamente a string vazia):
s = 'abc'
# é uma string, ou None
if isinstance(s, str) or s is None:
    print(True)
else:
    print(False)

O código acima imprime True se s for uma string (qualquer uma, não só a string vazia), ou None (e também pode ser encurtado para print(isinstance(s, str) or s is None)).

Enfim, não ficou claro o que você quer, mas como pôde ver, existem várias maneiras de testar o valor de uma variável. Escolha a que fizer mais sentido para o seu caso (mas tendo em mente que não é a string que pode ser None, e sim o valor da variável).


text:
Q: Floating Action Button is not displaying android This is my layout file.
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="@color/primary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="@color/primary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tab_layout"
            android:paddingTop="20dp"
            android:background="@color/windowBackground"
            android:layout_above="@id/bottomButtons"
            >
        </android.support.v4.view.ViewPager>

        <android.support.design.widget.FloatingActionButton
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:src="@drawable/cart"
            android:layout_margin="16dp"
            app:elevation="6dp" />

    </LinearLayout>

    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="com.wokoshop.sony.app.FragmentDrawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>

In this layout Floating action button is not displaying.
Can anyone help me on this?

A: You're using a LinearLayout as the container for your main layout.
Replace it with a RelativeLayout and the FAB will show up.

A: The view pager is being set to wrap_content and in this case the rest of the view is what its saying it needs to contain its content.  If you change the root viewgroup to Relative layout your problems are solved.
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="#456786"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="#456786"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="20dp"
            android:background="#765876"
            android:layout_below="@id/tab_layout"/>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:src="@android:drawable/ic_input_add"
            android:layout_margin="16dp"
            app:elevation="6dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>

A: You should not put a FAB (Floating Action Button) in a LinearLayout. There's  a special layout in the Android Design Support Library called the CoordinatorLayout, which correctly handles Snackbars and FABs.
Here are two nice tutorials which show you how it can be used:
https://lab.getbase.com/introduction-to-coordinator-layout-on-android/
https://guides.codepath.com/android/floating-action-buttons
Your layout is quite complicated, so you should play a bit with it to figure it out where the FAB and the content fragment will be in your structure. Probably your ViewPager and FAB will be inside the CoordinatorLayout.


text:
Q: Increment and decrements on button click using ajax I want when I click on increment button than points will increase. I do this in server side code but it increment after reloading page. I want it to do this without reloading page using ajax and jquery
here is my code
Deals.cs
[WebMethod]
[ScriptMethod]
public static string HOT(int DealPoints,int dealId)
{
    DealPoints++;
    int DealId = dealId;
    int Points = DealPoints;

    string retDeal = "";
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["FYP_Wish"].ToString()))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("IncrementDeals", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@DealPoints", SqlDbType.Int).Value = Points;
        cmd.Parameters.Add("@DealId", SqlDbType.Int).Value = DealId;
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        int result = cmd.ExecuteNonQuery();
        if (result == 1)
        {
            return "true";
        }
        con.Close();
        return retDeal;
    }
}

A: Try this:
$(document).ready(function(e) {
  $("#btn1").click(function(e) { //btn1 is button id
    var o = $(this).val();
    o++;
    $(this).val(o);
  });
});


text:
Q: script to copy a row of data from one sheet to a specific sheet based on the value of a cell I'm trying to create a script to copy a row of data from one sheet to a another sheet based on the value of a cell.
But essentially when a new row of information is input in the main sheet it'll copy the row and place that row of data into a another sheet based off the value of a specific cell. In this case it's the utility company.
If, for example, the customer is created and the utility company they have is United Power I want to have the sheet copy that customers information over and add it to the specified United Power sheet and so on and so forth with the other utility company's (3 total)
I keep getting the below error:
TypeError: Cannot read property 'source' of undefined (line 4, file "Code")
I'll paste below what I have so far. (I only have the code for one so far)
I can also link the spreadsheet if need be.
 function onEdit(event) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();

  if(s.getName() == "Contracts" && r.getColumn() == S && r.getValue() == "United Power") {

    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("United Power");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
  }
}

A: You could have written like this:
You need to change S to a number
function onEdit(e) {
  const sh=e.range.getSheet();
  if(sh.getName()=="Contracts" && e.range.columnStart==19 && e.value=="United Power") {
    const tsh = e.source.getSheetByName("United Power");
    const target = tsh.getRange(tsh.getLastRow() + 1, 1);
    sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).moveTo(target);
  }
}


text:
Q: How to solve " CSRF cookie not set." error when accessing a website using Firefox?
I am getting this error when I am trying to generate an output using a website. How to solve this?

A: The "CSRF cookie not set" error occurs when a website is trying to protect against cross-site request forgery (CSRF) attacks, but the browser is not sending the necessary cookie.
To fix this issue, you can try the following steps:
Step 1: Clear your browser's cookies and cache.
Step 2: Disable any browser extensions that may be blocking cookies.
Step 3: Check your browser's privacy settings and make sure that third-party cookies are allowed.
Step 4: Disable the 'Tracking Protection' feature of Firefox browser.
Step 5: If the website is using a Content Security Policy (CSP) header, make sure that it is configured correctly to allow the necessary cookies.
Step 6: Try accessing the website using an incognito/private browsing window.
Step 7: Finally, check with the website administrator to see if there is a known issue or if there are any other recommendations for resolving the error.
By following these steps, you should be able to resolve the "CSRF cookie not set" error and access the website using Firefox.


text:
Q: How to connect multiple HDDs to a computer? What is the best and most efficient way to connect 10 - 20 SATA HDDs to a home computer? I mean an ordinary motherboard supporting 2 connections for SATA HDDs.
The purpose of this assembly is to build a handy storage system for storing large files like movies, backups, etc. The current HDDs I have are mostly 3TB. Now I need to make an integrated archive for better accessibility to the data stored in different HDDs.

A: A typical desktop motherboard usually has much 4, 6, or even 8 SATA connections. You can add expansion cards to increase the number. 10-20 drives is likely not to have the physical space to put them in. You probably should consider an external NAS.

A: Typically that many hard drives in a single device isn't marketed to the general public.  The first thing you want to find is a chassis big enough to support all the hard drives you want.  The chassis you will want will need to be a server model or custom fabricated one.
Considering if your hard drives or lff or sff, you can fit 12 or 24 sata hard drives into this chassis, for example. http://h10010.www1.hp.com/wwpc/us/en/sm/WF05a/15351-15351-3896136-5080871-4290526-4324034.html?dnr=1
If you already have hardware, you can find a compatible 20 bay chassis that supports your drive needs like this.
Then you will need to purchase a powerful enough power supply(s) and you may want a raid card as well to connect all your hard drives. (Single expansion cards will work as well)

A: Can't really answer definitely without knowing how you plan to use those disks.
NAS/enclosures
For example, if you need a large storage, you might use a JBOD backplane or enclosure and "see" the 20 HDDs as two drives (possibly even with RAID). In this case the disk management is outsourced to the enclosure, and if you wanted to enquire about a specific drive status you'd need Linux compatible software capable of "talking" to the enclosure.
The above solution has the advantage of being flexible and well tested. A 10- or 12-disk enclosure on the other hand can be expensive, especially if you go for RAID-capable ones. There is a small risk of incompatibilities with the OS (which you can reduce if you're comfortable tweaking the kernel and modules); be sure to check with the vendor, and try downloading the drivers and reading the relevant README's before the purchase.
This is one possibility.
Issue: data transfer rate
Another drawback is bandwidth: the 10-disk enclosure will run at most at eSATA-1 speed (1.5 Gbps or 3 Gbps - you might achieve 6 Gbps on paper, but I wouldn't bet on that), even if it might be able to sustain that speed longer than a single drive would. Most desktop drives supply a sustained rate of ~500 Mbps, but an external enclosure might be able to read/write in parallel (RAID 0) and share the load between disks.
Issue: low-level control at disk level
If you want independent control of those disks (even just being able to query their SMART status, or know whether a disk has failed - cheap enclosures usually don't allow to do this programmaticallly, you have to visually inspect external LEDs), you need a multi-SATA expansion card (maybe more than one). This will definitely be cheaper than a DIY NAS as above.
Issue: what is really on an enclosure disk set
Unless you go for the JBOD solution and "see" the 20 disks as 20 independent disks, to be handled separately at increased central computational cost, the CPU in the enclosure will allocate space on a set of, say, 10 disks and devise an optimal strategy to access it. This means that on a single disk you won't have a full, independent file system but only a part of it. And which part exactly may be difficult to tell from the outside unless you are the enclosure's electronics that put it there in the first place.
What this means is that, if one disk dies, with the proper RAID setup you're still safe and no data gets lost. But if the electronics die you may find yourself with ten good hard disks that nobody knows how to read, and all data on them is still there, but unreachable; lost to all intents and purposes, needing restore from a complete backup.
So additional things you may want to investigate when purchasing a NAS/enclosure is what kind of data organization is supported and how likely will it be to find spare parts some years down the line. For example, many NAS are actually optimized, custom-built Linux boxes. If the NAS dies on you, chances are that connecting the disks to a suitable Linux computer will make the data on them accessible. Other vendors use proprietary schemes - sometimes standard schemes intentionally tweaked to be incompatible and "encourage" customer fidelity - and can't be read on other vendors' hardware.
Issue: powering all those disks
If not using an external powered enclosure, you'll have the problem of powering those hard disks. At spin-up, eight disks can draw current enough to send a stock PSU into overload, resetting the PC via the "power good" signal and looping the boot process, possibly forever (been there, done that. I'm told that sometimes the disks will keep spinning after the reset, so at the next cycle they won't draw that much current and the system will start. Even so, I shudder to think what that might do to the system's life expectancy). So you'd need one or more PSUs capable of delivering a substantial spin-up current (around 30-60 amp), or a card supporting "staggered/delayed spin-up" (not all do; when they do, they usually have two switch positions, "to be awakened immediately" and "to be awakened in 10 seconds". You might need more than that, if you wanted to spin up the hard disks in four groups).
The DIY option
A third possibility, still depending on what you need those disks for, is to refactor the whole architecture. A port multiplier will set you back around USD 500. A 8-SATA motherboard with gigabit Ethernet can cost as low as USD 79. Three such motherboards, three oversize power units and one gigabit switch, and you have something that can handle 24 hard disks independently (and much more flexibly).
Considerations: a balanced architecture
Even if you prefer the double-port-multiplier-enclosure USD 1,000 solution, you might consider investing into a computer upgrade: a 2-SATA motherboard is probably long in the tooth, and might not get you all the bang for the buck a PME is built to deliver.
Considerations: disk failure rate and maintenance costs
Also consider that dealing with 20 disks, disk failure is something you really want to plan for. Hot-swap capabilities and RAID offloading are much more common (and easy to use/implement) in external NAS/multipliers than in DIY solutions; you may want to factor in the maintenance and downtime costs.
External enclosure failure rate
For external enclosures, you'll often hear horror stories about enclosures failing and even destroying the disks inside, or at least shortening their lifespan. It happens. The main reason why this happens is that enclosure builders are too often lowest-bidding cheapskaters, and they do not pay sufficient attention to a simple fact - a hard disk is an electric inductive motor with a bunch of sensitive electronics on't. It therefore requires, or at the very least it desires, a proper working environment. For a hard disk this boils down to "constant temperature, not too warm, and clean input current". I've met several enclosures that failed abysmally on both counts, delivering "dirty" power with spikes and over/undervoltages, which is the death of electronics, and relying on passive cooling or having a single, often undersized, 12V rear fan with neither redundancy nor failure mode. Which means that when, not if, the USD 2,00 fan fails, the power is not cut, no alert buzzer sounds, and a half dozen of USD 250,00 disks may start silently getting hotter and hotter, until they lock or crash. When that happens, the system can remain powered and in some cases (it depends on the hard disks and their failure mode) actually get even hotter. I have seen a 5 disk enclosure with the plastic front melted. Needless to say, the RAID array was unsalvageable - all disks were dead (thank God for adequate and updated backups!).
Unfortunately, while things like "two redundant fans" or "overtemperature alert" can be gleaned from pictures and manuals before purchase, they're usually available only on much more expensive enclosures. A very safe thermal protection can add up to USD 10 to the bottom line, and several manufacturers seem to believe that risking 2,500 USD of magnetic storage to save those USD 10 is worthwhile.

A: As Keven suggested it's possible but you're obviously going to be limited on case space if you don't want it all sprawled out.
NAS is a good idea but you'll need more hardware, so you could look at RAID arrays or cards for your PC if you have a case big enough.

A: you can easily do 10 to 12 per MB with a big enough power supply and a pair of PCI SATA cards.
some motherboards have a native support for 4 or 8 SATA drives, and i'd look for one that has 3-4 PCI expansion slots so you can use atleast 2 of those for cards. then you just network them together as shared access. and 1200W power supplies!
now you havent explained what the purpose for so many drives when 4Tb drives are available, so WE can only guess what your up to. possibly considering speed as they could be used for data cache buffers if you were working with huge image files, but still one is good enough for that. so knowing WHY matters unless it is just for storage, then a raid array is only 5 drives at maximum per array for 3x redundancy (2 striped pairs and a third as backup to those). and the only reason for that is if you had a drive size limitation recognized and dozens of 200Mb drives to be used (but then again those would be IDE (parellel) not SATA interconnects.
alternatively USB through a hub can stack (daizychain) up to 127 devices through one USB port, but that's a lot of wiring nest, NAS w/4 drives per device would be a better alternative. either way your talking quite the expense

A: You don't, really. There's a few problems you need to deal with. You'd certainly not have enough power connectors in the average power supply - most would come with 6-8 at most. You could possibly use additional power supplies. Your case wouldn't have enough room for all those drives, you need a bigger case. You'd need to add port multiplier cards and backplanes...
You'd end up with something like one of backblaze's pods - a massive box of drives with lots of backplanes, multiple PSUs and lots of cooling. This wouldn't be an average desktop in any manner. With this many drives, it might make sense to consider having a few regular cases and simply splitting up the storage, your motherboard and case won't be a big cost factor with respect to the whole system, AND it would have better reduncancy

A: This is doable :) Answer controller (raid or HBA) card capable of staggered spin-up. Depending what the rest of the "stuff" in the case an startup in-rush currents 600-800 Watt power supply will be enough.
I used to run dual Xeon (socket 1366) motherboard with 96GB ram with two raid controllers and to 8x2.5 backplanes and 6 3.5" drives connected to motherboard SATA to power that up I used two PS 550W and dedicated for all and only drives 450W with drives starting 1 sec apart I didn't have any issues powering it up.
One thing start controller without drives connected first and set spin-up delay first. On some cards that value set to 0 by default. Jumper to enable RPS option (Reduced Power Spinup) will be needed if power supply and drives do not support SATA 3.3 specification


text:
Q: ¿Cómo obtener cambios de un Observable? Tengo un proyecto de Angular2+ donde tengo un servicio con un Observable, el cual se actualiza su valor al ejecutarse una petición HTTP.
resultados$: Observable<any>;
buscar( termino: string ) {
    this.resultados$ = this.http.get(`${environment.urlAPI}/products?&name=${termino}`).pipe(
      map( (data : any) => {
        return data.products;
      })
    );
  }

El método buscar() lo ejecuto desde un componente (buscardorComponent) al hacer click() en un elemento.
buscar() {
  this.busquedaService.buscar(this.busqueda);
}

Esto actualiza la variable resultados$ del servicio correctamente.
En otro componente necesito leer los cambios de resultados$ del servicio para poder mostrar la data.
export class BusquedaComponent implements OnInit {
  resultados$: Observable<any>;
  constructor(private busquedaService: BusquedaService) { }
  ngOnInit() {
    this.resultados$ = this.busquedaService.resultados$;
  }
}

Dentro del HTML de BusquedaComponent voy a utilizar el pipe async para poder subscribirme y desubscribirme del observable. Además de utilizar un ngFor para mostrar la data.
El problema es que al hacerlo en el ngOnInit() en ese momento el observable del servicio aún se encuentra vacío. ¿Cómo puedo sincronizar ambos observables para que cuando cambie el observable del servicio cambie el observable del componente?

A: te recomiendo usar una variable reactiva (RxJs) para tu caso puedes usar subject, en tu servico declara la variable asi:
productos = new Subject<Productos[]>();

Esta variable devuelve un observable entonces nos podemos subscribir a el desde el componente A
this.servicio.productos.subscribe((productos: Producto[]) => {
     // tu logica
});

supongamos que desde otro componente B actualizamos los datos, por tanto queremos que el componente A reaccione a esos datos para ello llamamos el metodo next y pasamos los nuevos datos, por tanto el componente A reaccionara
this.servicio.listar().subscribe(productos=> {
           this.servicio.productos.next(productos);
});

si tu aplicacion se vuelve muy grande entonces te recomiendo usar el patron Redux con NgRx


text:
Q: Custom Routing in mvc4 I am using mvc4 framework and .net framwork 4.5. I need a url like this:
www.examples.com/name (note:  'name' will be change dynamically)
which routes to the same page.
I have tried like this but getting error
My action method is like this:
public ActionResult Userlist(string status)
{
    return View();
}

Route Config
routes.MapRoute(
                 "user",
                "{status}",
                new { controller = "Home", action = "Userlist" }
            );

How can I create a route syntax and redirect this to a controller?

A: public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Add this route config
    routes.MapRoute(
        name: "Default_Userlist",
        url: "{status}",
        defaults: new { controller = "Home", action = "Userlist" },
        namespaces: new[] { "MyMvcProject.Controllers" }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        namespaces: new[] { "MyMvcProject.Controllers" }
    );

}

Don't forget to replace the "MyMvcProject" with the name of your project.
Issue
This is a bad practice because the value of the status could easily cause conflicts with your action methods.


text:
Q: How to upgrade disutils package PyYAML? I was trying to install chatterbot which has a dependency on PyYAML=3.12. In my Ubuntu machine installed PyYAML version is 3.11. So I used the following command to upgrade PyYAML:
sudo -H pip3 install --upgrade PyYAML
But it gives the following error:

Cannot uninstall 'PyYAML'. It is a distutils installed project and
  thus we cannot accurately determine which files belong to it which
  would lead to only a partial uninstall.

My pip3 version is 10.0.0.
How to resolve this?

A: You can try this:
$pip install --ignore-installed PyYAML

A: I personnaly had PyYAML installed on anaconda, just executing 'conda remove PyYAML' and then executing my pip command worked.

A: conda remove PyYAML

conda remove will take time
pip install chatterbot
pip install chatterbot_corpus

In this way it sloved my error while I was trying from chatterbot import chatbot

A: I found in this Github issue that pip 10 no longer uninstalls distutils packages. So I downgraded to pip 8.1.1. And now it works.
If anybody, who are viewing this question, knows how to uninstall or upgrade distutils package with pip 10.0.0, please let me know here. :)
(If anybody needs)
And to downgrade pip, I used the following:
sudo -H pip3 install pip==8.1.1

A: I have had a similar issue where the PyYAML package was installed by conda. There is another answer to use conda remove.
Instead I have got round this issue using conda update PyYAML, effectively using conda to update the dependency which pip is trying itself to update.

A: I just had to uninstall python3-yaml and try with pip again
sudo apt-get purge python3-yaml

A: Try using the --ignore-installed flag:
sudo -H pip3 install --ignore-installed PyYAML
This works because to upgrade a package, pip first uninstalls the old version, then installs the new version. It is the uninstall step that fails for distutils packages. With the --ignore-installed flag, the uninstall step is skipped and the new version is simply installed on top of the old one.

A: Issue:

Cannot uninstall 'PyYAML'. It is a distutils installed project and
  thus we cannot accurately determine which files belong to it which
  would lead to only a partial uninstall.

Solution : Remove Dist Package and RUN
sudo rm -rf /usr/lib/python3/dist-packages/yaml
sudo rm -rf /usr/lib/python3/dist-packages/PyYAML-*
Removing folder from distutils works

A: If --ignore-installed is NOT the case for you, and you are running Debian/Ubuntu, then you can try following solution.
PyYAML could possibly be installed with apt, as a dependency of another package.
To debug that:

*

*Detect a package name: run apt list --installed | grep python and search for any yaml occurrence.

*Let's say, you've detected a package python3-yaml.

*Search for reverse dependencies: apt-cache rdepends --installed python3-yaml
Then you can:

*

*either delete unused reverse deps along with python3-yaml

*or delete python3-yaml via dpkg -r --force-depends python3-yaml and
re-install it via pip

*or make a decision on your own and share results in comments

A: The following code will help:
rm -rf /usr/lib/python3/dist-packages/yaml
rm -rf /usr/lib/python3/dist-packages/PyYAML-*
rm -rf /usr/lib/python3.8/site-packages/PyYAML-*
sudo -H pip3 install --ignore-installed PyYAML


text:
Q: Convert Callback to Promise in Publish Subscribe Model Let say we have a service called A and it has the function subscribe(callback). The subscription from the service is an open connection that can receive data at any time, and the data can be accessed through the callback.
Can we convert this callback to promise? if so, how?
Sample
A.subscribe((error, data) => {
    // do something with data
});

A:
Can we convert this callback to promise?

Not just one promise, no, because a promise can only be settled once, with a single fulfillment value (on success), but you have a series of values (often called an "observable"). So you can't convert that to return a promise, unless of course you want the promise to only fulfill with just one of the values (the first, for instance).
You could convert it to an asynchronous iterator (perhaps using an async generator function). As the name implies, an asynchronous iterator provides a series of values asynchronously, by returning a series of promises. I can't say whether an asynchronous iterator is applicable to your use case, but it's the closest thing to a promise-based observable that comes to mind.
Here's an observable-to-async-iterator implementation designed for Angular's observables, but which could be adapted as necessary. (Sadly, there's no license indicated, so I can't copy it into the answer.)

A: duplexStream
As TJ suggests, you cannot represent a subscription with a single promise. However, you only need one variable and the ability to recreate the promise. I have used a technique similar to the one described in TJ's link but with notable differences in abstraction. duplexStream below gives the caller a read function for any stream consumers in your program, and a write function to use for stream producers -
function duplexStream () {
  let t = defer()
  async function* read () {
    while (true) yield await t.deferred
  }
  function write (err, value) {
    if (err) t.reject(err)
    else t.resolve(value)
    t = defer()
  }
  return [read, write]
}

defer is a simple abstraction to provide an externally controlled promise -
function defer () {
  let resolve, reject
  return { deferred: new Promise((res, rej) => (resolve = res, reject = rej)), resolve, reject }
}

Let's say we have two HTML elements -

channel
duplexStream is generic and not tethered to a particular library or class. We can now use it to convert an observable to an async iterator. Note read can be called multiple times and all readers will get values passed to write. write can also be given to any number of producers.  By providing read and write as generic functions to the caller, these handlers can be managed during ordinary publish and subscribe events.
Abstracting on top of duplexStream, we create a channel with familiar publish and subscribe methods -
function channel ([read, write] = duplexStream()) {
  return {
    publish(v) {
      if (v instanceof Error)
        write(v)
      else
        write(null, v)
    },
    async subscribe(onValue, onError = console.error) {
      while (true)
        try {
          for await (const v of read())
            onValue(v)
        }
        catch (err) {
          onError(err)
        }
    }
  }
}

Given some <form> -
<form id="myform">
  <button type="button" name="b1">▶ next value</button>
  <button type="button" name="b2">⏺ some error</button>

<output name="foo"></output>

<output name="bar"></output>

</form>

We create a channel, A, and make two <button> publishers and two <output> subscribers -
const f = document.forms.myform
const A = channel()

// publishers
f.b1.addEventListener("click", event => A.publish(String(new Date)))
f.b2.addEventListener("click", event => A.publish(Error("error")))

// subscribers
A.subscribe(v => f.foo.value += v + "\n")
A.subscribe(v => f.bar.value += v + "\n")

Each click of ▶ will publish a value to each subscriber -

render preview

Clicking ⏺ will publish an error to the console, yet subsequent publishes using ▶ will still work.
demo
Run the snippet below to verify the results in your own browser -

function duplexStream () {
  let t = defer()
  async function* read () { while (true) yield await t.deferred }
  function write (err, value) { if (err) t.reject(err); else t.resolve(value); t = defer() }
  return [read, write]
}

function defer () {
  let resolve, reject
  return { deferred: new Promise((res, rej) => (resolve = res, reject = rej)), resolve, reject }
}

function channel ([read, write] = duplexStream()) {
  return {
    publish(v) { if (v instanceof Error) write(v); else write(null, v) },
    async subscribe(onValue, onError = console.error) {
      while (true) try { for await (const v of read()) onValue(v) } catch (err) { onError(err) }
    }
  }
}

const f = document.forms.myform
const A = channel()
f.b1.addEventListener("click", event => A.publish(String(new Date)))
f.b2.addEventListener("click", event => A.publish(Error("error")))
A.subscribe(v => f.foo.value += v + "\n")
A.subscribe(v => f.bar.value += v + "\n")
pre { margin: 0.5rem 0; }
<form id="myform">
  <button type="button" name="b1">▶ next value</button>
  <button type="button" name="b2">⏺ some error</button>

<output name="foo"></output>

<output name="bar"></output>

</form>


text:
Q: Load data into a Knockout component via AJAX call I'm used to loading up partial views and user-controls from ASP.NET with some data when its requested. After seeing Knockout components, I tried to figure out how to do something similar with the documentation, but couldn't figure it out.
Can anyone help me with a quick example of how to do something simple like take a table full of data, and load up a Knockout component based on the row that was clicked?

        Fetch this record

    <client-information params="???"></client-information>

ko.components.register('client-information', {
    viewModel: function(params) {
        var self = this;

        self.someProperty = params.???
    },
    template: { element: 'note-preview-template' }
});

self.fetchNote = function(id) {
    //AJAX call that would load the data into <client-information>
}

So clicking the link would make an AJAX call to load up the component's data on demand. I don't need to load up the component at page load, but would like to reuse the component elsewhere in my application with similar behavior.
Is it even worth using components or should I just create a second viewmodel that has all the functionality wrapped in it?

A: just use Jquery's getJson (assuming your providing json to the client)
Once you get the data in via that method apply it to your observable array...
good practice is to extract the underlying array of the observable and push the new values in one by one then mark the observable array as mutated
Once you have the Json from the server this post should help you with updating your observable array:
Update Knockout.js Observable from JSON


text:
Q: Android Take Photo thumbnail code not working anymore? I have some code using MediaStore.ACTION_IMAGE_CAPTURE intent to capture thumbnails.  It has been working until recently :-(
The following is my code:
protected void takePicture() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    if (intent.resolveActivity(getMainActivity().getPackageManager()) != null) {
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    } else {
        Log.e(tag, ">>No Activity available to handle camera photo");
    }
}

// ...
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            enableUserInteraction(false);
            Bitmap bmp = (Bitmap) data.getExtras().get("data");

        }
    } else {
        // user canceled
    }
}

(permission stuffs omitted)
my code pretty much copied from the following android link https://developer.android.com/training/camera/photobasics
In my newer device running Android 9, the activity resultCode is always canceled, while same app/code still working on older Android version.
Any advice, fixes, or workaround are highly appreciated.


text:
Q: How can i get all the files that DO NOT start with "Something"? The line below fetches all files that start with Cake.
Dim fi As System.IO.FileInfo() = di.GetFiles("Cake*")

How can i write the search pattern to get all the files, that do not start with Cake?

A: Just wanted to give the VB.Net version (converted from @Daniel A. White's C# version) in case anyone else stumbles on this.
Dim FI = DI.GetFiles().Where(Function(f) Not f.Name.StartsWith("Cake"))

A: This will be in C#, but it should get you close.
FileInfo fi[] = di.GetFiles();
var doNotFiles = fi.Where(file => !file.Name.StartsWith("Cake"));

A: You get all the files that start with something and use all that are not in that list and are in the original list?


text:
Q: Suppress multiple package/library loading messages I am loading multiple packages using the following code.
Packages <- c("gridExtra", "scatterplot3d", "plot3D", "gridExtra", "plyr", "ggplot2", "magrittr", "reshape2", "data.table")
lapply(Packages, library, character.only = TRUE)

and it prints following loading messages
## [[1]]
## [1] "gridExtra" "stats"     "graphics"  "grDevices" "utils"     "datasets"
## [7] "methods"   "base"
##
## [[2]]
## [1] "scatterplot3d" "gridExtra"     "stats"         "graphics"
## [5] "grDevices"     "utils"         "datasets"      "methods"
## [9] "base"
##
## [[3]]
##  [1] "plot3D"        "scatterplot3d" "gridExtra"     "stats"
##  [5] "graphics"      "grDevices"     "utils"         "datasets"
##  [9] "methods"       "base"
##
## [[4]]
##  [1] "plot3D"        "scatterplot3d" "gridExtra"     "stats"
##  [5] "graphics"      "grDevices"     "utils"         "datasets"
##  [9] "methods"       "base"
##
## [[5]]
##  [1] "plyr"          "plot3D"        "scatterplot3d" "gridExtra"
##  [5] "stats"         "graphics"      "grDevices"     "utils"
##  [9] "datasets"      "methods"       "base"
##
## [[6]]
##  [1] "ggplot2"       "plyr"          "plot3D"        "scatterplot3d"
##  [5] "gridExtra"     "stats"         "graphics"      "grDevices"
##  [9] "utils"         "datasets"      "methods"       "base"

I tried suppressWarnings and suppressMessages but it didn't solve the problem
suppressWarnings(suppressMessages(Packages <- c("gridExtra", "scatterplot3d", "plot3D", "gridExtra", "plyr", "ggplot2", "magrittr", "reshape2", "data.table")))
suppressWarnings(suppressMessages(lapply(Packages, library, character.only = TRUE)))

I looked at these STO posts but they didn't help enter link description here enter link description here

A: This "message" is the return value of the lapply command. If you don't want to see this information, assign the result to a variable.
x <- lapply(Packages, library, character.only = TRUE)