text:
Q: RISC-V Examples Using Pointers I have an engineering assignment where I have to use RISC-V to decide whether or not the first character of a string is capitalized. I'm having trouble finding the first character of my string. (I commented out my if condition)
    .data
enterString: .string "Enter a string: "
lowerCaseResult: .string "The first character is a lower-case letter\n"
upperCaseResult: .string "The first character is not a lower-case letter\n"
string: .space 82
    .text
main:
    li a7, 4
    la a0, enterString
    ecall

    li a7, 8
    addi a1, zero, 20
    la a0, string
    ecall

    la s1, string
    sb a1, 0(s1)
    mv a0, a1
    li a7, 4
    ecall

    #slt t0, a0,zero
    ##beq t0, zero, secondCondition
    li a7, 10
    ecall

firstCondition:
    li a7, 4
    la a0, lowerCaseResult
    ecall

    li a7, 10
    ecall

secondCondition:
    li a7, 4
    la a0, upperCaseResult
    ecall

    li a7, 10
    ecall

Any... pointers?


text:
Q: "incompatible types" при использовании setSelectionModel() Есть строки кода:
private JList jlResultsList;

И в конструкторе:
jlResultsList = new JList(arraySearchResult);
jlResultsList.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);

IDE отмечает как ошибку ListSelectionModel.SINGLE_SELECTION.
А при попытке компиляции выдает:

Error:(49, 59) java: incompatible types: int cannot be converted to javax.swing.ListSelectionModel

import javax.swing.*; прописан. В чем может быть ошибка?

A: Должно быть так:
jlResultsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Метод setSelectionMode принимает значение int, одно из трёх:

*

*ListSelectionModel.SINGLE_SELECTION

*ListSelectionModel.SINGLE_INTERVAL_SELECTION

*ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
В то время как метод setSelectionModel принимает ListSelectionModel. Так как передавать int вместо ListSelectionModel некорректно, то и возникает ошибка.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which type of locking should be used to ensure 1 trasaction at a time? I have a situation where I need to pick one entry from a table [table containing only 1 column id which is also a primary key], and in the same transaction I want to increment the key value and save it in the database. During this transaction, I don't want any other transaction to read the table, since unique id is required every time.
For e.g. table contains only one entry with id = 1 initially,
In transaction t1 -> select entry from table where id = 1 -> some processing -> save a new entry in the table [not incrementing id explicity since its AUTO_INCREMENT type].
Now during t1, no read should be made on this table [and I don't want to discard these read requests], read can be made only after 2nd entry with id=2 is stored in the table.
Findings: After some research I came to know about optimistic and pessimistic lock types and found pessimistic one more suitable, but still cannot relate to my situation. Please guide.
Adding code level changes that I have done to lock transaction:
public interface CodeKeyRepository extends JpaRepository<CodeKey, Integer> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value = "3000")})
    CodeKey findFirstByOrderByIdDesc();
}

CodeKey is the entity for above mentioned table, containing only 1 column id.


text:
Q: Docker Swarm - Should I remove a stack before deploying a stack? I am not new to Docker, but I am new to Docker Swarm.
Our deployments typically consist of building a new docker image with the latest code, pushing that to our registry and then running docker stack deploy against a compose file.
My question is, do I need to run docker stack rm $STACK_NAME before running the deploy?
I'm not sure if the deploy command for swarm is smart enough to figure out that a docker image has changed and that it needs to do something.

A: You redeploy the same stack name without deleting the old stack. If you expect to have services deleted from your compose file, then you'll want to include the --prune option. For any unchanged service, swarm will leave it unmodified. But for any services with changes, including a new image on the registry server, you will see a rolling update performed according to the update config you specify in the compose file.
When you use the default VIP to connect to a service, as long as the service exists, even across rolling updates, the VIP will keep the same IP address so that other containers connecting to your service can do so without worrying about a stale DNS reference. And with a replicated service, the rolling update can prevent any visible outage. The combination of the two give you high availability that you would not have when deleting and recreating your swarm stack.


text:
Q: Change values in a csv with PS according to predefined values Hello fellow Stackoverflowers,
once again, I am stuck at a certain problem which I hope can be solved with PS:
A GIS program puts out lines in the following form into a csv:
"House 5";9660.7734;1782.7454;0;0;
"House 9";9675.0684;1779.7888;0;0;
"House 8";9675.0684;1779.7888;0;0;
"House 2";9688.3779;1777.323;0;0;
"House 12";9709.5742;1772.3938;0;0;
"House 11";9709.5742;1772.3938;0;0;
"House 12";9734.2217;1771.4075;0;0;
"House 8";9755.9111;1770.4211;0;0;
"House 5";9779.0801;1770.9155;0;0;
"House 7";9779.0801;1770.9155;0;0;
"House 2";9802.7412;1770.9155;0;0;

and so on....
I would like to keep that form but change each line's value after the 3rd semicolon (here 0) to values that are speficied by each line's 1st value (House XX). The values to be applied are 15 for House 5, 12 for House 8, 8 to House 2 and 3 to House 12.
Also, there are "Houses" in the list that dont have to be changed: House 9, House 11 and House 7.In the end , the output file (again csv) should look like this:
"House 5";9660.7734;1782.7454;15;0;
"House 9";9675.0684;1779.7888;0;0;
"House 8";9675.0684;1779.7888;12;0;
"House 2";9688.3779;1777.323;8;0;
"House 12";9709.5742;1772.3938;3;0;
"House 11";9709.5742;1772.3938;0;0;
"House 12";9734.2217;1771.4075;3;0;
"House 8";9755.9111;1770.4211;12;0;
"House 5";9779.0801;1770.9155;15;0;
"House 7";9779.0801;1770.9155;0;0;
"House 2";9802.7412;1770.9155;8;0;

So, when I provide the changevalues for all the different "Houses" (could also use a list), can a PS script save me the work of manual changing?
Thanks in advance!

A: So It's hollidays here, but I feel like doing sombody's homework :
Import-Csv yourfile.csv -Delimiter ';' -header 'a','b','c','d','e' | % {$a=$_;switch -regex ($_.a) {.*5 {$a.d=15} .*8 {$a.d=12} "House 12" {$a.d=3} "House 2" {$a.d=8}};$_}

You can pipe to export-csv.


text:
Q: Height of the div respective to other DIV Hi I have DIV structure something like this.

   Left Col Content

   Right Col Content

I want to calculate the height of the right col. and that height to Left col.

A: I presume you want to set the left columns height the same as the right one! if so this would work.
$(".leftCol").height($(".rightCol").height());

Although you would only want to do this when the DOM is ready so it would be wise to only execute the code when the page is fully loaded or the column resizes.
$(function() {
    $(".leftCol").height($(".rightCol").height());
});

HTH

A: var leftHeight = $(".leftCol").height();
var rightHeight = $(".rightCol").height();

var diff = leftHeight - rightHeight;

More info here


text:
Q: Cannot Read an item from a DynamoDB Table using the DynamoDB Node SDK docClient I am new to DynamoDB docClient for Node. I am trying to do a simple read an item call but it throws this error
The provided key element does not match the schema

The link that I am following
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.02
Here is my code
const id = req.params; //value is 83166ce1-b36b-4074-b586-e2468346eb03
const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName: 'users',
  Key: {
    'id': id,
  }
};

docClient.get(params, function(err, data) {
  if (err) {
    console.log(err);
    res.status(500).send("Error fetching user item from DB");
  } else {
    res.status(200).json(data.promoCredits);
  }
});

Here is my table configuration
Table Configuration
My Items
Items in Table
I have tried to google but I cannot find an answer to this. Currently I am returning all my users and manually filtering but that is not the optimal solution. Please help.
Hitting my request like this
http://localhost:8081/api/user/getPromoCredits/83166ce1-b36b-4074-b586-e2468346eb03

my endpoint config is
app.get('/api/user/getPromoCredits/:id', user.getUserPromoCredits);

Thank you

A: It was an issue where I was not deconstructing my id, and id was of type Object. Based on the two comments above, thank you so much for your help...
Updated to
const { id } = req.params;


text:
Q: Problem with cross-referencing subsections in Appendix I have a problem with cross-referencing subsections in the appendix using the AER-AEA document class. Here is an example:
\documentclass[AER]{AEA}
\newtheorem{proposition}{Proposition}

\begin{document}

\begin{proposition}\label{Prop1}
Interesting proposition.
\end{proposition}

Proof of Proposition~\ref{Prop1} is in Appendix~\ref{appendix_A1}.\\

\appendix
\section{Appendix}
\subsection{Proof of Proposition~\ref{Prop1}}\label{appendix_A1}
Proof is here.

\end{document}

This code gives:
Proof of Proposition 1 is in Appendix A.A1.
But I would like to get:
Proof of Proposition 1 is in Appendix A1.

A: The AEA class
does
\renewcommand\thesubsection{\thesection\@arabic\c@subsection}

in the \appendix command, i.e. prepending with \thesection, which is \@Alph\c@section effectively.
The reference format \p@subsection can be changed to use \theproposition only, by removing specific code for subsection.
Please note that journal editors might reject this change.
Edit: Some explanations
The macro \g@addto@macro adds additional code to an existing macro code, so \g@addto@macro{\appendix}{foo} would lead to printing foo if \appendix has been used.
Since this \g@addto@macro is a macro with @ - letter in its name, the \makeatletter...\makeatother macro pair is needed to allow @ in macro names.
The \AtBeginDocument hook 'guarantees' that our local changes to \appendix are done at the beginning of the document, after all other \AtBeginDocument - hooks that are provided by the class or the packages, so our changes are the last in this chain of commands.
\documentclass[AER]{AEA}
\newtheorem{proposition}{Proposition}

\makeatletter
\AtBeginDocument{
\g@addto@macro{\appendix}{\renewcommand{\p@subsection}{}}
}
\makeatother

\begin{document}

\begin{proposition}\label{Prop1}
Interesting proposition.
\end{proposition}

Proof of Proposition~\ref{Prop1} is in Appendix~\ref{appendix_A1}.\\

\appendix
\section{Appendix}
\subsection{Proof of Proposition~\ref{Prop1}}\label{appendix_A1}
Proof is here.

\end{document}


text:
Q: Debug jsrender template If I have any syntax error in jsrender its hard to debug. Is there any way to debug.
I use {{*debugger;}} and $.views.settings.allowCode=true;
and
$.views.settings.debugMode(true);

But none of them are working.

A: There is a new documentation topic which has been added to www.jsviews.com, here:
Error handling and debugging
which should answer your questions...


text:
Q: how to refer to a base class's derived class? class Element { };
class Container {
    vector<Element*> elements;
};

The above is the original code. I was told not to change the above code. Now I have
class IndexElement: public Element {
    int b_index;
};

class Container* ctr;

Now I have ctr->elements. But Element has no member b_index. Any simple method to redirect the attribution of elements from Element to IndexElement? Thanks in advance!

A: You have one option: you know that you have a IndexElement and not a Element in the vector, and then you can use static_cast<IndexElement*>(elements[i]);. Be aware that if you don't have only IndexElement, then this will utterly break.
If you can modify b, then you have another option, by making b virtual. If you don't know, you may have Elements and IndexElements, and in that case use dynamic_cast<IndexElement*>(elements[i]); and test it the result is nullptr or not. In this instance, b must be virtual (hence virtual destructor).
(I assume we are in Container, so direct access its members)
Full trial (that will break because no allocated elements) with the modified Elements:
#include <vector>

using namespace std;

class Element{
public:
    virtual ~Element() {}
};

class Container{
    public:
vector<Elements*>elements;
};

class IndexElement: public Element{
int index;
};

int main()
{
    Container aa;
    static_cast<IndexElement*>(aa.elements[0]);
    dynamic_cast<IndexElement*>(aa.elements[0]);
    return 0;
}

A: Well, even without virtual and RTTI (dynamic cast) you still have the option to track and check the IndexElement instances created, for example:
std::unordered_set<Element *> idxElemSet;

class IndexElement: public Element {
    int b_index;
public:
    IndexElement(int index) : b_index(index)
    { idxElemSet.insert(this); }

    IndexElement(const IndexElement& other) : b_index(other.b_index)
    { idxElemSet.insert(this); }

    // might also need the move constructor in case of c++11

    ~IndexElement()
    { idxElemSet.erase(this); }

};

int main()
{
    Container c;
    ...
    Element* e = c.elements[0];

    if (idxElemSet.find(e) != idxElemSet.end()) {
        IndexElement* ie = static_cast<IndexElement*>(e);
        // do something with ie->b_index
    }

    return 0;
}

So you can basically keep the set of addresses of all the instances created and when checking the particular instance, just check if the current object address is in the set.
The idxElemSet can be also static inside IndexElement and the class itself might just provide static conversion function which does the check and conversion internally, etc.


text:
Q: Visual Studio 2013 doesn't appear to install I have downloaded and installed Visual Studio 2010 (kind of successfully, but that's another story), and then attempted to install Visual Studio 2013 (update 2). The install tells me that it's finished successfully, but the application is nowhere to be found, despite all of the associated files and blend showing up. I don't think that this is a compatibility issue, but I have uninstalled and reinstalled VS2010 about 3 times, so that may have done something.
Both versions of VS were obtained legitimately through the Microsoft Dreamspark student program.
I would prefer to avoid reinstalling windows, if at all possible.
Images as proof:
VS2010 installed correctly
Suspicious lack of the VS2013 program folder

A: According to the image you posted, you're in the folder that Visual Studio 2013 installed in. You'll find it here:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe


text:
Q: Do HAM radios have a purpose? I'm mostly interested in what their purpose are in Fallout 4 since I seldom play Fallout 3 or New Vegas anymore, though it would be nice to finally understand how they worked for the previous fallouts.
I remember in Fallout 3 I had no idea what they were for. In Fallout 4 I see sometimes they activate an emergency frequency which I'm not sure if that's just for authenticity or if there is a purpose behind them.

A: According to the Fallout 3/NV wikia:

Generally, ham radio stations are only useful in that they broadcast a radio signal and serve as a beacon to lead a player to an otherwise difficult-to-find location. Players cannot affect a ham radio apart from turning the signal on or off. Ham radios are indestructible. Since all ham radios are set to the off position by default, they can be used as "breadcrumbs" for the player, turning them on to mark where he or she has been.
Only two ham radios have a more significant function in the game.
One is set up as part of the public-address system in the Super-Duper Mart. Raiders using the store as a base use the PA system to alert others in the building.
In the Operation: Anchorage add-on, Chinese technicians use ham radios to call for backup.

As for Fallout 4, it doesn't look like they serve any important purpose (see here and here)

A: In the RR Headquarters, one of the RR operatives is decoding the Morse Code coming over the Ham Radio on her desk.


text:
Q: How erlang returns exit status to linux When I tried to ssh to the IP in Linux through erlang.
SSH was getting successful, but while trying to check the exit status of the ssh
Its showing 255, which was treated as a failure case.
But when i tried to ssh to the IP without using erlang.
Its returning 0 in the success case.
Can you please let me know how erlang sends the exit status to linux.
I just want to know which files were responsible in sending the exit status to the linux.
Thanks in advance.


text:
Q: using django-tables2 in dashbord Trying to put django table into dashboard.html page. I can visualize my table in another html file but cant fix how to put inside the dashboard page
models.py

class Asset(models.Model):
    type = models.ForeignKey(AssetType, on_delete=models.CASCADE)
    lc_phase = models.ForeignKey("Asset_Life_Cycle.LifeCyclePhase", on_delete=models.CASCADE)
    name = models.CharField(max_length=30)
    # BaseSpatialField.srid()
    geom = models.GeometryField()

views.py
from .models import Asset
import django_tables2 as tables

class AssetTable(tables.Table):
    class Meta :
        model = Asset

class AssetTableView(tables.SingleTableView):

    queryset = Asset.objects.all()
    table_class = AssetTable
    template_name = 'deneme.html'

Tried this but didnt work

{% for asset in queryset %}

    <p>Name {{asset.name}} </span> </p>

  {% endfor %}

A: The beauty of django-tables2 is that you don't need to loop over all objects in your queryset. Just use the following code in your template which will display the table:

{% load render_table from django_tables2 %}

{% render_table table %}


text:
Q: How can I fix an sd card's gpt filesystem when gparted won't recognize any changes and I have superblock errors I simply want to properly format/partition my sd card so it can be used. I tried to format it but I have been continually hitting errors.
Specifically I would like to format it as ext4.

*

*However when I try to do so with gparted, after doing so and gparted updating the device, the file system is listed as unknown with error:

Unable to detect file system! Possible reasons are:

*

*The file system is damaged

*The file system is unknown to GParted

*There is no file system available (unformatted)

*The device entry /dev/sdb1 is missing

*furthermore, trying to run e2fsck on the partition and it cannot recognize any of the superblocks that I wrote after using mkfs.ext4

*I even used testdisk and it doesn't appear to properly restore the disk.

*I also tried creating a new gpt and even mbr record to try to start properly again from fresh to no avail.
I am almost certain the sd card still works I just can't figure out how to properly reset everything so that when I format my primary partition, it can then be properly used.


text:
Q: How to create an object dynamically I want to create an object on the fly, that is not assigned to a variable, and doesn't need a class definition.
In C#, it's possible via object initializers, or via ExpandoObject and dynamic keyword:
var ananymousObject = new { Property = "Value" }; // object initializer

or
dynamic instance = new ExpandoObject();
instance.Property = "Value";

How to do that in Android Studio?

A: Use HashMap
HashMap<String, Object> anon = new HashMap<>();
anon.set("property", value);

A: In Java you can write this "new ABC()" this creates anonymous object which doesn't have any reference here AB is any class name  like new String();

A: Java is much more strict in this case. So the short answer is no, Java doesn't have an Expando. The syntax just doesn't support that.
However there is an Expando in Groovy which is a dynamic language on top of java.
BTW, If you're using Expando for tests, there are a lot of various Mock related solutions: EasyMock, Mockito, JMock to name a few.


text:
Q: How to install UBIFS filesystem for SSD flash drive? I have SSD flash drive. So I want to make a new machine use UBIFS filesystem.
How can I do that? With Ubuntu desktop 17.0 dont have options for this filesystem.
And another question, with new filesystem, Could my machine run faster than ext2, FAT... filesystem? Because they are not designed to optimize for flash drive.
Thank you~

A: I had some result and found that. SSD called FTL devices, It transfer raw flash device to emulate block device with its controller. So My SSD can't use UBIFS like a filesystem. UBIFS just support for raw flash.
This link could make anything simple: https://digitalcerebrum.wordpress.com/random-tech-info/flash-memory/raw-flash-vs-ftl-devices/


text:
Q: How to remove an apostrophe from a string in a loop? I currently have a loop generating a URL to appear on a page. I have a few URL's that have an apostrophe in the string that it returns. I am attempting to remove the apostrophe from the URL. I am familiar with the .replace method which is what I'm attempting to implement. I am declaring a variable at the start of the case and then using the variable newUrl
Code:
     } else {

 let newUrl = sectorHTML += "
  "
//linkURLPart 1 = new ; linkUrlPart2 = article;
json.DataColumn1[r].ReportUrl = people's-home
    sectorHTML += "
";
                   newUrl = newUrl.replace("'", "")

                    }

Current output:
/new/article/people's-home/
expected output:
/new/article/peoples-home/


text:
Q: How can I evaluate a C function from a dynamic library in an R package? I'm trying to implement parallel computing in an R package that calls C from R with the .C function. It seems that the nodes of the cluster can't access the dynamic library. I have made a parallel socket cluster, like this:
cl <- makeCluster(2)

I would like to evaluate a C function called valgrad from my R package on each of the nodes in my cluster using clusterEvalQ, from the R package parallel. However, my code is producing an error. I compile my package, but when I run
out <- clusterEvalQ(cl, cresults <- .C(C_valgrad, …))

where … represents the arguments in the C function valgrad. I get this error:
Error in checkForRemoteErrors(lapply(cl, recvResult)) :
  2 nodes produced errors; first error: object 'C_valgrad' not found

I suspect there is a problem with clusterEvalQ's ability to access the dynamic library. I attempted to fix this problem by loading the glmm package into the cluster using
clusterEvalQ(cl, library(glmm))

but that did not fix the problem.
I can evaluate valgrad on each of the clusters using the foreach function from the foreach R package, like this:
out <- foreach(1:no_cores) %dopar% {.C(C_valgrad, …)}

no_cores is the number of nodes in my cluster. However, this function doesn't allow any of the results of the evaluation of valgrad to be accessed in any subsequent calculation on the cluster.
How can I either
(1) make the results of the evaluation of valgrad accessible for later calculations on the cluster or
(2) use clusterEvalQ to evaluate valgrad?

A: You have to load the external library. But this is not done with library calls, it's done with dyn.load.
The following two functions are usefull if you work with more than one operating system, they use the built-in variable .Platform$dynlib.ext.
Note also the unload function. You will need it if you develop a C functions library. If you change a C function before testing it the dynamic library has to be unloaded, then (the new version) reloaded.
See Writing R Extensions, file R-exts.pdf in the doc folder, section 5 or on CRAN.
dynLoad <- function(dynlib){
    dynlib <- paste(dynlib, .Platform$dynlib.ext, sep = "")
    dyn.load(dynlib)
}

dynUnload <- function(dynlib){
    dynlib <- paste(dynlib, .Platform$dynlib.ext, sep = "")
    dyn.unload(dynlib)
}


text:
Q: Undefined symbols for architecture arm64 I'm using a framework which someone else has written and I've included it in my project.
I run my application with xcode 6.1, i'm getting O-linker error 'Undefined symbols for architecture arm64'
Can anyone help me to resolve this issue?

A: There is no equivalent to thunking between 64 to 32 bit code: too much has changed (see: 64-Bit Transition Guide for Cocoa Touch).
The only solution is get the framework author to rebuild the framework with 64 bit support. If that is not possible, then you need to replace the framework with a different framework which does support 64 bit.


text:
Q: Teamcity Cloud Profile Canceling Builds in progress I am trying to setup Teamcity Autoscaling using EC2 instances as the agents
We keep having the agents shutdown mid-build

We have a value for "Terminate instance idle time" in the profile set to 120
The way i interpret that value is if no build has run on the agent for 2 hours it will terminate the agent.
Do I need to set another value to prevent it from shutting down mid build?


text:
Q: "Add Group Price" button not shown in magento my problem is: the button "Add Group Price" is not shown in magento backend.
I have made some changes to database but not exactly sure where!
it's the normal magento backend:

and here is my magento view:

as you see the button "Add Group Price" is not shown!!!
where should i fix?
any help appreciated.

A: You are using a right-to-left language so the buttons are on the opposite side.
Although I don't speak the language, I'm going to say with 99.99999999% confidence that the button is this one:

A:
is same as "Add group price(إضافة سعر المجموعة)"
good luck

A: so, as i see you have attribute value set as required, but i dont see any red asterisk symbol (*) near to it. and actually i dont see on screenshot Group Price field either?? so all you need is:
there is no magic. i dont see what you have done exactly. But it looks like you did something wrong.

create an attribute

*

*name it Group Price with code group_price

*set to Display on product page

*Add it to your Attribute Set

*edit product and enter Group Price value

*then call it on product view


text:
Q: Rails - Add games Association to users I'm building an association between Users and Games, Users can favorite or associate Games to their profile. But I got an issue with the routes or the link (I guess, maybe its something else).
I have a join table between Users and Games :

Game_User with games ID and User ID

The association is working fine in the console when I do this.
@user = User.find(session[:user_id])
@game = Game.find(params[:id])
@user.games << @game

games_controller.rb:
def favorite
  game = Game.find(params[:id])
  current_user.games << game
  flash[:notice] = 'You favorited #{@game.name}'
  redirect_to games_url
end

routes.rb
get "games" => "games#index"
post "games/:id" => 'games#favorite'

And I would like to do the same with my link.
Here is the list of the games, and for each a link to favorite them :
<% if current_user %>
    <% @games.each do |game| %>

        <%= game.name %>
        <%= game.plateform %>
        <%= game.typegame %>
        <%= link_to 'Show', game %>
        <%= link_to 'Edit', edit_game_path(game) %>
        <%= link_to 'Destroy', game, method: :delete, data: { confirm: 'Are you sure?' } %>
          <%= link_to "favorite", games_path, type: "favorite", method: :post %>

    <% end %>
<% end %>

My problem is : Creating the association between user and game(s) , when i click on the link Favorite, it's generating a new Game (def create game.new ... )

A: You're calling games_path in your link_to method, but that will give you games#create instead of favorite. You need to tell Rails what name you'd like to use, with a named route: post "games/:id/" => 'games#favorite', as: :favorite_game and use favorite_game_path(game) in your view.


text:
Q: Pythonic way to check if values are present in a dict I want to validate if there is a truth value present in a dictionary's values. If I validate the dict like below code then it says values exist as it would return dict_values(['']), which indicates in python that it's not None but if you'll check the dict then there is no value:
a = {1:''}
if a.values():
    print(a.values())
else:
    print('No values')

What's the best pythonic way to validate if a dict contains values or not? There can be cases where many keys are present but each has empty values.
Note:

*

*empty string would not be considered as a value (invalid, if condition would fail in this case).

*0 would be considered as a valid value.

*the value would not be a list/dict/tuple, it can be either string, int or float

A: It looks like all the usual falsey values are invalid, apart from numeric types of zero being valid. If this is the case, you can use Python's Truth Value Testing along with the numbers module from Python's standard library.
Simple solution:
This solution iterates over the dictionary's values twice.
Returns False if there is one or more invalid values.
from numbers import Number

a = {1: "", 2: 0, 3: 0.0}
all(isinstance(x, Number) or x for x in a.values())  # False

a = {1: "Hello", 2: 0, 3: 0.0}
all(isinstance(x, Number) or x for x in a.values())  # True

Better performance:
Here is_valid will only iterate until the first invalid value.
from numbers import Number

def _invalid(value):
    return not isinstance(value, Number) and not value

def is_valid(dict_):
    return next(filter(_invalid, dict_.values()), True)

Alt:
Returns True if there is one or more valid values.
next(filter(lambda x: isinstance(x, Number) or bool(x), a.values()), False)

A: Try this:
if a.values() and '' not in a.values():
I'm not sure this is the best pythonic way, but it is simple and it works.


text:
Q: How to distinguish installation of ArcView from ArcEditor? How would I tell an installation of ArcView from ArcEditor, if looking at only the installed files? Specifically, how do I distinguish

*

*ArcView 9.3 from ArcEditor 9.3

*ArcView 10.0 from ArcEditor 10.0

For example, the file ArcSOC.exe indicates an installation of ArcGIS Server.

A: My understanding is that the install files are the same between licensing levels. When installing you do not choose which licensing level to install. Available features are then determined by activation through the license manager.

A: The installs are the same.
If you go to desktop administrator and select the software product folder
you will see the options to switch between licensed products.
If you are using an ESRI network license you can change this setting readily.
If you are on a standalone you will only have the choice to use it or switch to a floating license.
In which case you would need to supply a license server.


text:
Q: Make two DIV elements with box-shadow not overlap thenselves I have two
 elements like so:

.lorem {
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:50px;
    box-shadow: 0px 0px 25px 10px rgba(30, 30, 30, 0.25);
}

.ipsum {
    position:fixed;
    bottom:0;
    right:0;
    width:15%;
    height:calc(100% - 50px);
    box-shadow: 0px 0px 25px 10px rgba(30, 30, 30, 0.25);
}

Lorem

Ipsum

and i want to have something like this.
Is there a way to do that without editing the already existing CSS rules?

A: I suspect you are looking for something like this:

.lorem {
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:50px;
    box-shadow: 0px 0px 25px 10px rgba(30, 30, 30, 0.25);
}

.ipsum {
    position:fixed;
    bottom:0;
    right:0;
    width:15%;
    height:calc(100% - 50px);
    box-shadow: -6px 22px 25px #ccc, 1px -6px 27px #fff;
    background: #fff;
}

Lorem

Ipsum


text:
Q: How to sum of value in gridview select data from database in asp.net I work in asp.net and i have one grid view in which i find out pf and ESI value from Basic Salary and I want proper solution of sum of total PF and total ESI in gridview footer in Repues So please help me

A: you have to write the code in RowDataBound Event of gridview.
i am posting a sample code for your reference try it yourself
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      Label lblPrice = (Label)e.Row.FindControl("lblPrice");
      Label lblUnitsInStock = (Label)e.Row.FindControl("lblUnitsInStock");

      decimal price = Decimal.Parse(lblPrice.Text);
      decimal stock = Decimal.Parse(lblUnitsInStock.Text);

      totalPrice += price;
      totalStock += stock;

      totalItems += 1;
   }

   if (e.Row.RowType == DataControlRowType.Footer)
   {
      Label lblTotalPrice = (Label)e.Row.FindControl("lblTotalPrice");
      Label lblTotalUnitsInStock = (Label)e.Row.FindControl("lblTotalUnitsInStock");

      lblTotalPrice.Text = totalPrice.ToString();
      lblTotalUnitsInStock.Text = totalStock.ToString();

      lblAveragePrice.Text = (totalPrice / totalItems).ToString("F");
   }
}

check this too http://msdn.microsoft.com/en-us/library/ms972833.aspx

A:   you can implement the code in RowDataBound Event of GridView

http://www.aspdotnet-suresh.com/2011/02/how-to-display-sum-of-columns-total-in.html
http://aspdotnetsubhash.blogspot.in/
http://www.ezzylearning.com/tutorial.aspx?tid=1676759
Please check your solution given url
May be you find your solution..............


text:
Q: How does sshd know which user belongs to which AuthorizedKeysFile? If I set a custom path for AuthorizedKeysFile, how does sshd decide which user this key belongs to?

AuthorizedKeysFile
Specifies the file that contains the public keys that can be used for user authentication. AuthorizedKeysFile may contain tokens of the form %T which are substituted during connection setup. The following tokens are defined: %% is replaced by a literal '%', %h is replaced by the home directory of the user being authenticated, and %u is replaced by the username of that user. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the user's home directory. The default is ''.ssh/authorized_keys''.

A: sshd doesn't need to decide which user a key belongs to; it knows which user is attempting to connect (user on the target system), and it knows which key is provided in the attempt.
After expansion, the file pointed to by AuthorizedKeysFile is used to determine whether the provided key is allowed for the target user. Again, it already knows which user this is (and it needs to to replace %u or find the file in the first place when it's relative to the target user's home directory).


text:
Q: Proving an isomorphism using the isomorphism theorems Is the following proof correct, or are certain steps illegal?
Suppose $f:G_1\to G_2$ is a surjective group isomorphism, $N_1\lhd G_1, N_2\lhd G_2$ normal subgroups, with $N_1=f^{-1}(N_2)$. Prove that $(G_1/N_1)\cong (G_2/N_2)$.
Proof:
As $f$ is surjective, we an use the first isomorphism theorem to get $G_1/\ker(f)\cong G_2$, which implies that $$(G_1/\ker f)/(N_1/\ker f)\cong G_2/(N_1/\ker f)$$
Using the first isomorphism theorem we also know that $$N_1/\ker (f)\cong f(N_1)=f(f^{-1}(N_2))=N_2$$
Combining this we can see that $(G_1/\ker f)/(N_1/\ker f)\cong G_2/(N_1/\ker f)\cong G_2/N_2$.
Using the third isomorphism theorem we have that:
$$ (G_1/\ker f)/(N_1/\ker f)\cong G_1/N_1$$
And from the last two lines we have $G_1/N_1\cong G_2/N_2$ $\tag*{$\Box$}$

A: It's basically correct. However,  some things you wrote requires proper justification or explanation. Namely,

*

*Show that $\ker f\lhd N_1$.

*How do you exactly mean $G_2/\, (N_1/\ker f) $?

For a more direct approach, consider the arising homomorphism $G_1\to G_2/N_2$.


text:
Q: Is there any defensive element for non-standard voltages on networks? Assume that an attacker join to our network as a good person and we give him a cable that is connected to one of our switches.
Now, If he connect the wires of that cable to a high voltage (60v for example), what happens? Our switch burns and some of our clients will disconnect. (And also may the network cards may burn also!) is this right?
Is there any device to prevents this kind of attacks? maybe a device that connect cables to switches via a electrical fuse?

A: First thing that will happen - the cable or router will fry itself. As ethernet is under 5 volts (think around 4v for gigabit, 3.5v for 100) they are not rated for high voltages.
Unless you are running power over ethernet, in which case 120v (or 240v) will be fine.
But this is mostly irrelevant - it's not a useful attack
Most companies will not bother trying to protect against this, as it is not a high value (or high likelihood) attack. What does the attacker manage to do? Fry a router/switch. Knock out a few clients? A DDoS attack is likely to have a bigger impact, and you don't need to be physically present.
The company will just pop it out, and plonk in a new one and everyone is back up and running. For standard network devices they may have ones in store and ready.
If the attacker tries to go for one of the core routers, your protection is more physical - why would you let them get into your data centre and plug into that router? Access should be strongly controlled there.


text:
Q: Mod re-write on sub folder I'm trying to mod re-write to a specific sub folder called /checkout this has an SSL certificate attached for https
So I have this in the root folder of my site -
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

# in http: force secure.html to https
RewriteCond %{server_port} !=443
RewriteCond $1 ^([^/]+)$ [NC]
# this kinda works below but is resolving to index2.php and is showing in the url so not really working yet
RewriteRule checkout/([^/]+)\.html$ https://mysite.com/checkout/index2.php [L]

Except that instead of showing something like
https://mysite.com/checkout/index.html
it shows
https://mysite.com/checkout/index2.php
(index2.php is a test url btw)
I've also tried amending the .htaccess in the sub folder to to something like
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteCond %{server_port} !=443
RewriteCond $1 ^([^/]+)$ [NC]
RewriteRule ^([^/\.]+)/?$ https://mysite.com/checkout/index2.php [L]

I just want to process
https://mysite.com/checkout/index.html or https://mysite.com/checkout/about-us.html as the same I would in the root like this
https://mysite.com/index.html => https://mysite.com/index.php (and then get the variables etc)
ie
 RewriteRule ^/?(catalogue-page)/([0-9]+)/([0-9]+)/([0-9]+)/([0-9]+)/([0-9]+) index2.php?friendly_url=$1&catalogue_id=$2&view=catalogue&categoryid=$3&subcategoryid=$4&subjectid=$5&item=$6

I think that https is more complex.
Any pointers/help etc much appreciated

A: Your RewriteRule seems to indicates that you are trying to take a non-secure url and display a different page via https, this in itself is not possible. Having said that your description doesn't sound like that is the overall aim.
If you wish to force non-secure URLs to be secure, this is fine and it's also fine to want requests for index.html to server index.php. It's not however possible to do this all in one fell swoop.
# first force urls to be secure.
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^checkout/([^/\.]+)/?$ https://mysite.com/%{REQUEST_URI} [R=301,L]

# now rewrite them, so that the requests all get served through the front controller
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^checkout/([^/\.]+)/?$ /checkout/index2.php [L]


text:
Q: Executing AsyncTask before the following code I have a problem and it's that I have a bundle in which I pass some info. The problem it's that the info that I get it's being retrieved from an AsyncTask and I need to execute it before the values will be set on the bundle.
This part of code resumes what happens:
String name = "";
final Bundle bundle = new Bundle();

new findCar(new OnCarListener()
{
    @Override
    public void onCarCompleted(String c) {

        synchronized (c)
        {
            name = c;
        }
    }

    @Override
    public void onCarError(String error) {
    }
}).execute(idCar);

Log.d("AsyncTask", "AsyncTask completed");
Log.d("AsyncTask", name);
bundle.putString(name);

And the lines that are below the AsyncTask are executed before it. What I need it's to execute the AsyncTask before the lines that it has below.
What I have tried:
1) As you can see in the code that I put above, I created an interface and try to synchronize the String that I pass from onPostExecute() method with the objective that it will be executed before the rest of the code, but it doesn't work.
2) I saw that you can block the UI Thread with AsyncTask.get() but it's not what I'm searching because I don't know how much seconds the AsyncTask will need to complete its objective.
3) If it is possible I would want to avoid use ProgressDialog.
4) I also tried to use the bundle directly inside onCarCompleted but it doesn't store the value into the bundle.
5) Furthermore, I tried executing the AsyncTask with .executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,idCar) but the result was the same.
Is there some option that let me execute the AsyncTask before the lines of code that are below it? I need to retrieve the info from the database before that setting it on the bundle, and not upside down.
I'm stuck here from hours. Any help will be welcome.
Thanks in advance!

A: AsyncTask is async, so when you'll receive the data is unknown.
For that reasons you have your callback.
Yours 4th solution is correct, but not fully. You should do ALL the things you need to do after you received the result only directly in callback method.
private Bundle bundle;

....
bundle = new Bundle();
new findCar(new OnCarListener()
{
    @Override
    public void onCarCompleted(String c) {
        processData(c);
    }

    @Override
    public void onCarError(String error) {
    }
}).execute(idCar);

void processData(String data) {
    bundle.putString(data);
    //Do all you need then
}

executeOnExecutor method with SERIAL_EXECUTOR is the same as just execute(), because the default executor of AsyncTasks is SERIAL_EXECUTOR.
Also, why do you synchronized your variable?

A: Here is why your current attempts have failed (mostly, you aren't really embracing the asynchronous nature of the problem at hand):
1) As you can see in the code that I put above, I created an interface and try to synchronize the String that I pass from onPostExecute() method with the objective that it will be executed before the rest of the code, but it doesn't work.
This fails for a lot of reasons, but primarily you aren't using synchronization for the correct reasons, and you aren't using it correctly (for example, only one thread is ever synchronizing on the string). Its not the way to go for this one.
4) I also tried to use the bundle directly inside onCarCompleted but it doesn't store the value into the bundle.
Actually, it probably does. But whatever you do with the bundle is probably finished by the time the async task has set the value
5) Furthermore, I tried executing the AsyncTask with .executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,idCar) but the result was the same.
The SERIAL_EXECUTOR executes async tasks serially, and would have no effect on what you are doing, since you only have one async task
What you should probably do is to put more logic into your onCarCompleted method. For example:
String name = "";
final Bundle bundle = new Bundle();

new findCar(new OnCarListener()
{
    @Override
    public void onCarCompleted(String name) {

        Log.d("AsyncTask", "AsyncTask completed");
        Log.d("AsyncTask", name);
        bundle.putString(name);
        // do something with the bundle here
    }

    @Override
    public void onCarError(String error) {
    }
}).execute(idCar);

A: Change a little bit like this way below. But I think you should throw this logic and update it: try to run AsyncTask and onPostExecute() do what it need do more to finish your works, it is easier to handle and avoid "before/after" problem.
String name = "";
final Bundle bundle = new Bundle();
final Object lock = new Object();
new findCar(new OnCarListener(){
@Override
public void onCarCompleted(String c) {

    synchronized (c)
    {
        name = c;
    }
lock.notify();//Unlock caller-thread
}

@Override
public void onCarError(String error) {
}
}).execute(idCar);

lock.wait();// Your current thread will be locked here, code below will not be executed until "lock.notify()" called
bundle.putString(name);


text:
Q: How to convert java.io.File to Scala Temporary File in Play 2.6.x I have this code on my project with play 2.5 in spec2 and it's worked fine.
Recently I updated play 2.6.9 and now it does not work anymore.
val file = new File(s"$home/the.upload.file4.$fileName")
val pw = new PrintWriter(file)
pw.write(fileContent)
pw.close
val tempFile = TemporaryFile(file)

I tried changing it to:
val file = new File(s"$home/the.upload.file4.$fileName")
val pw = new PrintWriter(file)
pw.write(fileContent)
pw.close
val tempFile = file.asInstanceOf[TemporaryFile]

It compiles but in runtime can't convert java.io.file to a temporary file. The error is:

[error]  java.lang.ClassCastException: java.io.File cannot be cast to play.api.libs.Files$TemporaryFile

A: You can replace
val tempFile = file.asInstanceOf[TemporaryFile]

with
val tempFile = SingletonTemporaryFileCreator.create(file.toPath)

and so you can use TemporaryFileCreator too,
for more info and another use you can see this
Interface Files.TemporaryFile

A: Looks like you have to use TemporaryFileCreator now to create it: https://www.playframework.com/documentation/2.6.9/api/java/play/libs/Files.TemporaryFile.html


text:
Q: R - plot existent levels, not all of them I'm having trouble on figuring how to plot my data. I've 2 variables, say x and y, where y is numeric, and x is composed of labels.
Imagine that x is
["F1", "F2", "F2", "F2"]

But the available labels are
["F1", "F2", "F3", "F4"]

Then, when I run:
plot(x, y)

The figure is composed of 4 x values (F1, F2, F3 and F4), and it shows 1 point on y for F1, and 3 points on y for F2.
What I want is to show ONLY F1 and F2 in my plot.
Any ideas?

A: Simply delete the unused level by reapplying factor()
x <- factor(x=c("F1", "F2", "F2", "F2"), levels=c("F1", "F2", "F3", "F4"))
plot(x)

plot(factor(x))

or as suggested by gagolews (this solution seems more elegant)
plot(droplevels(x))


text:
Q: Assert Application Logging in Junit Tests We want to write tests that assert certain content being logged as a part of an Application Startup. How should we do it ?

A: The basic approach I would try would be to:

*

*Create a custom logging appender for your logging framework that confirmed the content you were expecting.

*Ensure your JUnit test runs with that appender, perhaps by it being a part of your test logging configuration, or maybe by dynamically adding it when the test starts.

*Have that JUnit test run your application startup.

*At the end of the JUnit test, check some property on the appender to ensure that it logged what you were expecting, and fail the test if it didn't.

I don't think there's a whole lot of built-in functionality to help you, so you may have to write a bit of this infrastructure yourself unless you can find somebody's library to help. If you're logging logback with slf4j, I wrote some code that makes a custom appender to fail a test if an error is logged for a similar question. You might be able to use it as a starting point for how to dynamically include an appender when running a specific JUnit test. There are also some examples for java.util.Logging and log4j in "How to do a JUnit assert on a message in a logger".
In general, logging statements aren't "core" functionality and are just there to help understand a process, so there's usually not a lot of need to unit test them. You may be better off just testing the results of the application startup are what you're expecting, and not testing separately that it also logs something during the process. Presumably if it starts correctly, it also will run whatever logging is in there. I personally haven't needed to get more sophisticated than just checking that no errors were logged as in that linked answer, but perhaps you have more complicated requirements.


text:
Q: Install programm on computer I have jar file.
Also I have batch file, which contains:

start javaw -jar Name.jar

I want make .exe-file, which copy jar-file in choosen folder and add batch-file to autorun.
How I may make it?

A: You need corresponding tool called like "installer creator".
Some of the most popular are InstallForge - http://installforge.net/ and NSIS - http://nsis.sourceforge.net/.
Second one looks more complex, but can provide anything you only need.


text:
Q: Why do we need to pass an address value to an argument that accepts double pointers? #include <stdlib.h>
int malloc2(int **a) {
  *a = malloc(sizeof (int));
return 0;

}
int main() {
  int* b = NULL;
  malloc2(&b);
}

If an argument only accepts double pointers, how can it accept an address value?

A: If not to pass the pointer b by reference through a pointer to it then the function will deal with a copy of the value of the pointer
Changing the copy within the function will not influence on the original pointer.
As a result there the function produce a memory leak.
To change the original pointer b the function needs a direct access to the pointer. It can be achieved by dereferencing the pointer that points to the pointer (object) b.
Compare these two demonstrative programs.
#include <stdio.h>

void f( int *p )
{
    ++p;
    printf( "Within the function f p = %p\n", ( void * )p );
}

int main(void)
{
    int x = 10;
    int *p = &x;

    printf( "Before calling f p = %p\n", ( void * )p );

    f( p );

    printf( "After  calling f p = %p\n", ( void * )p );

    return 0;
}

The program output is
Before calling f p = 0x7ffc3a940cbc
Within the function f p = 0x7ffc3a940cc0
After  calling f p = 0x7ffc3a940cbc

as you can see the pointer p declared in main was not changed after calling the function f.
And another program
#include <stdio.h>

void f( int **p )
{
    ++*p;
    printf( "Within the function f p = %p\n", ( void * )p );
}

int main(void)
{
    int x = 10;
    int *p = &x;

    printf( "Before calling f p = %p\n", ( void * )p );

    f( &p );

    printf( "After  calling f p = %p\n", ( void * )p );

    return 0;
}

The program output is
Before calling f p = 0x7ffe011131ec
Within the function f p = 0x7ffe011131f0
After  calling f p = 0x7ffe011131f0

Now you can see that the pointer p declared in main was changed after calling the function f because it was passed to the function by reference through a pointer to it. Dereferencing the pointer to pointer the function gets the direct access to the pointer p declared in main.

If an argument only accepts double pointers, how can it accept an
address value

Each value is interpreted according to its type.  The value of this expression &b has the type int **. And the function parameter also has the type int **.
You may imagine the function definition and its call the following way
int main() {
  int* b = NULL;
  malloc2(&b);
}
//...
int malloc2( /* int **a */ ) {
  int **a = &b;
  *a = malloc(sizeof (int));
return 0;
}

That is the function parameter a is initialized by the value of the expression &b.
Or a more simple example
int main( void )
{
    int x = 10;
    int *b = &x;
    int **a = &b;
}

A: The function accepts a single int ** argument, i.e. a pointer-to-pointer-to-int.
The variable b in main has type int *, i.e. pointer-to-int.  If you then take the address of b, you now have a pointer-to-pointer-to-int, i.e. int ** which matches the function's argument.


text:
Q: C++ API availability for Cronet Are native bindings to Cronet available? Are there any C++ API available?That would be useful when having a C++ library shared between Android and iOS.

A: No, there are no C++ Cronet API available at the moment.


text:
Q: How to get ipset timeout programmatically? I am trying to get the timeout value of an ipset programmatically (not using the userspace ipset tool).
The following example tries to get the timeout from set named "my_set" which had been created with this command:
ipset create my_set hash:ip timeout 86400
Here's the example code where I tried a few different ways to access the timeout data field:
#include "stdlib.h"
#include <libipset/types.h>
#include <libipset/session.h>
int main(int argc, char* argv[]) {
  ipset_load_types();

  struct ipset_session *session;
  session = ipset_session_init(NULL, NULL);
  ipset_session_data_set(session, IPSET_SETNAME, "my_set");

  /* Validate set exist */
  if (ipset_type_get(session, IPSET_CMD_TEST) == NULL) {
    printf("Error: Can't find set\n");
    exit(1);
  }

  if ((const uint32_t*)ipset_session_data_get(session, IPSET_OPT_TIMEOUT) == NULL)
    printf("Timeout field is NULL\n");

  const struct ipset_data* data = ipset_session_data(session);

  if (!ipset_data_flags_test(data, IPSET_FLAG(IPSET_OPT_TIMEOUT)))
    printf("Timeout field is not present\n");

  if (!ipset_data_test(data, IPSET_OPT_TIMEOUT))
    printf("Timeout field is not present\n");

  if ((const uint32_t*)ipset_session_data_get(session, IPSET_OPT_TIMEOUT) == NULL)
    printf("Timeout field is NULL\n");
}

Compile with:
gcc -lipset test.c
Output is:
Timeout field is NULL
Timeout field is not present
Timeout field is not present
Timeout field is NULL

I think the timeout is not being provided by the kernel, but I don't know how to use the ipset API to ask the kernel for that information. I can't find any API documentation and I'm trying to use examples from the ipset source I found here or here
The API here is not useful for this task.

A: From what I can see, libipset has some quite silly interface. There is no decent way to obtain the properties of a given set through the library, and the associated command line tool (ipset(8)) also does not offer a simple way to query them. However, they are available when issuing a "list" command.
It seems that the information you want is only queried on-the-fly by the library when needed and then deleted, leaving no trace. This means that even after executing something like ipset_cmd(session, IPSET_CMD_LIST, 0), checking with ipset_session_data_get(session, IPSET_OPT_TIMEOUT) will yield absolutely nothing! Pretty funny.
The "proper" way to obtain this information would be to use a raw netlink socket and exchange the appropriate messages directly with the ipset netlink subsystem (NFNL_SUBSYS_IPSET), which is what libipset does under the hood, but that's quite the predicament...
However, since the library allows you to create a "session" registering a callback function to call for printing information, you can [ab]use this to get what you want.
Here's a working example:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <libipset/types.h>
#include <libipset/session.h>

struct info {
    uint32_t timeout;
    bool ok;
};

/* Callback print function executed by libipset when information is available.
 * Extract whatever information is needed and store it through the private data
 * pointer.
 */
static int dummy_print_fn(struct ipset_session *session, void *data, const char *_fmt, ...) {
    struct info *out = data;

    const uint32_t *ptr = ipset_session_data_get(session, IPSET_OPT_TIMEOUT);
    if (ptr != NULL) {
        out->timeout = *ptr;
        out->ok = true;
    } else {
        out->ok = false;
    }

    return 0;
}

int main(int argc, char* argv[]) {
    ipset_load_types();
    struct ipset_session *session;

    /* Passed as private data pointer to dummy_print_fn. */
    struct info info;

    /* Register dummy print callback and &info as private data ptr. */
    if ((session = ipset_session_init(dummy_print_fn, &info)) == NULL) {
        printf("Error: Can't initialize session\n");
        exit(1);
    }

    if (ipset_session_data_set(session, IPSET_SETNAME, "my_set") != 0) {
        printf("Error: Can't give set name\n");
        exit(1);
    }

    /* Validate set exists */
    if (ipset_type_get(session, IPSET_CMD_TEST) == NULL) {
        printf("Error: Can't find set\n");
        exit(1);
    }

    /* Execute a list command to get the information you want through the
     * registered callback function.
     */
    if (ipset_cmd(session, IPSET_CMD_LIST, 0) != 0) {
        printf("Error: list command failed\n");
        exit(1);
    }

    if (info.ok)
        printf("Timeout: %u\n", info.timeout);
    else
        printf("Timeout: field unavailable\n");

    return 0;
}


text:
Q: Outer JOIN 2 Tables using a third table to filter I am creating a view with two very large data sets numbering the millions of rows. I have joining the two tables together using a full outer join and group by some of the columns.
I have a field id column common to both tables that I need users to be able to filter the view on. Originally, I was using TableA.F_ID = TableB.F_ID in the outer join syntax and that performed very well. However, if there were F_ID rows in TableB that were not in TableA they would not be displayed unless I used
where TableA.F_ID = <VALUE> or TableB.ID = <VALUE>

To get around having to use the or clause I used the fable that F_ID comes from in the query via an inner join to filter the data. This method does work but it has to execute the select on TABLEA and TABLEB before filtering out the rows and the query is taking 10+ minutes to return.
Based on the query below is there a way to optimize this to get a quicker end result?
select fm.F_ID
       ,fad.A
       ,fad.B
       ,fad.C
       ,fac.A
       ,fac.B
       ,fac.C
       ,fab.SUM as FAB_SUM
       ,fac.SUM as FAC_SUM
from V_FAB_COMBINED_GROUPS fad
FULL OUTER JOIN V_LTB_ALL_GROUPED fac on
    fab.F_ID = fac.F_ID
    and fac.A = fab.A
    and fac.B = fab.B
    and fac.C = fab.C
inner join fm on (fm.F_ID = fab.F_ID or fm.F_ID = fac.F_ID)
where fm.F_ID = 1

A: Try this and see if it improves performance:
select cte.*
from (select fm.F_ID fm_id
       ,fac.F_ID fac_id
       ,fad.A
       ,fad.B
       ,fad.C
       ,fac.A
       ,fac.B
       ,fac.C
       ,fab.SUM as FAB_SUM
       ,fac.SUM as FAC_SUM
from V_FAB_COMBINED_GROUPS fab
FULL OUTER JOIN V_LTB_ALL_GROUPED fac
    on fab.F_ID = fac.F_ID
    and fac.A = fab.A
    and fac.B = fab.B
    and fac.C = fab.C) cte
 join fm on (fm.F_ID = cte.fm_id or fm.F_ID = cte.fac_id)
where fm.F_ID = 1


text:
Q: How to deserialize an object with an object as it's value I am in a pickle. I can not find how to deserialize this json. Everything i've found online talks about how to handle a key/value where the value is a type not an object. In this case the value is an object that has additional key/values inside.
Additionally, the long guid like string that you see there after "territories", is never the same...
How do i deserialize this with JSON.NET? I would love to be able to get the ID and the Name.
Thank you for reading this
{
  "territories":{
    "6368e494-c47c-4678-89de-45f3bfc35247":{
      "id":"6368e494-c47c-4678-89de-45f3bfc35247",
      "name":"Atlanta Camera Operations",
      "center":[
        33748995,
        -84387983
      ],
      "timeZoneCode":"America/New_York",
      "languageCode":"en"
    },
    "4d998d4c-fcc6-4fdc-9e73-3f2e7515ee47":{
      "id":"4d998d4c-fcc6-4fdc-9e73-3f2e7515ee47",
      "name":"Atlanta Operations",
      "center":[
        33748995,
        -84387983
      ],
      "timeZoneCode":"America/New_York",
      "languageCode":"en"
    }
  }
}

A: Here's a class that will hold the territory info:
class Territory
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("center")]
    public IList<int> Center { get; set; }

    [JsonProperty("timeZoneCode")]
    public string TimeZoneCode { get; set; }

    [JsonProperty("languageCode")]
    public string LanguageCode { get; set; }
}

Then you can deserialize them one by one like this:
string myJsonText = "your json here";

var jsonObject = JObject.Parse(myJsonText);
var territoriesToken = jsonObject["territories"];

We loop through the children and deserialize them:
var territoriesList = new List<Territory>();
foreach (var child in territoriesToken.Children())
{
    var territory = child.First.ToObject<Territory>();
    territoriesList.Add(territory);
}

Or if you prefer LINQ one liners you can use this:
var territoriesList = territoriesToken.Children()
                      .Select(child => child.First.ToObject<Territory>())
                      .ToList();

You can then access the name and id like you would with any other C# object
territoriesList[0].Id
territoriesList[0].Name

A: your json data structure is invalid it should be like that :
{
"territories":
[
    {
        "id": "6368e494-c47c-4678-89de-45f3bfc35247",
        "name": "Atlanta Camera Operations",
        "center": [
            33748995, -84387983
        ],
        "timeZoneCode": "America/New_York",
        "languageCode": "en"
       }
       ,
       {
        "id": "4d998d4c-fcc6-4fdc-9e73-3f2e7515ee47",
        "name": "Atlanta Operations",
        "center": [
            33748995, -84387983
        ],
        "timeZoneCode": "America/New_York",
        "languageCode": "en"
    }
]

}

wich you can map to Territory class, meaning :
    public class Territory
{
    public GUID id { get; set; }
    public string name { get; set; }
    public List<int> center { get; set; }
    public string timeZoneCode { get; set; }
    public string languageCode { get; set; }
}

and deserialize using :
JsonConvert.DeserializeObject<List<Territory>>(your_json)


text:
Q: Javascript sorts object values Hope you have been a good day. I want to ask you a question. Here is it:
So I have an object and I get values from it with Underscore.js (I will give you an example without using underscore.js to getting values).
After I get values, it puts numbers that are bigger than 0. I think it sorts bigger than smaller.

I want values exactly how they are at the object before I take them.

Here is an image for you

Here is the code
tmpReport.forEach(element => {
            const tmpVal = [];
            console.log("element: ", element);
            tmpValList.push(_.values(element));
            console.log('tmpValList: ', tmpValList);
        });

Here is the code without using underscore.js:
tmpReport.forEach(element => {
            const tmpVal = [];
            console.log("element: ", element);
            Object.entries(element).forEach(([key, value]) => {
                tmpVal.push(value);
            });
            tmpValList.push(tmpVal);
            console.log('tmpValList: ', tmpValList);
        });

So any help will be appreciated. Thank you!

A: In JavaScript, the order of object entries is not guaranteed.
If you want to put specific entries at specific indices in your array you have to do that manually.
For example:
tmpVal[0] = element['Cell damage by placing'];
...
tmpVal[4] = element['time'];
tmpVal[5] = element['toplan'];

You can only achieve that if you are aware of your object keys. As far as I know there is now generic way to keep the initial order as there is no order to begin with.
The best you can do in that case is use a lexicographic order and sort your keys accordingly.


text:
Q: WPF Databinding between two usercontrols I'll try to give a bit more details of this question
In a WPF application, on the left side of 'mainwindow' I have a UserControl containing a listBox, like this
<UserControl.Resources>
    <ObjectDataProvider x:Key="viewModel" ObjectType="{x:Type vm:TemplateListViewModel}"/>
</UserControl.Resources>
<StackPanel>
    <ListBox Height="Auto" Name="TemplateList"  ItemsSource="{Binding Source={StaticResource viewModel}, Path=TemplateNames}"
</StackPanel>

As shown, listbox items are fetched from a xml file via viewModel.
Now I have another usercontrol2 containing a Label to echo the selection from "TemplateList".
Also under this label I have another usercontrol3 containing a datagrid, which data will be fetched from a xml file based on the label, or the selection from the listbox on the left side of the window through usercontrol3's viewmodel.
So the question is how to pass the "SelectedItem" or "SelectedIndex" to viewModel of the Label and datagrid?
I know it works when I bind a label to a listbox with 'elementName' and Path to 'SelectedItem'. Now I couldn't figure out how to do with usercontrols and 'ObjectDataProvider'. I tried as suggested below couldn't get it to work out. So far for usercontrol2, if I use the same ObjectDataProvider as the above, I can get this label to work as
<Label Name="TemplateNameLabel" Content="{Binding Source={StaticResource viewModel}, Path=TemplateNames[0]}" />

Where 'TemplateNames' if of type 'XmlNodeList' because it was read from xml file. But I really want is something like
<Label Name="TemplateNameLabel" Content="{Binding Source={StaticResource viewModel}, Path=TemplateNames[SelectedIndex]}" />

Can this be done without any command, just like binding to 'elementname' without usercontrol involved?
Thanks.

A: I've removed not important properties to highlight the main:
 <ListBox Name="TemplateList" ItemsSource="{Binding Source={StaticResource viewModel}, Path=TemplateNames}" SelectedItem="{Binding Path=SelectedTemplate, Mode=OneWayToSource}" />

Note, that you will need SelectedTemplate property with public setter of type TemplateName - the same type that is used for single element in the TemplateNames collection in the ViewModel. In that setter you could pass the value to whatever other view-models you need.


text:
Q: How can I upgrade from Windows Server 2008 R2 Standard to Enterprise Edition? Our IT guy mistakenly set up Windows 2008 R2 Standard Edition instead of Enterprise Edition. The machine has 64GB of RAM, and Standard only supports 32GB, so half of it is unusable.
Is there a way to upgrade to Enterprise Edition without a complete re-install? He has already generated some CSRs for SSL certs and done other work we'd hate to waste. (The cost of the license isn't an issue, just mechanically how to best perform the upgrade.)

A: Windows Server 2008 R2 includes a command-line tool called the Deployment Image Servicing and Management tool, or DISM. It's functionally equivalent to the Windows Anytime Upgrade feature in client versions of Windows. You can run it from an elevated command prompt.
To determine the currently installed edition:
DISM /online /Get-CurrentEdition

To determine the editions you can upgrade to:
DISM /online /Get-TargetEditions

To actually perform an upgrade:
DISM /online /Set-Edition:<edition ID> /ProductKey:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX

Source (with more information): http://blogs.technet.com/b/server_core/archive/2009/10/14/upgrading-windows-server-2008-r2-without-media.aspx


text:
Q: Exit While loop from String input So I am writing a user menu using a simple while loop and case breaking but having an issue. I need to use chars instead of ints for my cases (really using a string Scanner for simplicity) and for the most part it works. But when I enter D (my exit case) the loop does not break. Not sure why, I have done this with ints many times without an issue...
import java.util.Scanner;

public class Postfix_Notation {
 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  String choice = "Z";

  while (choice != "D") {
   System.out.println("Enter A, B  or C to perform an operation or enter D to exit.");
   System.out.println("A- Evaluate a user input postfix expressions");
   System.out.println("B- Convert, display infix expressions to postfix expressions then evaluate and display the result of thepostfix expression");
   System.out.println("C- Reads words from a the text file (hangman.txt) in a LinkedList and use an iterator on it to displays all the words (duplicates allowed) in descending alphabetical order");
   System.out.println("D- Exit");
   choice = new Scanner(System.in).next();

   switch (choice) {
    case "A":
     System.out.println("Enter a string: ");
     String s = new Scanner(System.in).next();
     System.out.println("All possible permutations of " + s + " are: ");
     System.out.println("\n");
     break;

    case "B":
     Scanner input2 = new Scanner(System.in);

     System.out.println("Enter a hex string: ");
     String hexString = input2.next();

     System.out.println("The decimal equivalent of " + hexString + " is " + (hexString));
     System.out.println("\n");
     break;

    case "C":
     Scanner input = new Scanner(System.in);

     System.out.println("Enter a binary string: ");
     String binaryString = input.next();

     System.out.println("The decimal equivalent of " + binaryString + " is " + (binaryString));
     System.out.println("\n");
     break;

    case "D":

     System.out.println("Program Ended");

     break;

    default:
     System.out.println("Invalid Input");
   }
  }
 }
}

A: So while(!choice.equals("D")) do the job. Check this link: How do I compare strings in Java?. You compared references instead of values.


text:
Q: Minimum pumping length for a regular language How to calculate minimum pumping length of a regular language. For example if i have 0001* then minimum pumping length for this should be 4 ,that is 000 could not be pumped . Why it is so?

A: It will be less than or equal to the number of states in a minimal DFA for the language, minus one. So convert the regular expression into a DFA, minimize it, and count the states. For your example:
0001*

SOURCE    SYMBOL    DESTINATION
q1        0         q2
q1        1         q5
q2        0         q3
q2        1         q5
q3        0         q4
q3        1         q5
q4        0         q5
q4        1         q4
q5        0         q5
q5        1         q5

Why is it equal to this? Because that's the maximum number of transitions you can take in the DFA without visiting some state twice. Once you visit a state twice, you have looped.
Of course, it's possible for a language's minimal DFA to lack a path of that length. In that case, you can find the longest path (from the start state) that doesn't visit a state twice by using something like depth-first search of the automaton's graph and seeing how long a path you can trace. That would be your real answer.


text:
Q: Shadow cljs doesn't see java on Macbook M1 I used npx create-cljs-project my-app and revived error when I tried to start with npm start
I have tried few java ask version, but I get same error anyway.
shadow-cljs - config: /Users/tomaszsikora/dev/my-app/shadow-cljs.edn
Execution error (UnsatisfiedLinkError) at java.lang.ClassLoader/loadLibrary (ClassLoader.java:2398).
Can't load library: /var/folders/x7/k_6f989d60z2k0pz_cz_3y_40000gn/T/jna1171015707293329039.tmp
Full report at:
/var/folders/x7/k_6f989d60z2k0pz_cz_3y_40000gn/T/clojure-11795200488797552517.edn

and it starts like this, but it's too long to paste here.
{:clojure.main/message
 "Execution error (UnsatisfiedLinkError) at java.lang.ClassLoader/loadLibrary (ClassLoader.java:2398).\nCan't load library: /var/folders/x7/k_6f989d60z2k0pz_cz_3y_40000gn/T/jna14133068692257536681.tmp\n",
 :clojure.main/triage
 {:clojure.error/class java.lang.UnsatisfiedLinkError,
  :clojure.error/line 2398,
  :clojure.error/cause
  "Can't load library: /var/folders/x7/k_6f989d60z2k0pz_cz_3y_40000gn/T/jna14133068692257536681.tmp",
  :clojure.error/symbol java.lang.ClassLoader/loadLibrary,
  :clojure.error/source "ClassLoader.java",
  :clojure.error/phase :execution},
 :clojure.main/trace
 {:via
  [{:type java.lang.UnsatisfiedLinkError,
    :message
    "Can't load library: /var/folders/x7/k_6f989d60z2k0pz_cz_3y_40000gn/T/jna14133068692257536681.tmp",
    :at [java.lang.ClassLoader loadLibrary "ClassLoader.java" 2398]}],
  :trace

java version
tomaszsikora@DeadBook-Void my-app % java --version
openjdk 18.0.2.1 2022-08-18
OpenJDK Runtime Environment Homebrew (build 18.0.2.1+0)
OpenJDK 64-Bit Server VM Homebrew (build 18.0.2.1+0, mixed mode, sharing)


text:
Q: Image not loading after moving art.scnassets folder After creating a new "Augment Reality App" project in Xcode, I want to move art.scnassets folder from its default location to /Resources/ folder that I created. So the folder path would be like Resources/art.scnassets. However, it fails to load a png file in it if I move the folder. See below:
Before (working):
// art.scnassets folder is in its default place
// below code loads image.png
print(UIImage(named: "art.scnassets/image.png")!)

After (not working):
// moved folder to "Resources/art.scnassets"
// Resources folder is a group.
// below returns `nil`
print(UIImage(named: "Resources/art.scnassets/image.png")!)

I cleaned up the builds, and checked Copy Bundle Resources menu as well, but there is nothing wrong. If I move art.scnassets folder back to the project root, it works, meaning code works fine.
What should I do to move art.scnassets to somewhere else? I am new to Swift.

A: Have you tried using the first code?
print(UIImage(named: "art.scnassets/image.png")!)

As far as I know it doesn't matter in which folder the scnassets are, you can refer to it the same way.


text:
Q: How to ignore data annotation validation in asp.net MVC Is there any way to ignore data annotation validation in asp.net validation?
Look at the following case:
I have this metadata class for a message entity
public class MessageMetaData
{
    [Required(ErrorMessage="This field is required")]
    public int[] To { get; set; }

    [Required(ErrorMessage = "This field is required")]
    public string Title { get; set; }

    [Required(ErrorMessage = "This field is required")]
    public string Body { get; set; }
}

and this is my message class:
public partial class message
{
    public message()
    {
        this.FilesRelatedToTheMessage = new HashSet<file>();
        this.Receivers = new HashSet<MessageReceiversConnector>();
    }

    public int id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public Nullable<int> C_From { get; set; }
    public Nullable<int> AreaId { get; set; }
    public Nullable<int> Project { get; set; }
    public string Status { get; set; }
    public System.DateTime DateOfCreation { get; set; }

    public virtual ICollection<file> FilesRelatedToTheMessage { get; set; }
    public virtual EventsArea EventsArea { get; set; }
    public virtual project ProjectTheMessageRelatedTo { get; set; }
    public virtual ICollection<MessageReceiversConnector> Receivers { get; set; }
    public virtual user Sender { get; set; }
}

[MetadataType(typeof(MessageMetaData))]
public partial class message
{
    public int[] To { get; set; }
    public int[] Areas { get; set; }
    private MessageDTO mdto = new MessageDTO();
    public MessageDTO MDTO { get { return this.mdto; } set { this.mdto = value; } }
}

When I want to store a message as a draft message, one of the properties might not be sent. Is there any way to handle this issue?
Edit:
this is my DraftMessage action
    public string DraftMessage(message draftMessage, string status)
    {
        if (status == "new")
        {
            draftMessage.Status = "DR";
            draftMessage.DateOfCreation = DateTime.UtcNow;
            draftMessage.C_From = CurrentUser.Id;
            context.messages.Add(draftMessage);
            foreach (int receiverId in draftMessage.To)
            {
                if (context.users.Any(user => user.user_id == receiverId && (user.DepartmentOfTheUser.Company == CurrentUser.Company || user.DepartmentOfTheUser.CompanyOfTheDepartment.CompanyCustomers.Any(cus => cus.customer_of == CurrentUser.Company) || user.DepartmentOfTheUser.CompanyOfTheDepartment.CompanySuppliers.Any(supp => supp.supplier_of == CurrentUser.Company))))
                {
                    context.MessageReceiversConnectors.Add(new MessageReceiversConnector() { MessageId = draftMessage.id, ReceiverId = receiverId, MessageStatus = "DR" });
                }
            }
        }

        context.SaveChanges();

        return "draft";
    }

here it throws message on  context.SaveChanges(); because of validation, the fields in the database are all nullable but it throws exception due to metadata class.

A: Maybe it is worth to make two ViewModels. One for Draft message and another for message you want to send.


text:
Q: Redirect from Rails controller after Angular POST I have a normal Rails app (no SPA) and on one page only I'm using Angular.
At the end I'm sending a POST to the server with the form data (and it is working) and as the final step of the POST I'd like to redirect to another page.
Rails controller is like this:
def save
  data = params[:data]
  respond_to do |format|
    format.js { render :js => "window.location.href = '/products';" }
  end
end

But nothing is happening.
My Angular post is simple:
app.service('httpService', ['$http', function($http) {
  this.post = function(data) {
    $http({
      method  : 'POST',
      url     : '/cart/save',
      data    : { data: data },
      headers : {'Content-Type': 'application/json'}
    });
  };
}]);

Calling service just like this, no promises:
this.save = function(ids) {
  httpService.post(ids);
};

Any ideas? Thanks.
EDIT:
I have tried also change the mime-type to 'application/javascript', but no success:
app.service('httpService', ['$http', function($http) {
  this.post = function(data) {
    $http({
      method  : 'POST',
      url     : '/cart/save',
      data    : { data: data },
      headers : {'Content-Type': 'application/javascript'}
    });
  };
}]);

A: Ok, so the problem was that the $http is sending an asynchronous request, thus the page cannot be redirected.
The solution was to send jQuery synchronous $.ajax(..., async: false);.


text:
Q: Shape of pseudosphere beyond cusp including frills So far we have shape of pseudosphere defined below/upto its cuspidal boundary/edge. However,
FullPseudosphereModelBeltrami has detail around (what appears to me) material added outside cusp radius that appears with small amplitude frills.
 Daina Taimina's Crochet Art  gives detail of its hyperbolic geometry (adding more circumferential thread material over the radial) e.g., at 15 min 19 sec of video as large amplitude frills.
EDIT 1:
As per Hilbert's theorem (if stated in other words) when a smooth patch constant $K<0$ is sufficiently extended it should encounter a cuspidal boundary.
We see no cuspidal boundaries somewhere among the crocheted frills. Is $K$ constant? Can  a parameterization be suggested for (what looks to me like a neat inner $K<0$ area of a toroid) surface she is demonstrating at 11 min 05 secs?
Nash embedding theorem states that every Riemannian manifold can be isometrically embedded into  Euclidean space of sufficiently large dimension. Is embedding into $\mathbb E^3$ at all possible with such frills?
Is there yet no parametrization or differential equation describing full frilled/convoluted shape of a pseudosphere?
Or is this shape nearer to the Catalan's minimal surface?

A: I will try to explain why the  tractricoid has a cusp (and why there sometimes are  frills  beyond the cusp )
The tractricoid is the "real" name of what many people call the pseudosphere
The tractricoid is the best known but not the only pseudo-spherical surface, In the earlier post I think I even show that it  was not the first known one)
The tractricoid is the revolution surface of a tractrix (good to know but not used in the proof)
I thought it was easy but while trying to write a good and simple explanation I realised it was more complex than I expected. but i think a good simple explanation is a good thing to have
In this proof I maybe sometimes state the obvious this is to make the proof better to understand.
I hope it is not to annoying.
the whole proof might as well done a bit easier by just looking at a tractrix instead of an tractricoid, (replacing radius of h-circle with distance of the x-axis)
I did choose not to do so, to keep the idea of a tractricoid intact and to remove the attention of coordinates (I would like a proof that did not mention coordinates at all, I did get quite close, I think  :)
Lets go into the maths:
Suppose we have a tractricoid where the axis of rotation/ revolution / symmetry  is the x axis.
Define an h-circle as the circle that is the  intersection of the on the plane perpendicular to the x axis and the tractricoid.
suppose $S_1 (x_1, y_1 , 0) $ is a point on the tractricoid.
The radius of the  h-circle  through $ S_1 $ is $ y_1 $
and  the circumference of the  h-circle  through $ S_1 = 2 \pi y_1 $
Some fixed distance $ds$ from $S_1$ we have the point $ S_2 = (x_2, y_2 , 0) $
With distance here I mean the length of the arc that is the intersection between the tractricoid and the $ y >0, z=0 $ half plane, measuring the distance this way is very importand and we will come back to this later.
The circumference of the  h-circle  through $S_2 = 2 \pi y_1 $ times some (small) factor $ a  > 1 $
A distance $ds$ from $S_2$ we have the point $S_3 = (x_3, y_3 , 0) $
The circumference of the  h-circle  through $S_3 = 2 \pi y_3 =  2 \pi y_2 a = 2 \pi y_1 a^2$
and $ y_3 =  a y_2  = a^2 y_1 $
This can be generalised  to $ y_n =  a y_{n-1} $
(Now stating some obvious facts)
When $ i < j < k $  then $S_j$ is between $S_i$ and $S_k$
if $ i < j$ then the circomference of the  h-circle  through $S_i$  is smaller than the circumference of the  h-circle  through $S_j$
(End of obvious facts)
The difference between $y_n $ and $y_{n-1}$ is $ (a-1) y_{n-1}$
At some point  $S_c$ , the difference between $y_c $ and $y_{c-1} $ is  $ (a-1) y_{c-1}$ is $ ds$
(or to be more exact the difference is between $ \frac{ds}{a}$ (?) and $ ds$ )
The circumference of the  h-circle  through $S_c$ is $ 2 \pi y_c $
A step further at $S_{c+1}$ the circumference of the  h-circle  is $ 2 \pi y_c $ times $a$.
and the radius at  $S_{c+1}$ is $ a y_{c}$
Now an impossible situatie occurs that
The difference between the radius at $S_{c+1}$  and $S_{c}$  is  $(a-1) y_c $
And $(a-1  ) y_c  > (a-1 ) y_{c-1} = ds $ so the necessary radius of the circle at $S_{c+1}$ is bigger than the radius at  $S_{c} + ds $ and therefore this circle cannot be constructed.
(the maximum circle that can be made after $ S_c $ is one with radius $y_c + ds$)
This is why there is a cusp
But then what "beyond the cusp"?
the circle is the shortest curve to surround a given area, and a way out of this is to change curve and opt for a longer curve than a circle to surround a given area, and this is your circle with frills, or cusps ,
Or as the tractricoid does: stop at the cusp.
Hope this helps


text:
Q: 301 redirect folder root I'm struggling with a fairly simple 301 redirect.
I have several redirects for pages which all work fine - eg
Redirect 301 /folder/mypage1.html https://www.example.com/folder/mypage2.html.
However now I want to redirect from a folder root to another page, I don't however want any of the other pages in the folder to redirect.
So /myfolder/ should redirect to https://www.example.com/mypage.html but /myfolder/mypage.html should not redirect.
I've tried:
Redirect 301 /myfolder/ https://www.example.com/mypage.html but this doesn't work.
I apologize for the newbie question that probably has a very simple answer.

A: With your shown samples, please try following htaccess rules file. This uses apache's THE_REQUESTvariable to perform rewrite.
Please make sure to clear your browser cache before testing your URLs.
RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s/myfolder/\s [NC]
RewriteRule ^  mypage.html [L]

A: Use RedirectMatch, which matches using a regex, rather than simple prefix-matching (as with Redirect) to redirect requests for the folder only.
For example:
RedirectMatch 301 ^/myfolder/$ https://www.example.com/mypage.html

Both Redirect and RedirectMatch belong to the same Apache module: mod_alias
You will need to clear your browser cache if you have been experimenting with 301 (permanent) redirects. Test first with 302 (temporary) redirects to avoid potential caching issues.


text:
Q: Integral Inequality for symmetric function Let $f$ be a continuous function from $[0,1] \rightarrow \mathbb{R}$.  I want to prove the following result, but I can't even start really.
$$I \equiv \int_0^1 \int_0^1 x \wedge yf(x)f(y)dxdy \ge 0 $$ with equality holding if and only if $f(x) = 0 \quad \forall x \in [0,1]$.  I can obviously make the observation that $I = 2\int_{x \leq y} x f(x) f(y)dxdy$ but this is unhelpful.  Any hints/solutions would be massively appreciated, and I'm sorry to not really have any ideas so far on my own.  Thanks if you can help!

A: Let $h_x(t)=0$ for $t >x$ and $1$ for $t \leq x$. Then $\int_0^{1} h_x(t)h_y(t)dt=x\wedge y$. So (by interchanging the order of integration) we can write $$I=\int_0^{1}\int_0^{1}\int_0^{1} h_x(t)h_y(t)dtf(x)f(y)dxdy$$ $$= \int_0^{1}(\int_0^{1}\int_0^{1} h_x(t)h_y(t)f(x)f(y)dxdy) dt$$ $$=\int_0^{1}(\int_0^{1} h_x(t)f(x)dx)^{2}dt \geq 0.$$ Equality holds only when  $\int_0^{1} h_x(t)f(x)dx=0$ for all $t$ which means $\int_t^{1}f(x)dx=0$ for all $t$. This implies $f(x)=0$ for al $x$.


text:
Q: What compiler flags are libstdc++ compiled with? I'm specifically using mingw-builds 6.2, but the answer could apply to any compiler.
When linking against the libstdc++.dll that comes with my compiler, what flags are typically used to compile it? Would I see some performance increase if I were to build it myself with -O3?


text:
Q: Adding an exception for a letter In my program it searches a text file, in this case a list of every word in a dictionary, and adds a number to the count of vowels if aeiou are found in it. I need to add an exception for counting y, it needs to only be counted if none of the other vowels are found in the word. I am fairly new to the concept and wondering if I was going in the right direction. And help would be loved!
package TEST;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class test {

    public static void main(String[] args) throws FileNotFoundException, IOException{
        int count= 0;

        FileReader FR = new FileReader("Words.txt");
        BufferedReader BR = new BufferedReader(FR);

        String Vowels;
        while((Vowels= BR.readLine()) != null) {

                for (int i = 0; i < Vowels.length(); i++) {
                  char c = Vowels.charAt(i);

                if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u' ) {
                       count++;
                 // if (c=='y') {
                 //    count++;

                           }}}
              System.out.println("Total:"+ count);
                }}

A: To be sure that y is not contained in the word, you have to wait that all the letters of the words were read. So you should increment the number of y found  for the current word after the for loop if it is relevant, that is if any a-e-i-o-u letters were found.
The variables you will need :

*

*int countY to count the number of y found in the current word.

*boolean isOtherVoyelsThanYfound to flag if any a-e-i-o-u letters were found in the current word.

These should be reinit to 0 and false for each new word to analyse.
Here is the idea :
while{
...
  boolean isOtherVoyelsThanYfound = false;
  int countY = 0;

  for (int i = 0; i < Vowels.length(); i++) {
    char c = Vowels.charAt(i);

    if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u' ) {
         count++;
         isOtherVoyelsThanYfound = true;
    }
    else if (c == 'y'){
        countY++;
    }
  }

  if (!isOtherVoyelsThanYfound){
    count += countY;
  }
...
}

A: You can try this approach:
while((Vowels= BR.readLine()) != null) {
    boolean foundVowel = false;

    for (int i = 0; i < Vowels.length(); i++) {
        char c = Vowels.charAt(i);

        if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u') {
            count++;
            foundVowel = true;
        }
    }

    if (!foundVowel) {
        for (int i = 0; i < Vowels.length(); i++) {
            char c = Vowels.charAt(i);

            if (c=='y'||c=='e'||c=='i'||c=='o'||c=='u') {
                count++;
            }
        }
    }
}
System.out.println("Total:"+ count);

Here you scan all the word and when you don't find any vowel, you scan it again just searching ys.

A: Hey you can use another int to count every "y" and count them.
Then in the end you can check if count != 0 or else overwrite it with your yCount.
So your code should look something like this.
public static void main(String[] args) throws FileNotFoundException, IOException{
        int count= 0;
        int yCount = 0;

    FileReader FR = new FileReader("Words.txt");
    BufferedReader BR = new BufferedReader(FR);

    String Vowels;
    while((Vowels= BR.readLine()) != null)
    {

            for (int i = 0; i < Vowels.length(); i++)
            {
              char c = Vowels.charAt(i);

              if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
                   count++;

              if (c=='y')
                   yCount++;

             }

             if(count == 0)
             count = yCount;

          System.out.println("Total:"+ count);
  }

This way you dont have to scan the file twice when count == 0.


text:
Q: Normal convergence I have some problems to apply normal convergence of series of functions in any vector space.
In fact $(f_{n})$ is a sequence of differentiable functions defined from a topological space $X$ to a normed vector space $Y$, that is normally convergent,
I want to ask if the sequence of derivatives $(f_{n}')$ converges normally as well?

A: The formulation is a little unclear (should $X$ be a topological vector space?) but in any case the answer is going to be negative. There is never a reason for derivatives to converge, unless we restrict attention to functions that solve some nice elliptic equation and therefore satisfy interior regularity estimates.
A typical counterexample is the sequence $f_n(x)=\frac{1}{\sqrt{n}}\sin nx$ on the real line.


text:
Q: Correct way to define board outline? I'm a student and am almost ready to have a PCB I designed fabricated, but I'm confused about how the board outline should be defined.
Here's what I currently have:

I also have a 20mil keepout line centered on the board edge, but hid the layer to make the board outline visible.
I'm planning on ordering the board from a company called Gold Phoenix PCB. I've emailed them several times about this, but haven't been able to get a clear answer. They said:

You only need to design the board in the way you want, size tolerance +/-10mil

Not helpful!
Then after sending the above image:

Make things simple, you need keep everything 10mil from the edge of the board.

Ok, 10mil from the edge of the board, but what do they consider to be the edge? Is it the center of the 10mil track I placed on mechanical 1, or is it the edge of the track?
The example I gave them when asking how the outline should be defined is:

Let's say your router bit diameter is 90mils and it follows the center of the line defining the board outline -- that means it would be cutting 40mils too deep into the board, which would not only mess up the connector alignment but also create a risk of shorts since I only have a copper pullback of 20mils.

I've already emailed them four times about this and don't want to get on their bad side, so can anyone explain the correct way to define the board outline to meet my requirements?

A: The middle of the pink line is the board edge you are defining.  The width of that line is a CAD/visual construct and means nothing to the fabrication process.  The keep-out applies only to electrical (i.e., metal) portions of the design.  You can typically take silk all the way to the edge of the board.  Based on the polygon you have just above the "RAW" PTH, you likely are as close as you can get to the edge of the board with this connector (looks like a pin header).  If you want to have the yellow (black plastic of pin header) directly to the edge of the board, you will have to decrease your keep-out.
The keep-out is for your own protection so that when they cut the PCBs from the panel, and apply mechanical stresses to the edges of the board, they aren't inadvertently breaking any of the metallization causing random opens/shorts.

A: You can define the board shape either way you want.
If you tell the shop that you are providing a board outline, they will make the outer edge of the board follow the center of the line in your gerbers.
If you tell the shop that you are providing a route tool path, they will make the routing tool follow the center line, and the edge of the board will be offset from that by the radius of the cutting tool.
For a simple board, it's better to provide a board outline and let the fab shop generate the route tool path for the size of tool they want to use.
If you want to have inner corners, or only partially depanelize the boards or something, then you might want to provide a route tool path. In Altium, look for the "Generate Route Tool Path" command to generate the path easily.
In Altium, for a board outline, typically you just use the Keepout layer to define it. Of course if you want you can redefine one of the mechanical layers to be the board outline and use that instead. If you generate ODB++ output instead of gerbers, there will be board outline information in the ODB++ based on the actual defined board outline in Altium, not any paths on any particular layers.
Since different layout tools name their gerber files differently, I suspect that most shops just look through the gerbers for a layer that looks like it has a board outline and use that (but it's better if you give them a readme file that says what each gerber file represents)
In a comment you mentioned,

No, I don't have a "fab drawing." I'll try to figure out if this is possibly in Altium.

Typically for simple boards Altium users just use the Drill Drawing layer for the fab drawing. If for some reason you want to have separate fab drawings and drill drawings, then you can again just rename one of your mechanical layers to be the fab drawing.

A: I would say you should define the dimensions of your board in your fab drawing, you do have a fab drawing right :)   Showing your stackup, and board outline, and clearly labeled finished dimensions?  Maybe some notes about finishes, and hole tolerances?  That will take the ambiguity out of trying to communicate with them.
Also you shouldn't be worried about getting on your fab houses bad side, if they are tough to work with, or can't give you answers go somewhere better.   Of course at the same time it's a two way street so you want to be respectful when dealing with them.  Ideally your fab house is your partner, and part of their job has and will always be educating new engineers/customers ;)
Good luck.

A: It might depend on the board house.
I use a 100mil line as the outline of my board and treat it as the kerf of the router. That means if you want to align a component with the edge, align it with the inside edge of the outline.
If you still haven't got a satisfactory response from the board house, use a different one. There are hundreds of options. I suggest OSH Park.

A: You have the board outline defined with the dotted line, so you don't need an outline on the mechanical layer, and the Gerber files should come out with the correct board outline. You can check that the Gerbers are correct by viewing them with a Gerber viewer like GC-Prevue.


text:
Q: Why "Documents & Data" is consuming so much space in iPhone? Looking at the iTunes storage information associated to my iPhone 5S, it seems that Documents & Data occupies around 3.5 GB of space.

On the other hand, on the iPhone, Documents & Data stored on iCloud are around 300 MB (so much less).

Which value should I trust? Moreover, if iCloud just requires 300 MB to store documents and data, what is the meaning of the 3.5 GB data that appears on iTunes?

A: Well it is normal. You can refer to this: https://support.apple.com/en-us/HT201656
If storage amounts on an iOS device differ from what you see reported in iTunes

Since iTunes categorizes cached files as Other, reported usage for
  Music or Videos might differ. To view usage on your iOS device, go to
  Settings > General > Usage > Manage Storage.


text:
Q: Passing arguments to a function and calling it via "&" Is there any way to shorten these kinds of method calls:
aaa = Enum.find(Statuses, fn(x) -> x.name == :pending end)

to something like this:
aaa = Enum.find(Statuses, &==, [:name, :pending])

That is, to pass the arithmetic operator "==", structure field name name and value :pending as arguments.

A: You can use the partial application syntax for this:
aaa = Enum.find(Statuses, &(&1.name == :pending))

or
aaa = Enum.find(Statuses, & &1.name == :pending)

iex(1)> f = &(&1.name == :pending)
#Function<6.52032458/1 in :erl_eval.expr/5>
iex(2)> f.(%{name: :pending})
true
iex(3)> f.(%{name: :complete})
false

A: Also, the answer by Dogbert is perfect, as usual, I would put mine here too, for the sake of formatting.
This is a perfect example of when Elixir "prevents" you from doing things in a wrong way. If there is no such method on hand, it pretty much means the approach is wrong.
You are looking for a struct, that has a name having value :pending. Do that explicitly, with Kernel.match?/2 macro:
iex> [%{n: 1, name: :pending}, %{n: 2, name: :complete}]
     |> Enum.find(&match?(%{name: :pending}, &1))
%{n: 1, name: :pending}

Quote from the documentation:

match?/2 is very useful when filtering of finding a value in an enumerable:
list = [{:a, 1}, {:b, 2}, {:a, 3}]
Enum.filter list, &match?({:a, _}, &1)
#⇒ [{:a, 1}, {:a, 3}]


text:
Q: По аналогии с vector vec_1(50) не могу понять, как задать размер для vector> vec_2 Не смог придумать, как сделать вот что.
понятно, что vector<int> vec_1(50) - это вектор из 50 элементов.
А если я теперь хочу сделать вектор из 10 векторов, в каждом из которых по 50 элементов - как это синтаксически оформить?
Простые попытки написать что то типа
    vector<vector<int>> vec_2(10,50);

или
    vector<vector<int>> vec_2(10)(50);

-не прокатывают...

A: Прошу прощения за беспокойство и простой вопрос.
Мне ответ подсказал Юрий Козлов, и ответ этот звучит так:
    vector<vector<int>> vec_2(10, vector<int>(50));

(написано в предположении, что std:: писать не обязательно)
Ну, в общем, не самое тривиальное задание размера :-)