text:
Q: Web Service Client Architecture - c# Morning all,
I have been tasked with developing a client tool for a cloud web service API (A simple WSDL). I am not a seasoned or even qualified developer, I have an intermediate knowledge of C# and enough I believe to make this work, but I don't want a solution that just works, I want to build something clean and well coded which another dev can read and understand and which is intuitive.
You may want to stop me there and say "That is something you can only learn through experience." if that is the case then I can accept that and move on, but if you do have some advice the rest of the details are below.
The solution will be a C# Console application. I have produced a spec for this, it is below:

1.)    Create a console application in .NET which has the following
  capabilities:
2.)    Consume CSV file containing Processed Data OR    ODBC
  Connection to staging SQL database and read records directly out of
  load table
3.)    Make the following calls to Zuora Webservice (Asynchronous) ·
SubscribeWithExisitingAccount() ·         Create() ·
  Login() ·         Subscribe() ·         Update() ·         Delete()
(*) Calls marked with this are possibly avoidable,
*it is possible to create a subscription, account and contact with a
  single call (Subscribe())
*Create() may be the exception as a scenario may occur where we need
  to create an instance of an object with no corresponding subscription.
4.)    Report back the success and errors of every record into a CSV
  file.
 Mappings will be done on a 1 to 1 basis, where the input file

will have the same column names as the target

Where I lack knowledge is following a design which will make this app make sense and work efficiently. I am not looking for someone to do this for me, what I am looking for is tips on how I can improve on what I am already doing
Currently I am just organically building the solution due to a lack of foresight on jobs like this, so I am also interested in things I can do post development.
ALL Advice and criticism is welcomed.
Thanks in advance,
Matt

A: Design principles are a big subject, and how to apply them correctly is only something that comes with experience. There's a lot more of them out there then you'd ever use in a given project, and in some cases using them correctly means not using them at all (or only choosing specific ones that suit the project). The first step is wanting to write good code though, so you're starting in the right place. :) A couple of things did stand out to me:

2.) Consume CSV file containing Processed Data OR ODBC Connection to
  staging SQL database and read records directly out of load table

What you're going to want to do here is only build the logic that does something with this data once. The most direct way to achieve that is to have your logic expect the data in a certain format (probably business classes that hold the parsed data and that your logic an use).
So what you'll do is take the input data (CSV/SQL Table/Whatever) and first parse it into your internal business classes. Then you feed the parsed data to your logic that does whatever your app does with it. The advantage here is that you can change the logic once and it will work with both data types, AND if someone comes along later and says "now we need it to read this Excel file" all you'll have to do is add another parser to get the Excel data into your internal format. No changes to the logic will be required.

4.) Report back the success and errors of every record into a CSV
  file.
Mappings will be done on a 1 to 1 basis, where the input file
will have the same column names as the target

Same as above. Don't assume that you'll be exporting to CSV forever, make a simple "ReportError" class or some such that holds error details and stick it into a List while doing your processing. At the end when it's time to output your errors, you can convert that into a CSV. So if this requirement changes and you instead report errors to a web service, you only have to change a small part of the code (and none of it is your processing logic).
There's a theme here. :) Try to encapsulate logical bits so that if something changes it's easy to find where that something is in code. If you can learn to do that, you'll wind up with maintainable code even if you don't follow any other process or pattern (particularly since as one person you won't be making huge projects).

3.) Make the following calls to Zuora Webservice (Asynchronous) ·
  SubscribeWithExisitingAccount() · Create() · Login() · Subscribe() ·
  Update() · Delete()

As a console app, I'm going to question if you actually need these to be asynchronous or not. What do you hope to gain from an async call to Login()? Can your program do anything while waiting for Login() to return?
It's not that async is terribly difficult, but it IS more to manage then synchronous calls. For a console app from someone whose not that experienced in the technology yet, I'm not sure what benefit you're gaining to weigh against the extra effort it requires of you.

A: I would recomend you read a book on webservices (this is a good one) They arent really something you can just pick up from playing about and can be quite frustraiting if you dont know what your doing.
As for development, I recomend you prototype it first. Hammer something out thats messy but lets you get an idea of how to do things. You can then use that as a reference for when your actually building your app.


text:
Q: How to dump autowired spring beans to a xml configuration file? I am using the @Autowired annotation with spring-mvc and spring-security, it works, but the webapp start very slow, about 1 munute every time, because the spring-mvc and  spring-security scan twice all autowired classes and the total count of classes about 500.
Are there any suggestions to speed up the scan time? or the static xml configuration is better?
in web.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/rest-servlet.xml
    </param-value>
</context-param>
    <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

    <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

    <servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
    <servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
    ....

in rest-sevlet.xml
    <context:component-scan base-package="com.mycomp" />
<mvc:annotation-driven />
<mvc:interceptors>
    ....
    </mvc:interceptors>
<import resource="classes/config/applicationContext-security-base.xml"/>
<import resource="classes/config/applicationContext-security.xml"/>

<import resource="classes/config/spring-aop.xml"/>
<!-- i18n -->
<import resource="classes/config/spring-locale.xml"/>

A: First don't load your configuration twice. Currently both the ContextLoaderListener as well as the DispatcherServlet load the same configuration files. Result duplicate bean instances, duplicate scanning (and next to that in the future memory problems, weird transaction problems etc.).
Your configuration needs to be split. Your ContextLoaderListener should only load things that are general to your application (services, repositories, datasources etc.). The DispatcherServlet in turn should contain/load only web related things like (@)Controllers, ViewResolvers, Views, mvc configuration etc.
Also beware of component-scanning and don't fall into the trap everyone does. If you add the same comonent-scan to each configuration file this will result in bean duplication (ever bean is instantiated twice). So make sure that your ContextLoaderListener' scans for everything but controllers and that yourDispatcherServlet` scans only for web related content (controllers for instance).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install RA3 uprising on ubuntu without origin? Can anyone help me? I got a pc with ubuntu 20.04 LTS and i already got wine and playonlinux (and not-working-origin on playonlinux) and i got RA3 uprising game files from my windows pc with origin copied, and i want to install it but when i run RA3launcher.exe, it says origin is not installed. Can anyone fix this?

A: I think you should give it a try and upload this question to a forum that has to do with Ra3. They might help you better, as not many ppl that use ubuntu (and are surfing this forum) might play Ra3.


text:
Q: Simulate SIP phone in asterisk I've installed GoAutoDial Call Center Software. Due to our ancient phone equipment - until we upgrade it - I'm trying to use it only as a call management software for outbound campaigns. So I can present the phone number to agent , etc. without actually dialing it. agent will still do that by hand.
The problem is that agent disconnects in approx. 20 seconds (no sip phone present). I've tracked down this to asterisk.
From the asterisk log :
NOTICE[15426] channel.c : Unable to request channel SIP/8001

Is there a way to simulate a dummy sip phone , so it doesn't throw the client out ?
Or are there any obscure settings to prevent this (otherwise desirable) behavior ?
I was looking at /etc/conf/asterisk/sip.conf

A: You can use local channel to do call via dialplan. After that you can call client, if fail wait, call again etc. As needed
exten => s,1,dial(Local/exten@context/n,,)

You have setup nat correctly so your agents always online and setup at agents phone re-registration inteval to 20 sec or less.


text:
Q: Visual Basic Struct with all windows constants Every time I do something that ends up using windows API calls in VB, I always end up having to look up the values for the windows constants.
Does anyone have a file with a class or something for VB that defines all the WIN-API constants?

A: Here are a couple of resources for you

*

*Pinvoke.Net: Community driven website which tries to be a reference for Windows API Pinvoke declaration

*PInvoke Interop Assistant: Tool for generating managed PInvoke signatures for native code definitions or the majority of the windows API.

A: It is already available on your machine, unless you have the Express edition.  Navigate to c:\program files\microsoft sdks\windows\xxx\include directory.  Where xxx depends on the version of VS you use.  Like v6.0a for VS2008.  The WinUser.h file contains the most common ones you'd use in a Declare statement.  WinError.h has error codes.  Etcetera.  Convert hexadecimal constants, like "0x0123" to VB.NET notation, like "&H123".
This is the 'ultimate and true' source, the Windows SDK declarations that you use an unmanaged program written in C or C++.  Jared showed you the derived ones, they do tend to be flaky in places but that's mostly because there is more than one way to skin a pinvoke cat.  Ymmv.


text:
Q: Remove main site link from user dashboard in multisite of wordpress I have created a multi site website in wordpress, I want to remove main site link from user admin area, Please prefer screenshot.
Please guide me how can i remove it.
Thank you in advance.

A: *

*Install & network activate User Role Editor plugin from http://example.com/wp-admin/network/plugins.php

*Then go to Settings > User Role Editor menu on network and make sure you have the settings as shown in following screenshot.
Check image this

*Go to "User Role Editor" settings page on your main site http://example.com/wp-admin/users.php?page=users-user-role-editor.php and select the "Administrator" role. Then remove the capabilities which you want to remove. For example, in below screenshot you can see that all User related capabilities have been removed. Do note that I have checked "Apply to All Sites" so that it applies to all the sites on the network.

Check image this

*Now check backend of any of your subsite and you will notice that "Users" menu is no more there. Similarly you can hide other menu pages as intended. Let me know how it goes :-)


text:
Q: How can I resume the match when playing offline with bots? Whenever I enter offline with bots, the match starts paused:

Using pause and unpause commands in the console apply a pause on top of the match pause.
How can I resume the game?

A: This appears to be something caused by spectating matches in GOTV in the same session as trying to play with bots. Restarting the game and going to the offline match first before anything else works fine.

A: Just type the following command into the console:
mp_unpause_match

A: sv_pausable 1

in order to have the ability to set :
pause

and
unpause


text:
Q: If sequence of r.vs $(X_n)$ is independent, then complete convergence is equivalent to convergence a.s? We say that $X_1,X_2,.... $ is a completely convergent sequence to $X$ if
$$ \sum_{n=1}^{\infty} P( |X_n -X | > \epsilon ) < \infty \; \; \; \; for \; \; each \; \; \epsilon >0$$
Question: If sequence of r.v ($X_n)$ is independent, can we conclude that the notions of completely convergence and convergence a.s are equivalent ?

A: If $(X_n)_{n \in \mathbb{N}}$ is completely convergent, then it follows from the (first) Borel-Cantelli lemma that $X_n \to X$ almost surely.
On the other hand, if $(X_n)_{n \in \mathbb{N}}$ is a sequence of independent random variables such that $X_n \to X$ almost surely, then $X=c$ almost surely for some constant $c \in \mathbb{R}$. Therefore, the events
$$\{|X_n-X|>\epsilon\}, \qquad n \in \mathbb{N},$$
are independent. It follows from the (second) Borel-Cantelli lemma that $X_n$ converges completely to $X$.


text:
Q: Have an IF statement constantly check Is there anyway to have an IF statement constantly checking? I'm working with a List and I need to check if the list count exceeds a variable. I've since noticed the easiest way to make the program run smoothly is to have an IF statement checking constantly while the program is running.

A: The best approach for this would be to change from 'List' to 'BindingList'. This is an event enabled list which will fire events when the list changes:
Private WithEvents mList As New System.ComponentModel.BindingList(Of String)

Public Sub Main()
    mList.Add("An Item")
End Sub

Private Sub mList_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles mList.AddingNew
    If mList.Count > 100 Then
        MessageBox.Show("Threshold exceeded")
    End If
End Sub

Alernatively you could start a thread / timer that polls this, however you'll have to watch out for synchronization issues.


text:
Q: Microsoft Access Expression Builder I am exploring the various features of microsoft access and stumbled upon the expression builder. I would like to know what syntax language does this expression builder support? I am not sure if it is VBA, SQL or T-SQL.

A: It's neither. Expressions have their own syntax. They can be used also in VBA and in the query design editor, which may cause your confusion.
Here are the essential links:
Guide to expression syntax
Create an expression
Examples of expressions


text:
Q: Segmentation fault in Boost blocking connect function when no server is present? Boost blocking TCP implementation taken from here:
http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/example/timeouts/blocking_tcp_client.cpp
Another similar problem, mentioned here
Boost.Asio segfault, no idea why
I tried checking the destructor order and dependencies as mentioned in the answer but no luck.
Posting relevant code here
edit:: This MSVC code actually works without segmentation fault. Will be updating code with more relevant info from the failing program.
main.cpp
{
int main(void) {
  int k = Connection_Init();
  return k;
}

}
In Connection_Init(), I am calling c.connect(IP, Host, timeout);
The seg fault occurs while returning from c.connect(), given in Network.cpp
Network.h
{
class client
{
public:
  client()
    : socket_(io_service_),
      deadline_(io_service_)
  {
    // No deadline is required until the first socket operation is started. We
    // set the deadline to positive infinity so that the actor takes no action
    // until a specific deadline is set.
    deadline_.expires_at(boost::posix_time::pos_infin);

    // Start the persistent actor that checks for deadline expiry.
    check_deadline();
  }

  int connect(const std::string& host, const std::string& service, tcp::resolver::query& q1,
      boost::posix_time::time_duration timeout)
  {
    // Resolve the host name and service to a list of endpoints.
    //tcp::resolver::query query(host, service);
    tcp::resolver::iterator iter = tcp::resolver(io_service_).resolve(q1);

    // Set a deadline for the asynchronous operation. As a host name may
    // resolve to multiple endpoints, this function uses the composed operation
    // async_connect. The deadline applies to the entire operation, rather than
    // individual connection attempts.
    deadline_.expires_from_now(timeout);

    // Set up the variable that receives the result of the asynchronous
    // operation. The error code is set to would_block to signal that the
    // operation is incomplete. Asio guarantees that its asynchronous
    // operations will never fail with would_block, so any other value in
    // ec indicates completion.
    boost::system::error_code ec = boost::asio::error::would_block;

    // Start the asynchronous operation itself. The boost::lambda function
    // object is used as a callback and will update the ec variable when the
    // operation completes. The blocking_udp_client.cpp example shows how you
    // can use boost::bind rather than boost::lambda.
    boost::asio::async_connect(socket_, iter, var(ec) = _1);

    // Block until the asynchronous operation has completed.
    do io_service_.run_one(); while (ec == boost::asio::error::would_block);

    // Determine whether a connection was successfully established. The
    // deadline actor may have had a chance to run and close our socket, even
    // though the connect operation notionally succeeded. Therefore we must
    // check whether the socket is still open before deciding if we succeeded
    // or failed.
    if (ec || !socket_.is_open()) {
        cout <<  "send_test_case:connect: Connection could not be established to"
                 << LWIP_IP << " " << LWIP_PORT << endl;
      //throw boost::system::system_error(
            //boost::asio::error::operation_aborted);
          //ec ? ec : boost::asio::error::operation_aborted);
        return -1;
    }
    return 1;
  }

private:
  void check_deadline(

  boost::asio::io_service io_service_;

  //moving to public access
  public: tcp::socket socket_;

  private: deadline_timer deadline_;
  boost::asio::streambuf input_buffer_;
};

}
and Network.cpp
{
 client c;
tcp::resolver::query query(LWIP_IP, LWIP_PORT);

int Connection_Init() {
    cout << "IP: " << LWIP_IP << "and Port:" << LWIP_PORT << endl;
    int status = 1;
    try
    {
        status = c.connect(LWIP_IP, LWIP_PORT, query, boost::posix_time::seconds(POSITIVE_TESTING_CONNECT_TIMEOUT));
    }
    //connection initialization should never fail
    catch(std::exception &e) {
        status = -1;
        std::cerr << __FUNCTION__ << ": " << "Exception: " << e.what() << "\n";
    }
    catch(...) {
        status = -1;
    }
    return status;
}

}


text:
Q: Creating an algorithm for a roulette bot I was wondering if there's any way that I can make a bot that can play roulette (casino game in case you're wondering) while still making a profit?
Say we have a simpler version of a roulette game where the following features count:

*

*Number range is from 0 to 14

*Red is 1 - 7

*Black is 8 - 14

*Green (the rare one) is 0

*You can only bet on either color and any amount you want (as long as you have  the amount)

*A number from the range is picked at random each round.

*Colors red and black will grant you twice the amount you bet if you win

*Green will grant you 15 times the amount since it's 1/15 chance to get the number.

I'm using NodeJS to create my bot, and so far without any luck. This is of course only for practice and it would be pointless to use on a casino anyways since if you're winning too much, you're most likely to get thrown out.
Edit (13.10.2019):
I realize now, 4 years later, that this was a kind of silly question since no, there isn't any way to create a bot that could win every game of roulette. Because that's how the game is designed...
For those stumbling upon this question today, I apologize for the silly question. I was a naive kid wanting to win some CS:GO skins by creating a bot, not realizing that if creating a bot that can win every time, gambling in roulette probably wouldn't be a thing.
For those with the same question, see @Draco18s answer. He explains it pretty well why there is no way to win every time in roulette.

A: No, there is no strategy that will allow you to win in the long-term.

A: No
Here's the thing.  If you bet Red or Black, winning double, your odds of winning are 7/15, or 46%.  This means that on average, you will lose 8% of your bet with every spin of the wheel.  Betting Green will break even.  Betting on any other number, assuming the same 15x payout as betting Green, you still only break even (typically numerical bets ignore 0 and 00, so you'd only get 14x of your bet, not 15x).
There is no strategy that will lead to making a profit unless the randomness of the chosen winning number has a bias.  All true roulette wheels in real casinos develop a slight bias, but they are often checked and maintained on a regular schedule, and the casino tracks all bets being made and will locate a player who has found the bias before that player has made any significant winnings.
http://www.casinoinsider.com/roulette/gonzalo-garcia-pelayo-roulette-made-millions/


text:
Q: How to get hidden column in DataTable? I'm able to get index 2 and 3 of my DataTable while looping through all the checked items. My problem is I can't get the column ID that was set to visible = false.

      <input name="myCheckbox" value="1" id="myCheckbox-select-all" type="checkbox" />
      ID
      Name
      Category
      Address

JQUERY:
manageTable = $('#myTable').DataTable({
  ajax: {
    url: base_url + 'rule/fetchCategory',
    data: function(d) {
      d.category = categoryFilter;
    }
  },
  'columnDefs': [{
    'targets': 0,
    'searchable': false,
    'orderable': false,
    'className': 'dt-body-center',
    'render': function(data, type, full, meta) {
      return '<input type="checkbox" name="id[]" value="' + $('
').text(data).html() + '">';
    }
  },
  {
  "targets": [1],
  "visible": false
    }]
});

//Function on form submit

var rows = [];
manageTable.$('input[type="checkbox"]').each(function() {
var row = $(this).parent().parent();

if (this.checked) {
  var data = [];
  $(row).find("td").each(function(i, obj) {
    if (i == 2) {
      data.push($(this).text());

    } else if (i == 3) {
      data.push($(this).text());
    }

  })
  data.push($("#category").val());
  rows.push(data);

A: You shouldn't iterate over the html of the table because the hidden column obviously isn't in the HTML DOM.
Use datatables functions for this purpose.
First, use row selection plugin for selected rows.
Then, iterate over row's data with myTable.rows({selected:true}).data()
Full working example:

              <LINK href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css">

              <LINK href="https://cdn.datatables.net/select/1.3.4/css/select.dataTables.min.css" rel="stylesheet" type="text/css">

                Checkbox
                Position
                Office
                Age
                Start date
                Salary

                System Architect
                Edinburgh
                61
                2011/04/25
                $320,800

                Accountant
                Tokyo
                63
                2011/07/25
                $170,750

                Checkbox
                Position
                Office
                Age
                Start date
                Salary

And then, you can iterate over row's data with:
myTable.rows({selected:true}).data()


text:
Q: How can I adjust the placement of my html elements I'm using jQuery Mobile 1.3.2 for building a Web-App.
I have a ListView, which entries are not buttons.
I want to have an Icon at the left, a headline, a detail-text and a flip switch. On each entry.
I got it roughly working. But the vertical alignment of my elements could be optimized, if I knew how. That means, the icon is placed higher than the headline, but should be on the same position. As an alternative I would accept a thumbnail, but I don't know how to get that working on list entries that are not buttons.
The following is the code for the list entry template:

Any ideas on that?

A: I'm sorry for tagging this wrong. Of course it is not a jqm problem @mizurnix. I figured out a solution with CSS and HTML:

In CSS, I set padding and margin dependent on the device's orientation.


text:
Q: Partition of [3n] into summoids Let $ [n] $ be the set $ \{1,2,\ldots n\}$.
A summoid is a subset $ A \subset [n] $ of the form $ \{a,b,a+b\} $ (you can choose a better name, if it doesn't exist already).
Now, I developed by accident this simple result:

There is no partition of $ [9] $ into (disjoint) summoids.

I want to ask the following questions:

*

*Is it true for general $ [3k] $ when $ k > 1 $? According to a computer program I found that it is true for $ [12] $, but it seems my method for $ [9]$ can't be applied to the general case (maybe my program for $[12]$ isn't trustworthy).
According to the comment below by R. van Dobben de Bruyn, there is no such partition when $ k \equiv 2,3 \pmod 4$.
According to the comment below by Gerhard Paseman, there is a counterexample for $ k = 5 $ that extends also to $ n = 3 \cdot 4^k $ and to $ n = 3 \cdot (1+4^k) $.

*Is it useful for something?

*Is there any study of such results?

A: I have the following results:

*

*N = 12:
(1, 11, 12)
(3, 7, 10)
(4, 5, 9)
(2, 6, 8)

*N = 15:
(1, 14, 15)
(3, 10, 13)
(4, 8, 12)
(5, 6, 11)
(2, 7, 9)

*N = 24:
(1, 23, 24)
(2, 20, 22)
(5, 16, 21)
(6, 13, 19)
(7, 11, 18)
(8, 9, 17)
(3, 12, 15)

*N = 27:
(1, 26, 27)
(2, 23, 25)
(4, 20, 24)
(7, 15, 22)
(8, 13, 21)
(9, 10, 19)
(6, 12, 18)
(3, 14, 17)
(5, 11, 16)
and so on.
My guess would be that there are always (a lot of) solutions for any $k \equiv 0, 1\mod 4$.
In my opinion, this is some kind of Goldbach-ish problem. It is likely to get some probabilistic heuristic, but may be difficult to prove.

For reference, here I add the number of different solutions for each $k$.

*

*N = 12: 8 solutions;

*N = 15: 21 solutions;

*N = 24: 3040 solutions;

*N = 27: 20505 solutions;

and so on.

EDIT:
Thanks to OEIS, we now have some reference.
In this paper: http://oeis.org/A104429/a104429.pdf, the existence of solutions is discussed in detail in section I.3 (starting from page 22).


text:
Q: How to convert array to string in ruby I have a array with one string value in it
["spec/main/fixtures/rules/test.yml"]

How do i convert this to get "spec/main/fixtures/rules/test.yml"
I tried using [array].to_s which converts to string but will not return the string element from that array.

A: Just take that one element out of the array:
["spec/main/fixtures/rules/test.yml"][0]
#=> "spec/main/fixtures/rules/test.yml"

Or:
["spec/main/fixtures/rules/test.yml"].first
#=> "spec/main/fixtures/rules/test.yml"

A: You can use the previous answers or just use the join method.
like this ["spec/main/fixtures/rules/test.yml"].join, which returns

  # => "spec/main/fixtures/rules/test.yml"

 To know more about join

ruby docs - join method


text:
Q: RNFS.uploadFiles only works for raw uploads not for multipart/form-data I am trying to upload JSON files to the nodejs server which is usng multer as a middleware to receive files and the RNFS.uploadFiles only works for raw Multer and does not work for the multer which has a specific field eg(upload.single('files')
var file = [
                {
                    name: newpath,
                    filename: newpath,
                    filepath: newpath,
                    filetype: 'json'
                }
            ];

            var uploadBegin = (response) => {
                var jobId = response.jobId;
                console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
            };

            var uploadProgress = (response) => {
                var percentage = Math.floor((response.totalBytesSent / response.totalBytesExpectedToSend) * 100);
                console.log('UPLOAD IS ' + percentage + '% DONE!');
            };

            RNFS.uploadFiles({
                toUrl: uploadUrl,
                files: file,
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                },

                begin: uploadBegin,
                progress: uploadProgress
            }).promise.then((response) => {
                if (response.statusCode == 200) {
                    console.log('FILES UPLOADED!');
                } else {
                    console.log('SERVER ERROR');
                }
            })
                .catch((err) => {
                    if (err.description === "cancelled") {
                        // cancelled by user
                    }
                    console.log(err);
                });

            // }
        })
        .catch((err) => {
            console.log(err.message);
        });

multer code
var upload = multer({
storage: storage,// fileFilter: fileFilter
});

router.post('/GetFiles', upload.single('files'), function (req, res) {

if (req.file) {
    res.send({ "Status": true, "Msg": "File Uploaded Successfully" });
}
else {
    res.send({ "Status": false, "Msg": "Failed to upload the File", "body": req.body });
}

})

and is giving error

Error: ENOENT: no such file or directory, open 'http://192.168.1.15:3333/SurveyJsonFiles/GetFiles/' at createErrorFromErrorData (NativeModules.js:155) at NativeModules.js:104 at MessageQueue.__invokeCallback (MessageQueue.js:414) at MessageQueue.js:127 at MessageQueue.__guard (MessageQueue.js:314) at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:126) at debuggerWorker.js:80

A: I changed
 var file = [
            {
                name: newpath,
                filename: newpath,
                filepath: newpath,
                filetype: 'json'
            }
        ];

into
 var file = [
            {
                name: 'files',
                filename: newpath,
                filepath: newpath,
                filetype: 'json'
            }
        ];

it fixed this issue.


text:
Q: Create custom builder that works like Spring DataSourceBuilder? I'm trying to mimic the behaviour of Springs Boot DataSourceBuilder when you can define multiple datasources with a code like this.
    @Bean
    @Qualifier("dataflow")
    @ConfigurationProperties(prefix = "dataflow")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Qualifier("task")
    @ConfigurationProperties(prefix = "task")
    public DataSource taskDataSource() {
        return DataSourceBuilder.create().build();
    }

I've developed some solution based on this question Binding @ConfigurationProperties to builder used to create bean and it works as described below.
I'm trying to create multiple Foo objects based on ConfigurationProperties prefix. Foo class looks like this.
Foo.java
public class Foo {
    private String name, surname;

    public Foo(String name, String surname) {
        this.name = name;
        this.surname = surname;
    }

    @Override
    public String toString() {
        return "Foo{" +
                "name='" + name + '\'' +
                ", surname='" + surname + '\'' +
                '}';
    }
}

I've also created simple FooBuilder
FooBuilder.java
public class FooBuilder {
    private String name, surname;

    public static FooBuilder create(){
        return new FooBuilder();
    }

    public FooBuilder name(String name) {
        this.name = name;
        return this;
    }

    public FooBuilder surname(String surname) {
        this.surname = surname;
        return this;
    }

    public Foo build(){
        return new Foo(name,surname);
    }
}

then I created FooProperites component which has initializeBuilder method.
FooProperties.java
@Component
public class FooProperties {
    private String name, surname;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public FooBuilder initializeBuilder(){
        return FooBuilder.create().name(getName()).surname(getSurname());
    }
}

Then I create some InitConfiguration class for later use with InitTest CommandLineRunner
InitConfiguration.java
@Configuration
public class InitConfiguration {
    @Bean
    @ConfigurationProperties("t1.foo")
    public FooProperties firstFooProperties() {
        return new FooProperties();
    }

    @Bean
    public Foo firstFoo(FooProperties firstFooProperties) {
        return firstFooProperties.initializeBuilder().build();
    }

    @Bean
    @ConfigurationProperties("t2.foo")
    public FooProperties secondFooProperties() {
        return new FooProperties();
    }

    @Bean
    public Foo secondFoo(FooProperties secondFooProperties) {
        return secondFooProperties.initializeBuilder().build();
    }
}

InitTest.java
@Component
public class InitTest implements CommandLineRunner {
    private Foo foo1,foo2;

    public InitTest(Foo firstFoo, Foo secondFoo) {
        this.foo1 = firstFoo;
        this.foo2 = secondFoo;
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println(foo1);
        System.out.println(foo2);
    }

}

Based on following application.properties file:
t1.foo.name=a
t1.foo.surname=b

t2.foo.name=x
t2.foo.surname=z

everything works fine, and the following output is produced:
Foo{name='a', surname='b'}
Foo{name='x', surname='z'}

The question is how to make the same outcome without explicitly defining properties beans, so that the code in initConfiguration could look something like this:
@Configuration
public class InitConfiguration {
    @Bean
    @ConfigurationProperties("t2.foo")
    public Foo firstFoo() {
        return FooBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("t2.foo")
    public Foo secondFoo() {
        return FooBuilder.create().build();
    }
}

and the output is:
Foo{name='null', surname='null'}
Foo{name='null', surname='null'}

It works the same when written that way:
@Configuration
public class InitConfiguration {
    @Bean
    @ConfigurationProperties("t1.foo")
    public Foo firstFoo(FooProperties properties) {
        return properties.initializeBuilder().build();
    }

    @Bean
    @ConfigurationProperties("t2.foo")
    public Foo secondFoo(FooProperties properties) {
        return properties.initializeBuilder().build();
    }
}

I quess it has something to do with auto configuration feature of Spring Bootbut I can't figure it out from Spring implementations of DataSourceBuilder, DataSourceProperties, DataSourceConfiguration, DataSourceAutoConfiguration.
The question is... how to achieve that?
Please find my GitLab repo for this problem HERE.


text:
Q: Simple logic in C++. Not allowed to use an IF statement So I'm new to programming and learning C/C++. The assignment is to create a simple program that will compute the total of a given price and quantity of an item. The part that I am stumped on is that we are not allowed to use an "if or switch statement" in creating the program. We are required to ask the user if the item is taxable or not, using 1 as yes and 0 as no. Right now I have the program to calculate both and read out both taxed and non-taxed. Any help would be greatly appreciated, I know this is amateur and the most basic of programming.
#include <stdio.h>

#define TAX_RATE 0.065
int main() {

  int item_quantity, taxable;
  float item_price, total_with_tax, total_without_tax, a, b;

  // Read in the price of the item

  printf("What is the price of the item? (Should be less than $100)\n");
  scanf("%f<100", &item_price);

  // Read in the quantity of the item being purchased

  printf("How many of the item are you purchasing? (Should be less than 100) \n");
  scanf("%d<100", &item_quantity);

  // Read in if it is taxable or not

  printf("Is the item a taxed item (1 = yes, 0 = no)?\n");
  scanf("%d", &taxable);

  // Calculate total with tax

  a = item_quantity*item_price*(1 + TAX_RATE);

  // Calculate total without tax

  b = item_quantity*item_price;

  printf("Your total purchase will cost $%.2f\n", a);

  printf("Your total purchase will cost $%.2f\n", b);

  return 0;

}

A: So taxable is either 0 or 1. Now look at the similarity between these two lines:
a = item_quantity*item_price*(1 + TAX_RATE);
b = item_quantity*item_price;

How could you make these a single line that uses the value of taxable so that it does what the first line does when taxable is 1 and what the second line does when taxable is 0? Which bit needs to change? How could you make that happen?
Since it's your assignment, I think that's enough of a clue.

You seem to be struggling. Okay, consider the following lines that do exactly the same as the above two lines:
a = item_quantity*item_price*(1 + TAX_RATE);
b = item_quantity*item_price*(1);

What's the difference between them? Something disappeared. What's an easy way to make something disappear using basic math operators?
The answer has nothing to do with anything special to C++. It's just math!

A: The most common options for making decisions without an if or switch statement are the && ("and" operator), || ("or" operator), ?: (ternary operator), and * (multiplication operator).

A: You have to find a way to negate the TAX_RATE if the user is giving you 0. It's a simple mathematical operation that we're trying to clue you in on.

A: U can change the Equation:
a = item_quantity*item_price*(1 + TAX_RATE);
Add taxable variable in the equation in such a way that when taxable is 0,
Equation becomes:
a = item_quantity*item_price


text:
Q: Relation of SPT phases with different boundary conditions Using the definition that two SPT phases are distinct if they can't be connected by a symmetric finite depth local unitary, how does one relate systems with different boundary conditions?
For example, the ground state of the Majorana chain with periodic/antiperiodic boundary conditions have different fermion parities. Why do we consider them the same phase if one must break fermion parity to connect them?


text:
Q: error in invalid initialization of non-const reference type . Using c++ code in Linux OS. GCC Compiler vector<string>& temp = var_obj.funct(); is not working in Linux but except & ITS WORKING FINE.
vector<string> temp = var_obj.funct();

error :  invalid initialization of non-const reference of type
  'std::vector,
  std::allocator >, std::allocator, std::allocator > > >&' from a temporary
  of type 'std::vector,
  std::allocator >, std::allocator, std::allocator > > >'

A: The problem is that the value returned by the function is temporary. You cannot generate a reference to it because it exists only temporarily. After the function call, the value is gone.
Instead, try this:
vector<string> temp = var_obj.funct();
vector<string> &temp2 = temp;

Now you have a reference with the name temp2.


text:
Q: how do i register .xap mime type in IIS 6 programatically i want to register .xap mime type for a particular site in IIS6

A: I believe you can only add them manually.
Go to Run >> "inetmgr"
Right click on your computer (Local Computer) and click on Properties
Select MIME Types, then "New".
Type ".xap" for Extension and "application/x-silverlight-app" for MIME-Type.


text:
Q: How to replace characters or words in a string using javascript even with no space between them? I have a function something like this :
 var exchange = function(code) {
     var ref = {
       'one' : '1' ,
       'two' : '2' ,
       'three' : '3'
     };
   return code.split(' ').map( function (a) {
     return a.split(' ').map( function (b) {
        return ref[b];
     }).join('');
   }).join(' ');
 };

So now I do it :
 var strg = "one two three";
 alert( exchange( strg ) ); // => 123

It works fine but I have a problem. Let me explain. I want it to execute same as now till with no space between.
For example :
 var strg = "onetwothree";
 alert( exchange( strg ) ); // => Nothing

But I want it to change the text even with no spaces. How can I do that ?

A: You could create a regular expression with a joined string with pipe and replace found string with the values.

var exchange = function(code) {
        var ref = { one: '1',  two: '2', three: '3' };
        return code.replace(new RegExp(Object.keys(ref).join('|'), 'ig'), k => ref[k]);
    };

console.log(exchange("onetwothree"));

A: You can iterate over number values and replace them.
 var exchange = function(code) {
     var ref = {
       'one' : '1' ,
       'two' : '2' ,
       'three' : '3'
     };
   Object.keys(ref).forEach(k => code = code.replace(k, ref[k]))
  return code
 };
 var strg = "onetwothree";
 alert( exchange( strg ) ); // => 123

A: I think likely the best thing to do is to create a standard parser constructor that goes character by character and then provide it a configuration and a function wrapper.
Constructor
//Parsing input output constructor;
function ParseFor( i, o ) {
    this.str = i;
    this.indexLength = this.str.length - 1;
    this.arr = [ ...i ];
    this.pointer = 0;
    this.output = o;
    this.match = false;
    this.reset = function() {
        this.pointer = 0;
        this.match = false;
    }
    this.next = function( c ) {
        if ( this.arr[ this.pointer ] === c ) {
            if ( this.pointer === this.indexLength ) {
                this.match = true;
            } else {
                this.pointer++;
            }
        } else {
            this.reset();
        }
        return this;
    }
}

Parse Work with RegEx and Constructor
    let parsers = [];
    for ( let [ k, v ] of Object.entries( ref ) ) parsers.push( new ParseFor( k, v ) );
    let parsedStr = str.replace( /./g, ( c ) => {
        let output = "";
        parsers = parsers.map( parser => parser.next( c ) );
        parsers.forEach( parser => {
            if ( parser.match ) {
                parser.reset();
                output = parser.output;
            }
        } );
        return output;
    } );

Parse Function Wrapper
function parseStr( str, ref ) {

//... PARSE CONSTRUCTOR

//... PARSE WORK
    return parsedStr;
}

parseStr( "onetwothree",  {
        'one': '1',
        'two': '2',
        'three': '3'
    });

EXAMPLE:

function parseStr( str, ref ) {

//Parsing input output constructor;
function ParseFor( i, o ) {
 this.str = i;
 this.indexLength = this.str.length - 1;
 this.arr = [ ...i ];
 this.pointer = 0;
 this.output = o;
 this.match = false;
 this.reset = function() {
  this.pointer = 0;
  this.match = false;
 }
 this.next = function( c ) {
  if ( this.arr[ this.pointer ] === c ) {
   if ( this.pointer === this.indexLength ) {
    this.match = true;
   } else {
    this.pointer++;
   }
  } else {
   this.reset();
  }
  return this;
 }
}

//parse work

 let parsers = [];
 for ( let [ k, v ] of Object.entries( ref ) ) parsers.push( new ParseFor( k, v ) );
 let parsedStr = str.replace( /./g, ( c ) => {
  let output = "";
  parsers = parsers.map( parser => parser.next( c ) );
  parsers.forEach( parser => {
   if ( parser.match ) {
    parser.reset();
    output = parser.output;
   }
  } );
  return output;
 } );
 return parsedStr;
}

console.log( parseStr( "onetwothree",  {
  'one': '1',
  'two': '2',
  'three': '3'
 }) );


text:
Q: Pulling information from one tab to another I need to populate specific columns in one tab from the original data held in the first tab. I have done a quick reordered VBA code to help anybody understand what I am trying to do in the hope they can refine. I also need the VBA code to stop at the line where the data ends. currently the recorded VBA code pulls down to row 159 yet the data in the original tab stops at row 72. I would have stopped my VBA code at the line where the information ends but this changes from day to day and could be anywhere from row 1 to 158.
(If I populate a cell past where the data ends in the original it makes the sheet unusable for other purposes I require it for, even if it is a zero.)
There is data in column A and B, so I was thinking if the macro could say if data is in cell A15 then pull though info from G15 etc?? No data no pull.
I know this may seem basic to some but as a novice I am still getting my head around VBA.
Sub Populate_Order()
ActiveWindow.SmallScroll Down:=-15
Range("M8").Select
ActiveCell.FormulaR1C1 = "='Order Sheet'!R[7]C[-6]"
Range("M8").Select
Selection.AutoFill Destination:=Range("M8:M159"), Type:=xlFillDefault
Range("M8:M159").Select
ActiveWindow.SmallScroll Down:=-135
Range("Q8").Select
ActiveCell.FormulaR1C1 = "='Order Sheet'!R[7]C[-9]"
Range("Q8").Select
Selection.AutoFill Destination:=Range("Q8:Q159"), Type:=xlFillDefault
Range("Q8:Q159").Select
ActiveWindow.SmallScroll Down:=-132
Range("R8").Select
ActiveCell.FormulaR1C1 = "='Order Sheet'!R[7]C[-9]"
Range("R8").Select
Selection.AutoFill Destination:=Range("R8:R159"), Type:=xlFillDefault
Range("R8:R159").Select
ActiveWindow.SmallScroll Down:=-123
Range("I3").Select

A: to find the next empty row try something like this
Dim sourceSheet As Worksheet: Set sourceSheet = ThisWorkbook.Worksheets("sheet1")
Dim destSheet As Worksheet: Set destSheet = ThisWorkbook.Worksheets("sheet2")
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row

destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("M1").Value

this is a simple example of finding the next empty row then setting column A in that row to the value from cell M1 in another sheet


text:
Q: How to create a new tag in a Subversion repository, using hgsubversion? Using TortoiseHg and the hgsubversion extension (command line is fine too).
Cloning an SVN URL  hg clone http://svn.example.org/hello-world, that has the following structure.

*

*..

*branches/

*tags/

*trunk/

Results in a local copy with only files from /trunk.

*

*..

*.hg

*.hgtags

*file1

*file2

*file3

Doing hg push works fine and alters the files in /trunk. But I need to create new tag folders in /tags and push changes there.
Adding a tag to a revision in Hg and pushing changes results in a "Sorry, can't find svn parent of a merge revision."
Is there any way to preserve the SVN folder structure during clone?
edit: Typing hg tags does show the structure at the command line, but I need to push into the remote /tags directory and a default push is going into /trunk, no idea how to change how this works.

A: You can't create tags in SVN from Mercurial

A: https://bitbucket.org/durin42/dotfiles/src/ae22ef7859eb0d2b8ba0edbacfae0e61a0e7bb51/.shell.d/50.hg_functions.sh?at=default#cl-88 is how I usually create svn branches when using hgsubversion. It shouldn't be hard to modify that to create tags instead.


text:
Q: User models and Auth0 I am developing an app in Aurelia which has a .net core backend. I have already implemented user Authentication with Auth0 in the frontend.
The problem comes as I am not sure if its good practice to implement a way so that users from auth0 database are linked with my user model in .net core and in my database. When a user registers/logs in I can get the corresponding user model from my database.
Basically I would be using the auth0 database jsut for logging in and my database for the user details.
If it is good practice how should I go around and doing it? Is a 'post user registration' action good? Any help appreciated :)

A: It is a common approach to let the Authentication Service keep only the minimum amount of data it needs to authenticate a user, and then have additional, business-related data in a separate service. These should be linked upon user registration.
Note, that if that data in the separate service would be used to perform authorization decisions, then the Authorization Server (Auth0 in your case) should be able to read that data when issuing tokens, and relevant information about the user should end up in the signed token in form of claims. This gives you the assurance that this data is not tampered with.
Have a look at this article that my colleague wrote: https://curity.io/resources/learn/integrate-identity-business-data/ as it describes in more detail what you need.


text:
Q: MySQL server start error with "ERROR! The server quit without updating PID file" When I was start mysql, It happened.
Starting MySQL
.Logging to '/opt/homebrew/var/mysql/luyaodeMacBook-Air.local.err'.
 ERROR! The server quit without updating PID file (/opt/homebrew/var/mysql/luyaodeMacBook-Air.local.pid).

My computer is MacBook Air with M1.


text:
Q: Context switching in different thread Is there any way to perform a preemptive same-thread context switch?
I am pretty sure that is not the right way to describe what I am looking for, so here is a longer description:
I want the same type of behavior as POSIX ucontext_t or boost::context. There are probably others I am not aware of. I don't know the official term for it, but basically they allow single-threaded multitasking. Both those libraries require "cooperative" code, that is, the currently running "thread" must explicitly perform a context-switch.
I am looking for a way to force a context switch. I assume this would have to be done from a separate thread (real OS thread). I would want to have an array of "contexts", frozen execution paths, and be able to switch to any one I choose, freezing the current execution.
I don't care whether the solution uses a separate thread for the "switcher" (I assume this is required) or not.
I am fine with Java/C#/C++/C solutions, or a combo of C/C++ and some minimal Assembly.
I would like if it was cross platform (Windows and Linux) and cross compiler (GCC, MinGW and VS, assuming a c/c++ solution), but am aware this is not likely to be possible. At a minimum it should work on Windows with at least one compiler.
I am fine using almost any library or compatibility layer needed (e.g. boost or some sort of 'POSIX on Windows' layer)
I hope this isn't asking for to much.

A: boost.fiber - can be programmed like boost.thread but provides user-land threads


text:
Q: Members in backoffice I am developing an application in Umbraco where I need to get my members from an external already existing database. I have succeeded in making a custom membership provider which I use to validate users.
What I would like to do now is to get the list of members in the external database to be visible in the members area in the backoffice. Is this possible and if so any ideas on how to accomplish it?

A: Unfortunately no.
To achieve this you must build a custom member application for Umbraco.
== Edit on request ==
The member gui is explicitly built to handle Umbraco Member Objects, these object can be extended with properties of the same data types as all objects in Umbraco. This gui won't simply work with a regular asp.net membership provider since they are not compatible.
To best match this you should extend the umbraco.providers.members.UmbracoMembershipProvider class instead of the ordinary asp.net membership provider.
Now, you can make calls from the UmbracoMembershipProvider to any asp.net membership provider but this is a discussion of architecture and philosophy :)

A: I have had a similar requirement in a previous project. We created a scheduled task that used a secure web service to collect the users and then programmatically added them into the Umbraco backoffice. The scheduled task had to check for existing users in order to avoid duplicate entries.
Also, the passwords of the users would need to be available in plain text in order for them to be added into Umbraco. If they aren't, then you will need to create a new password for each user which may be impractical.
See here for more information on the membership api.


text:
Q: Headless UI & React Dropdown menu changing position when clicked I want to create a dropdown menu, for which I'm using HeadlessUI on React with Tailwind.
The menu is working fine, except that when clicked on, the position of the menu changes, as in instead of dropping down perfectly from the menu button it overlays it (I don't know how to describe it exactly).
Here's a before and after, hope you can make out what I'm trying to say:
Before button is clicked
After the button is clicked
The code for the dropdown menu:
function HomeMenu(props) {
return (
<Menu>
  <Menu.Button>{props.name}</Menu.Button>

  <Transition
    enter="transition duration-100 ease-out"
    enterFrom="transform scale-95 opacity-0"
    enterTo="transform scale-100 opacity-100"
    leave="transition duration-75 ease-out"
    leaveFrom="transform scale-100 opacity-100"
    leaveTo="transform scale-95 opacity-0"
  ></Transition>

  <Menu.Items>
    <Menu.Item>
      {({ active }) => (

          Account settings

      )}
    </Menu.Item>
    <Menu.Item>
      {({ active }) => (

          Logout

      )}
    </Menu.Item>
  </Menu.Items>
</Menu>
  )
  }

The div in which the menu is used:

          NEW STREET JOURNAL

        <HomeMenu name={props.name}/>

A:

        <HomeMenu name={props.name}/>

try to remove the classname absolute and try again


text:
Q: Why wont my onclick not remove any of my classes? I have a huge problem here.
I can't get my onclick to work as I want .. So I hope someone here can help me.
#NiceToKnow

I want it to display: none; every of my class="nice", so you only can see class="video", but nothing happens at all.

A: You are selecting the elements of the class not the class itself. So you will have to loop through the elements as javascript can only edit what is in the DOM not the CSS classes that effect your elements. So getElementsByClassName returns an array of nodes in which we must loop through and hide each one. Click runsnippet below to see this work

function changeNice(){
//ASSIGN ELEMENTS TO ARRAY
elementsofClass=document.getElementsByClassName('nice');
for(i=0; i<elementsofClass.length; i++){
    //HIDE SELECTED ELEMENT
    elementsofClass[i].style.display='none';

}}
#NiceToKnow

TEST 1

TEST 2

TEST 3

I don't HIDE

Also don't use duplicate ID. This will cause errors later when trying to select your elements.

A: The getElementsByClassName will return an array, so we need to iterate through the array and hide one by one.
So it is better to declare a function and define the logic inside that. Please see the example below.

window.hideAllniceClass = function () {
    var elems = document.getElementsByClassName('nice');
    for (var i = 0; i != elems.length; ++i) {
        elems[i].style.display = "none"; // hidden has to be a string
    }
}
#NiceToKnow

Test Content

Test Content

Test Content

Test Video Content

DEMO

A: Change your code to something like that:
var elems = document.getElementsByClassName('nice');
for(var i = 0; i < elems.length; i++) {
    elems[i].style.display = 'none'
}

You have to iterate on the results returned by getElementsByClassName.
jsfiddle

A: You can create a loop that will loop through all the nice elements and then display none like this:  https://jsfiddle.net/7vf9pz8u/

A: getElementsByClassName returns array of all the match elements so you will have to provide index or loop through all of them to change their property.
Change your code to this
document.getElementsByClassName('nice')[0].style.display='none'

//For every element
var e = document.getElementsByClassName('nice');
for (i = 0; i < e.length; i++) {
  e[i].style.display = "none";
}

A: As your divs do not have unique names they are in an array cards[].
So to access a particular div you need to reference the the array to that particular div. The quoted solution should work.


text:
Q: Trying to setup Exchange 2010 certificate on TMG I'm running into a problem here, and I'm positive it's simply that I'm not doing something correct (as opposed to it not working).  I have a current Exchange 2007 server setup with a third party cert for it on TMG.  I'm currently testing Exchange 2010 and wanted to test OWA and Activesync as well (I'm the only mailbox on the server so far).  For the life of me I can't figure out how to issue a self-signed cert and install it on the TMG server so that when i go to "mail.company.com" it likes it.
I've done quite a bit of looking online but so far have yet to get a working solution.  My last attempt I did this:
Open Chrome, attempt to go to mail.company.com.  It sees the cert as not trusted, i then export that cert to the desktop (this was done from my PC).
Copy that cert to the TMG server.  Open up certmgr and add that certificate to the Personal/certificate group (via import).  Import was successful and I now see that cert as well as the working Exchange 2007 cert in there that folder.
Open Forefront TMG and go to Firewall policy, add a new Web Listener, require SSL, select All Networks, click select certificates and I see the current 2007 Exchange cert there from the 3rd party, but not the one I just imported.
What am I missing here?  I do see that the certs in there that are available (and currently being used) are all "Class 3 International Server" certs, if that is relevant.  The one I imported is issued by our Domain Controller.  I just want to try to use the self signed cert for testing, to make sure it all works before moving forward.  We will eventually just edit our current Exchange cert to work with the new Exchange server.
It's been awhile since I messed with this, and I'm obviously missing something.  If anyone could point me in the right direction I would appreciate it.  Thanks!

A: You need to place the certificate in the "Computer" account and not the user account.  Do do that

*

*run "MMC"

*Click on File.Add/Remove Snapins

*Add the "Certificates" snap in and when prompted select  "Computer account" rather than the default "My user account"

*Click Finish

*In the tree on the left, expand the Certificates node

*Right click the "Personal" node and select All Tasks -> Import

From there the import procedure is similar to what you have already done.
After than it should appear in the list of certs.
Note that you also may need to add it to the trusted list


text:
Q: can't execute shell script from crontab can't execute shell script from crontab
Here is my crontab
* * * * *       /home/open-cv/run.sh

Here is my run.sh
#!/bin/bash

cd /home/py
source env/bin/activate
python script.py

A: *

*Ensure that your script is executable

chmod +x /home/open-cv/run.sh

*Try to use a particular binary from your environment

#!/bin/bash
/home/py/env/bin/python /home/py/script.py

A: Jobs run through cron, or at, or batch, aren't run in the same runtime environment that you have on your desktop. None of your PATH changes, or other environment  variable settings are automatically propagated to  your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).
One can set environment variables for all one's cron jobs in the crontab file
Read man 5 crontab.
Look at the results of  echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.
Since the command part of the crontab line is, by default,  interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script  (executable, mounted, starts with #!/bin/bash) which sets up the environment,  then calls the desired program.


text:
Q: How can I export function in a function in bash? I am learning bash. And I would like to make a function which wrap another function in a temporal script file and execute it with sudo -u command in sub-shell.
 The problem I encountered is the generated script cannot find the wrapped function although it is exported in the wrap function.
 I append test cords below. Someone who finds problems, please let me know. Thank you very much.
main.sh
source "./display.sh"
source "./sudo_wrap.sh"

display_func "load success"

sudo_wrap_func '' 'display_func' '3' '4 5'

output, display.sh, sudo_wrap.sh and generated temporal file are appended below,
output
display_func : load success
export -f display_func
30481: line 5: display_func: command not found

display.sh
function display_func() {
  echo "display_func : $@"
}

sudo_wrap.sh
function sudo_wrap_func() {

  local sudo_user="${1:-root}"
  local function_name="${2:?'function_name is null string.'}"
  shift 2
  local func_augs=( "$@" )

  local script

  # *** script : header ***
  script="#!/bin/bash\n"
  script="${script}\n"

  # *** script : making augments for function ***
  script="${script}augs=("

  for aug in "${func_augs[@]}"
  do
    if [[ "${aug}" =~ [[:blank:]] ]]; then
      script=" ${script} \"${aug}\""
    else
      script=" ${script} ${aug}"
    fi
  done
  script="${script})\n"

  local tmp_script_file="${RANDOM}"

  echo -e "${script}" >> "${tmp_script_file}"

  # *** script : calling function with augments ***

  echo -e "${function_name} \"\${augs[@]}\"\n" >> "${tmp_script_file}"

  echo "export -f "${function_name}"" >&2
  export -f "${function_name}"

  sudo -u"${sudo_user}" bash "${tmp_script_file}"
  rm "${tmp_script_file}"

}

temporally generated file (in this case, file name is 30481)
  #!/bin/bash

augs=( 3 "4 5")

display_func "${augs[@]}"

A: As I said in a comment, the basic problem is that sudo cleans its environment (including both variables and functions) before running the command (/script) as another user. This can be overridden with sudo -E, but only if it's explicitly allowed in /etc/sudoers.
But the problem is not insoluble; you just have to include the definition of the function in the script, so it gets recreated in that environment. bash even has a convenient command, declare -f display_func, that prints the function definition in the appropriate form (and declare -p variable does the same for variables). So you can use those to add the appropriate definitions to the script.
Here's a script I wrote to do this. I made a few other changes vs. your script: I take -u username to specify a different user to run as (so you don't have to pass '' as the first argument if you don't want to specify a different user). I also added -f functionname and -v variablename to "export" additional function and variable definitions into the script (in case the main function depends on them). I also create the temp script file in /tmp, and change ownership if necessary so it'll be readable by the other user.
#!/bin/bash

me="$(basename "$0")"
usage() {
    echo "Usage: $me [-u user] [-f otherfunction] [-v variablename] function [args...]" >&2
}

tmp_script_file=$(mktemp "/tmp/${me}.XXXXXXXXXXXX") || {
    echo "Error creating temporary script file" >&2
    exit 1
}
echo "#!/bin/bash" > "$tmp_script_file" # Not actually needed, since we'll run it with "bash"

# Parse the command options; "-u" gets stored for later, but "-f" and "-v" write
# the relevant declarations to the script file as we go.
sudo_user=""
while getopts u:f:v: OPT; do
    case "$OPT" in
      u)
        sudo_user="$OPTARG" ;;

      f)
        declare -f "$OPTARG" >>"$tmp_script_file" || {
            echo "Error saving definition of function $OPTARG" >&2
            exit 1
        } ;;

      v)
        declare -p "$OPTARG" >>"$tmp_script_file" || {
            echo "Error saving definition of variable $OPTARG" >&2
            exit 1
        } ;;

      ?) usage; exit 1 ;;
    esac
done
shift $(($OPTIND-1))

if (( $# == 0 )); then # No actual command specified
    usage
    exit 1
fi

# Write the main function itself into the script
declare -f "$1" >>"$tmp_script_file" || {
    echo "Error saving definition of function $1" >&2
    exit 1
}

# Then the command to run it, with arguments quoted/escaped as
# necessary.
printf "%q " "$@" >>"$tmp_script_file"
# the printf above won't write a newline, so add it by hand
echo >>"$tmp_script_file"

# If the script will run as someone other than root, change ownership of the
# script so the target user can read it
if [[ -n "$sudo_user" ]]; then
    sudo chown "$sudo_user" "$tmp_script_file"
fi

# Now launch the script, suitably sudo'ed
sudo ${sudo_user:+ -u "$sudo_user"} bash "$tmp_script_file"

# Clean up
sudo rm "$tmp_script_file"

Here's an example of using it:
$ foo() { echo "foo_variable is '$foo_variable'"; }
$ bar() { echo "Running the function bar as $(whoami)"; echo "Arguments: $*"; foo; }
$ export -f foo bar # need to export these so the script can see them
$ export foo_variable='Whee!!!' # ditto
$ # Run the function directly first, so see what it does
$ bar 1 2 3
Running the function bar as gordon
Arguments: 1 2 3
foo_variable is 'Whee!!!'
$ # Now run it as another user with the wrapper script
$ ./sudo_wrap.sh -f foo -v foo_variable -u deenovo bar 1 2 3
Running the function bar as deenovo
Arguments: 1 2 3
foo_variable is 'Whee!!!'

Note that you could remove the need to export the functions and variables by either running the script with source or making it a function, but doing that would require changes to how $me is defined, the usage function, replacing all those exits with returns, and maybe some other things I haven't thought of.


text:
Q: Unable to perform javascript functions on Rails mobile site I have a existing website in rails 2.3.8 which i want to develop for mobile phones(andriod,iphone), something like facebook's mobile site.
I found that creating the view pages with extension .mobile.erb will do the job.
But the problem is i am unable to call existing javascript functions on mobile site which i used for the main site.
I want to know if it is possible to call js or is there any alternative way.

A: Of course, you can use javascript on you mobile web pages. For iOS and Android. For other mobile i don't know.
Doc for safari ios : http://developer.apple.com/devcenter/safari/index.action

A: For iPhone you can use the iUI framework http://code.google.com/p/iui/ which consists of a JavaScript library, and CSS similar to that of native iOS apps.


text:
Q: Java Spring Actuator Grafana - time taken for a request different between http_server_requests_seconds_max and http_server_requests_seconds::sum/count Quick question regarding two queries for the time taken for an API please.
My SpringBoot app has out of the box http_server_requests_seconds max, count and sum metrics.
Therefore, I wanted to build a visual in order to see how much time do I take to answer a request.
With that in mind, I started to search on the web existing queries, and found two, which are both supposed to provide the request duration:
http_server_requests_seconds_max{_ws_="my_workspace"}
irate(http_server_requests_seconds::sum{_ws_="my_workspace"}[5m]) / irate(http_server_requests_seconds::count{_ws_="my_workspace"}[5m])
Unfortunately, the dashboards show completely different graphs.
May I ask if I use one of the two query wrong please?
Which of the two is the most appropriate query in order to get the time taken for a request?
Thank you

A: One obvious difference is that the second example calculates the first derivative of your values (the rate), whereas the first does not.
The second query calculates the average response time over 5 minute intervals, the first query simply shows the maximum value of the timer metric.
An explanation of the different metric types in Prometheus can be found at https://prometheus.io/docs/concepts/metric_types/#summary. irate is explained at https://prometheus.io/docs/prometheus/latest/querying/functions/#irate


text:
Q: A Program to Store File Info I am super confused on how to make a program that scans a directory for files (and files in sub directories) for information such as size, name, path, etc. For now, I just need this information written to a txt file, but I will later need to use this txt file to copy all my files to a directory on a remote computer.
I'm not very experienced with Java so if there are some libraries that you think I should research, please let me know. I think the scariest part of getting this information is how to tell computer that you need to enter a sub directory to search for its contents (like going into a Documents folder from Home, and then maybe even going into an EnglishClass folder from there).
I hope this isn't too vague. Let me know if you need more details.

A: This will print a list of files from the current directory and their sizes:
List<String> fileList = Arrays.asList(new File(".").list());
fileList
    .stream()                   // Use java streaming api.
    .map(f -> new File(f))      // Convert file name into file.
    .forEach(f -> {             // Iterate over each file.
        // Print info about each file.
        System.out.println("File name:"+f.getAbsolutePath());
        System.out.println("File size:"+f.length());
    }
);

If you want to scan sub-directories, read up on how to use recursion. (Hint: f.isDirectory() {...} )


text:
Q: Get release date for project version with jira-python I am using jira-python to generate some status reports. My issues are associated with Versions and I want to order them according to the release dates of the versions. These dates can be set in Jira under version administration, but it seems difficult to access them in jira-python!
I can't find a releasedate attribute on the version object. One possibility seems to be to use the self-attribute of the version, which yields an http:/-address. Pasting that address into my browser I find a string like this:
{"self":"http://jira/rest/api/2/version/11781","id":"11781","description":"Nera 555 DVT build","name":"NE_555_DVT","archived":false,"released":false,"releaseDate":"2016-04-01","overdue":true,"userReleaseDate":"2016-04-01","projectId":11130}

I should be able to download and parse this string, but want to check first if anyone knows of a simpler way.

A: I figured out that I can get the release date in this way:
i = jira.version(v.id, expand="ReleaseDate")
i.releaseDate

Where jira is the JIRA object and v is the version I want to get the release date for.


text:
Q: Como puedo obenter mi edad a travez de una consulta en sql WORBENCH Cuando ejecuto esta consulta
SELECT TRUNCATE(sysdate()- fecha_nacimiento) from personas;

obtengo este error

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') from personas' at line 1

A: Si el campo fecha_nacimiento es tipo date, puedes utilizar TIMESTAMPDIFF y obtendrás el resultado que necesitas, algo así:
SELECT TIMESTAMPDIFF(YEAR,fecha_nacimiento, NOW()) from personas;

Te dejo un ejemplo:
Ejemplo


text:
Q: How to add username and password in WebService body and get token I am working on swift and facing issue for fetching token from the server. I tried to solved it but in iOS it always fails. I put the api in hurl.it and Add header content type: Application/json, but I don't know how to add payload value : payload--{\"username\": \"username\",\"password\": \"userpassword\"} in Webservice request.

A: You can set your payload data in httpbody of Request Like Below Code.
var dicParameter : NSDictionary = ["username": "username","password":"password"]
                var reqData : NSData = JSONSerialization.data(withJSONObject: dicParameter, options: JSONSerialization.WritingOptions.init(rawValue: 0))

                var request : URLRequest = URLRequest.init(url: "url")
                request.httpBody = reqData


text:
Q: Symmetry in summation Can someone please explain the motivation behind this equality?
$\sum_{i=1}^{n} (\sum_{j=1}^{i} + \sum_{j=i}^{n})\frac{1}{ij} = 2\sum_{i=1}^{n} \sum_{j=1}^{i} \frac{1}{ij}$
They explain that it is symmetry of some kind.

A: To obtain $(1)$, note that
$$\sum_{i=1}^n\sum_{j=1}^i\frac{1}{ij}
= \sum_{1 \le j \le i \le n} \frac{1}{ij}
\overset{\text{(interchange $i$ and $j$)}}{=} \sum_{1 \le i \le j \le n} \frac{1}{ji}
\overset{\text{(commutativity)}}{=} \sum_{1 \le i \le j \le n} \frac{1}{ij}
= \sum_{i=1}^n\sum_{j=i}^n\frac{1}{ij}$$

A: We can rewrite the equation as
$$\sum_{i=1}^n\sum_{j=1}^i\frac1{ij}+\sum_{i=1}^n\sum_{j=i}^n\frac1{ij}=2\sum_{i=1}^n\sum_{j=i}^n\frac1{ij}\,,$$
so the question is why
$$\sum_{i=1}^n\sum_{j=1}^i\frac1{ij}=\sum_{i=1}^n\sum_{j=i}^n\frac1{ij}\,.\tag{1}$$
$\sum_{j=1}^i\frac1{ij}$ is the sum of the fractions in row $i$ of the following table, as shown in the last column, and the lefthand side of $(1)$ is therefore the sum of all of the entries in the table, as shown in the lower righthand corner.
$$\begin{array}{c|ccccc|c}
i\backslash j&1&2&3&\ldots&n&\\\hline
1&\frac1{1\cdot1}&&&&&\sum\limits_{j=1}^1\frac1{1\cdot j}\\
2&\frac1{2\cdot1}&\frac1{2\cdot2}&&&&\sum\limits_{j=1}^2\frac1{2j}\\
3&\frac1{3\cdot1}&\frac1{3\cdot2}&\frac1{3\cdot3}&&&\sum\limits_{j=1}^3\frac1{3j}\\
\vdots&\vdots&\vdots&\vdots&\ddots&&\vdots\\
n&\frac1{n\cdot1}&\frac1{n\cdot2}&\frac1{n\cdot3}&\ldots&\frac1{n\cdot n}&\sum\limits_{j=1}^n\frac1{nj}\\\hline
&\sum\limits_{i=1}^n\frac1{i\cdot1}&\sum\limits_{i=2}^n\frac1{i\cdot2}&\sum\limits_{i=3}^n\frac1{i\cdot3}&\ldots&\sum\limits_{i=n}^n\frac1{in}&\sum\limits_{i=1}^n\sum\limits_{j=1}^i\frac1{ij}=\sum\limits_{j=1}^n\sum\limits_{i=j}^n\frac1{ij}
\end{array}$$
At the bottom I've shown the sums of the columns. Of course the sum of the column sums must be the same as the sum of the row sums, since in both cases we're just getting the sum of all of the fractions in the body of the table, so the sum across the bottom must be the same as the sum down the righthand edge. The sum across the bottom is
$$\sum\limits_{j=1}^n\sum\limits_{i=j}^n\frac1{ij}\,,$$
and the sum down the righthand edge is
$$\sum\limits_{i=1}^n\sum\limits_{j=1}^i\frac1{ij}\,,$$
so
$$\sum\limits_{i=1}^n\sum\limits_{j=1}^i\frac1{ij}=\sum\limits_{j=1}^n\sum\limits_{i=j}^n\frac1{ij}\,.\tag{2}$$
The actual names of the index variables aren't important: clearly
$$\sum\limits_{j=1}^n\sum\limits_{i=j}^n\frac1{ij}=\sum\limits_{\ell=1}^n\sum\limits_{k=\ell}^n\frac1{k\ell}\,,$$
where we've renamed $i$ to $k$ and $j$ to $\ell$. Thus, $(2)$ says the same thing as
$$\sum\limits_{i=1}^n\sum\limits_{j=1}^i\frac1{ij}=\sum\limits_{\ell=1}^n\sum\limits_{k=\ell}^n\frac1{k\ell}\,.\tag{3}$$
Similarly, we can rename $k$ to $j$ and $\ell$ to $i$ and see that
$$\sum\limits_{i=1}^n\sum\limits_{j=1}^i\frac1{ij}=\sum\limits_{\ell=1}^n\sum\limits_{k=\ell}^n\frac1{k\ell}=\sum\limits_{i=1}^n\sum\limits_{j=i}^n\frac1{ij}\,,$$
which is exactly what we wanted back at $(1)$.


text:
Q: nonorientability of the projective plane by vanishing 2 form I raised a related question but hope to get some answer using the nonvanishing 2 form definition.
Let P be the real projective plane obtained by identifying antipodal points on the unit sphere of $R^3$.
How to prove that P is nonorientable by showing that any 2 form on P will vanish somewhere?
My idea is to consider the closed curve  $a(t)=(\cos t,\sin t, 0)$  , $0 \leq t \leq \pi$
This curve is closed in P and
 the tangent vectors $a'(0)$ and $a'(\pi)$ are identical.
However, for a vector field V on $a(t)$ defined by $V(a(t))=(0,0,1)$, the tangent vectors at $a(0)$ and $a(\pi)$ differ by a sign.  Also V and $\alpha'(t)$ are always linearly independent.
For any 2 form $u$ on P,
$u(a'(0), V(a(0))=-u(a'(\pi), V(a(\pi))$
Therefore $u$ must vanish somewhere on the curve.
Is the constant vector field V continuous on the curve?
Are my arguments right?

A: If $\omega $ is a nonzero two form on $P$ then define $\pi^\ast \omega$ on $S^2$ where $\pi : S^2\rightarrow P$. Note that $$ \pi^\ast \omega(e_1,e_2)=\omega (d\pi e_1,d\pi  e_2)\neq 0$$ where $\{ e_1,e_2\}$ is indepedent.
This implies that $\pi^\ast \theta$ is nonzero form on $S^2$. And note that $$ (\pi^\ast \omega)_p (e_1,e_2) = (\pi^\ast \omega)_{-p}(-e_1,-e_2)\neq 0 $$
Let $N$ is unit normal on $S^2$ and $\theta = (N,\ )$
Then $(\pi^\ast \omega)\wedge\theta$ is a nonzero three form. If $\{ (1,0,0),e,N \}$ is an orthnormal frame along $c(t)=( 0,\sin\ t,\cos\ t),\ 0\leq t\leq \pi$, and if $e(0)=(0,1,0)$, then $$ (\pi^\ast \omega \wedge \theta )_{c(t)} ((1,0,0),e,N)\neq 0 $$
So $(\pi^\ast \omega)_{c(0)} ((1,0,0),(0,1,0))$ and $(\pi^\ast \omega  )_{c(\pi)} ((1,0,0),(0,-1,0))$ have same sign. So $$e_1=(1,0,0),\ e_2=(0,1,0),\ p=(0,0,1),\ (\pi^\ast \omega)_p (e_1,e_2)  (\pi^\ast \omega)_{-p}(e_1,-e_2)>0  $$
It is a contradiction.


text:
Q: remove last element of a list sml by keeping the list in a val How can I remove the last element in a list in Standard ML?
I have a list defined as:
val list = [1, 4, 6, 8, 9]

and I want to remove the last element and have the list in the val list.

A: Well you have various ways of doing it.

*

*You could take the original list apart, and start building a new list with the elements, until you reach the last element.
fun f [] = ...
  | f [x] = ...
  | f (x::xs) = x :: ...

*Or you could use the List.take function to take the first i elements from the list. Obviously you could use the List.length function to calculate how many elements you wan't to take from the list.
fun h xs = List.take (xs, ...)


text:
Q: How can I reduce the memory used for perm gen in web-app I use tomcat7. My web-app contains:

*

*hibernate

*log4j

*jdom

*upload jar

*mysql driver

*...

the total of lib is 30 jar files. My hoster says: "A lot of memory is allocated to the your program(for Perm gen and heap). Please reduce the amount of memory consumed".
How do I reduce the memory requirements of my program?
How can the reduce the perm gen memory?
please help me.

A: You should probably attach a memory profiler first and see what type of memory is being used and why. The answers to this question list a bunch of profilers you could try.
Heap is all the memory you allocate for storing objects in Java. Every time you use "new" you allocate on the heap and the memory will become garbage collected some time after the last reference to it is cleared. Here are some typical things you might do to reduce heap usage: Switch from an in-memory parsing API to a streaming one, perhaps by using StAX or SAX instead of JDOM. Fix memory leaks or simply longer-than-necessary object retention by cleaning up in a finally block as soon as the object is no longer needed. Optimize SQL queries to make them return only exactly the necessary data to the app, perhaps by adding a max row constraint or a more restrictive where clause. Limit the size of uploads and stream them to temp files on disk instead of keeping them in memory.
Perm gen is "permanent generation". Generally, memory in the perm gen is never freed until the JVM exits. It is mostly used to store loaded classes. So anything you can do to load fewer classes helps here. Here are some ways to load fewer classes: Try not to use multiple versions of the same jars. Try to load jars in the widest context possible, preferring Tomcat's lib directory or a shared lib directory over WEB-INF/lib. Minimize reloading of the webapp because every time you reload a webapp in Tomcat, it doesn't unload the old versions of all classes it simply loads the new ones.


text:
Q: Windows firewall application inbound rules Do I have to have any rules in my inbound and outbound windows firewall app? I think the youngster here applied all these rules to add access...Before I did not use windows firewall app. Had it turned on. I am very good about security. He reset our router twice and had turned on remote in the firewall. I do not leave remote on ever..windows 10.

A: To restore Windows Firewall default settings, open Control Panel and click open Security applet. Here on the left side, you will see a link Restore defaults. Click on it. You will be taken to a window which will allow yout to restore the default firewall settings.


text:
Q: Why i am able to add a new item even if i have a Required field which is hidden inside the New form, Inside the content type I set a field as required inside my SharePoint online site as follow:-

and using PnP i set the field to be hidden in new form, as follow:-
PS C:\WINDOWS\system32> $ctx = Get-PnPContext
PS C:\WINDOWS\system32> $field = Get-PnPField -Identity "LineManager"
PS C:\WINDOWS\system32> $field.SetShowInNewForm($false)
PS C:\WINDOWS\system32> $field.UpdateAndPushChanges($true)
PS C:\WINDOWS\system32> $ctx.ExecuteQuery()

now when i add a new item inside the list i thought that i will get an error since the new form is missing a required field, but i was able to save the item even if the new form is missing a required filed.. so can anyone advice how SharePoint handle this?

A: SetShowInNewForm($false) does not change the column status to "hidden", its status is still shown as Required in the content type.
PnP PowerShell to Hide a Field at Content Type Level:
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com"
$ContentTypeName ="Crescent Project V2"
$FieldName = "ProjectManager" #Internal Name

#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get the Client Context
$Context = Get-PnPContext

#Get the content type
$ContentType = Get-PnPContentType -Identity $ContentTypeName -ErrorAction Stop

#Get the Field from Content Type
$ContentTypeField = $ContentType.Fields.GetByInternalNameOrTitle($FieldName)
$Context.Load($ContentTypeField)
$Context.ExecuteQuery()

#Set Hidden Property of the field
$ContentType.FieldLinks.GetById($ContentTypeField.Id).Hidden = $True
$ContentType.Update($True) #Update Children
$Context.ExecuteQuery()
Write-host -f Green "Field '$($ContentTypeField.Title)' Set to Hidden!"


text:
Q: How to route on multiple components in angular 2 I have a messaging project in angular 2.

Routing Conditions:
1) path: /login , component: LoginComponent
2) path: /inbox , component: InboxMessageComponent
3) path:/inbox/all , "Load InboxMessageListComponent in Right side Box Only",
4) path:/inbox/13 , "Load InboxMessageDetailComponent in Right side Box Only"

So I created two routing module named app-routing.module.ts and inbox-routing.module.ts.
app-routing.module.ts
@NgModule({
    imports: [
        RouterModule.forRoot([
            { path: 'login', component: LoginComponent},
            { path: 'inbox', component: InboxMessageComponent },
            { path: '', component: InboxMessageComponent },
            { path: '**', component: NotFoundComponent }
        ])
    ],
    exports: [RouterModule]
})

inbox-routing.module.ts
@NgModule({
    imports: [
        RouterModule.forChild([
            {path: '/inbox/list',component: InboxMessageListComponent},
            {path: '/inbox/detail/:id',component: InboxMessageDetailComponent}
        ])
    ],
    exports: [RouterModule]
})

app.component.ts
template : '<router-outlet></router-outlet>'<!--This route-outlet will load "LoginComponent/InboxComponent" depending upon the routing. -->

inbox-message.component.ts
template:`
<sidebar-component></sidebar-component>
<router-outlet></router-outlet> <!-- This will load InboxMessageListComponent or InboxMessageDetailComponent -->
`

But the problem is only one  is working at a time. The second one is skipping.
How to Route this kind of project ?

A: You have to declare one main path and childer paths for example:
import {NgModule}             from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {AddProject} from './add-project.component';
import {ViewProject} from './view-project.component';
import {Project} from './charity-project.component';
import {ProjectList} from './charity-project-list.component';

export const routes: Routes = [
    {
        path: 'project', component: Project,
        children: [
            { path: '', component: ProjectList },
            { path: 'add', component: AddProject },
            { path: 'view/:id', component: ViewProject },
            { path: 'edit/:id', component: AddProject }
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})

export class ProjectRoutes { }

In children path you have to declare your
3) path:/inbox/all , "Load InboxMessageListComponent in Left side Box Only",
4) path:/inbox/13 , "Load InboxMessageDetailComponent in Right side Box Only"

A: I assume that inbox is a module of the app application. In this case you should also import the inbox module in module app as follow:
@NgModule({
    imports: [
        RouterModule.forRoot([
            { path: 'login', component: LoginComponent},
            { path: 'inbox', component: InboxMessageComponent },
            { path: '', component: InboxMessageComponent },
            { path: '**', component: NotFoundComponent }
        ]),
        MyInboxModule
    ],
    exports: [RouterModule]
})

See also the link Routing and Natigation in Angular2: https://angular.io/docs/ts/latest/guide/router.html
Hope this helps.


text:
Q: UDP malformed packets I use C# program for client UDP application. Application listens for a connection, and then communicates.
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpClient.Bind(new IPEndPoint(IPAddress.Any, ListenPort));
udpClient.Blocking = true;
int count = 0;

while (count == 0) udpClient.ReceiveFrom(receiveBuffer, ref ePoint);
udpClient.SendTo(data, endPoint);
udpClient.ReceiveFrom(receiveBuffer, ref ep);
...

I use Wireshark to debug the application. The problem is that after sometime my application starts sending malformed STUN packets, and I think that because of that they get rejected by a router on the internet.
The question: is it possible to prevent sending malformed UDP/STUN packets?

A: When your application sends malformed UDP packets, it has a bug. The minimal fragment of your code has only one SendTo call. You can add a check function for the content/length of data.
BTW: UDP is connectionless. I would say, your application waits for a request or a kind of start command not for a connection.


text:
Q: How to unzip multiple files with InnoTools post install? The script sample I have came from http://www.saidsimple.com/daniel/blog/117966/ and it's only set for one zip. I want to be able to unzip any zips in a particular location. I guess one approach might be a wildcard *.zip when the zip name might vary depending on earlier installer selections.
No unzipping occurs. I've missed defining something or procedure is not setup properly. In my use the zips are text files the intended program reads for functions.
[Setup] …
SolidCompression=true
Compression=lzma
CreateAppDir=false
DirExistsWarning=false
ShowLanguageDialog=false
CreateUninstallRegKey=no
#include <idp.iss>

[Files]
Source: "{tmp}\text.net";  DestDir: "{userappdata}\ccc"; Flags: external; Components: abc
Source: "{tmp}\HLNJ.zip";  DestDir: "{userappdata}\ccc"; Flags: external deleteafterinstall; Components: hlnj
Source: "{tmp}\HNJ.zip"; DestDir: "{userappdata}\ccc"; Flags: external deleteafterinstall; Components: hnj

[Code]
const
  SHCONTCH_NOPROGRESSBOX = 4;
  SHCONTCH_RESPONDYESTOALL = 16;
procedure InitializeWizard; ...
begin ...
end;
procedure CurStepChanged(CurStep: TSetupStep); ...
begin
  if CurStep = ssPostInstall then
  begin ...
end;
end;

procedure unzip(ZipFile, TargetFldr: PAnsiChar);
var
 shellobj: variant;
 ZipFileV, TargetFldrV: variant;
 SrcFldr, DestFldr: variant;
 shellfldritems: variant;
begin
 if FileExists('{userappdata}\ccc\HLNJ.zip') then begin
 ForceDirectories('{userappdata}\ccc');
 shellobj := CreateOleObject('Shell.Application');
 ZipFileV := string(ZipFile);
 TargetFldrV := string(TargetFldr);
 SrcFldr := shellobj.NameSpace(ZipFileV);
 DestFldr := shellobj.NameSpace(TargetFldrV);
 shellfldritems := SrcFldr.Items;
 DestFldr.CopyHere(shellfldritems, SHCONTCH_NOPROGRESSBOX or SHCONTCH_RESPONDYESTOALL);
 end;
end;

procedure ExtractSomething(src, target : AnsiString);
begin
 unzip(ExpandConstant(src), ExpandConstant(target));

end;

I would expect one of the zips to be unzipped. But nothing, even in inno log; nothing happens in this section of code. At least deletion of zip works.
EDIT: I'm revisiting an issue I did not solve last year. The problem is getting the Unzip to work. Zip downloads to location but is deleted without unzipping first.
EDIT 2: Might not be the best but appears to work. I've changed my recent code to a working version for Inno 5 (edited the filenames, removed setup.)
; #pragma include __INCLUDE__ + ";" + ReadReg(HKLM, "Software\Mitrich Software\Inno Download Plugin", "InstallDir")
#pragma include __INCLUDE__ + ";" + "c:\lib\InnoDownloadPlugin"

[Setup]
#include <idp.iss>

[Types]
Name: custom;  Description: "Custom installation"; Flags: iscustom

[Components]
Name: conn;  Description: "CC File";  Types: custom; Flags: exclusive
Name: hlnj;  Description: "H L (Recommended)"; Types: custom; Flags: exclusive

[Files]
Source: "{tmp}\text.net";  DestDir: "{userappdata}\ccc"; Flags: external; Components: conn
Source: "{tmp}\HLNJ.zip";  DestDir: "{userappdata}\ccc"; Flags: external deleteafterinstall; Components: hlnj conn

[Code]
const
  SHCONTCH_NOPROGRESSBOX = 4;
  SHCONTCH_RESPONDYESTOALL = 16;
procedure InitializeWizard;
begin
    idpAddFileComp('http://ccc.sourceforge.net/text.net',  ExpandConstant('{tmp}\text.net'),  'conn');
    idpAddFileComp('http://ccc.sourceforge.net/SecurityUpdates/HLNJ.zip',  ExpandConstant('{tmp}\HLNJ.zip'), 'hlnj');

    idpDownloadAfter(wpReady);
end;

procedure CurStepChanged1(CurStep: TSetupStep);
begin
  if CurStep = ssPostInstall then
  begin
    FileCopy(ExpandConstant('{tmp}\text.net'), ExpandConstant('{userappdata}\ccc\text.net'), false);
    FileCopy(ExpandConstant('{tmp}\HLNJ.zip'), ExpandConstant('{userappdata}\ccc\HLNJ.zip'), false);
end;
end;

procedure unzip(ZipFile, TargetFldr: variant);
var
 shellobj: variant;
 SrcFldr, DestFldr: variant;
 shellfldritems: variant;
begin
 if FileExists(ZipFile) then begin
   if not DirExists(TargetFldr) then
      if not ForceDirectories(TargetFldr) then begin
        MsgBox('Can not create folder '+TargetFldr+' !!', mbError, MB_OK);
        Exit;
      end;

   shellobj := CreateOleObject('Shell.Application');
   SrcFldr := shellobj.NameSpace(ZipFile);
   DestFldr := shellobj.NameSpace(TargetFldr);
   shellfldritems := SrcFldr.Items;
   DestFldr.CopyHere(shellfldritems, SHCONTCH_NOPROGRESSBOX or SHCONTCH_RESPONDYESTOALL);

if FileExists(TargetFldr+'\HLNJ.zip') then MsgBox('HLNJ.zip'+ZipFile+
 ' extracted to '+TargetFldr, mbInformation, MB_OK);
 end else MsgBox('HLNJ.zip  does not exist', mbError, MB_OK);
end;

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssPostInstall then
  begin
     unzip(ExpandConstant('{userappdata}\ccc\HLNJ.zip'),ExpandConstant('{userappdata}\ccc'));
  end;
  end;

A: You can not even extract one .zip file.
So step by step first one and then ...
The code is not complete.
So one can only guess what is missing or wrong.
To test the proper functioning of the unzip procedure you should use a simple standard inno-setup program.
If this works you can add extra features and then find the error easier.
Also the used constants "src" and "target" are not visible.
How are they constructed?
unzip(ExpandConstant(src), ExpandConstant(target));

The use of different types of data should be avoided.
AnsiString vs PAnsiChar
procedure unzip(ZipFile, TargetFldr: PAnsiChar);
....
end;

procedure ExtractSomething(src, target : AnsiString);
begin
  unzip(ExpandConstant(src), ExpandConstant(target));
end;

The use of {tmp} will, I suspect, made by the #include idp.iss download.
This code also not exists.
We will simulate this and use a known zip file from a known directory. So we do not need the download of the files.
Information also does not harm but makes it easier to find fault.
I used some MsgBox() for that.
A simple procedure is for the beginning following.

*

*Copy the HLNJ.zip file to C:\HLNJ.zip
and look for a file or folder name part of the HLNJ.zip
so we can test the extraction.

*I use here a file named atext.txt wich is part of my HLNJ.zip
CreateOleObject needs variants so use them instead.
 [Files]
 ; Simulate the download of HLNJ.zip is ok
 ; On the development PC .. on the client PC.
 Source: "C:\HLNJ.zip"; DestDir: "{tmp}";

 ; Now "HLNJ.zip" is in the {tmp} folder so we can use it.
 Source: "{tmp}\HLNJ.zip";  DestDir: "{userappdata}\ccc"; Flags: external deleteafterinstall

[Code]
const
  SHCONTCH_NOPROGRESSBOX = 4;
  SHCONTCH_RESPONDYESTOALL = 16;

....

procedure unzip(ZipFile, TargetFldr: variant);// <--- variant instead of PAnsiChar
var
 shellobj: variant;
 SrcFldr, DestFldr: variant;
 shellfldritems: variant;
begin
 if FileExists(ZipFile) then begin
   if not DirExists(TargetFldr) then
      if not ForceDirectories(TargetFldr) then begin
        MsgBox('Can not create folder '+TargetFldr+' !!', mbError, MB_OK);
        Exit;
      end;

   shellobj := CreateOleObject('Shell.Application');
   SrcFldr := shellobj.NameSpace(ZipFile);
   DestFldr := shellobj.NameSpace(TargetFldr);
   shellfldritems := SrcFldr.Items;
   DestFldr.CopyHere(shellfldritems, SHCONTCH_NOPROGRESSBOX or SHCONTCH_RESPONDYESTOALL);

   if FileExists(TargetFldr+'\atext.txt') then MsgBox('ZipFile '+ZipFile+
     ' extracted to '+TargetFldr, mbInformation, MB_OK);

 end else MsgBox('ZipFile '+ZipFile+' does not exist', mbError, MB_OK);
end;

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssPostInstall then
  begin
     unzip(ExpandConstant('{userappdata}\ccc\HLNJ.zip'),ExpandConstant('{userappdata}\ccc\extracted'));
  end;
end;


text:
Q: Toggle visibility of text box based on status of check box--jquery So I have a list of races for a survery form.  there is a box named 'other specify' for those people that don't meet any of the other criteria. I need a text book to become visible when 'other specify' is checked, and to dissappear when it's not.  I have been able to make the box appear when another is checked, but not dissappear when it was unchecked.  Any help would be greatly appreciated.  Thanks.

Jscript

html
<input type="checkbox" name="race"  id="other"value="other" />Other, specify

<input type="text" name="fname" size="25" maxlength="25" id="otherrace" />

A: Do it this way:
Example: http://jsfiddle.net/patrick_dw/K3kvE/
$('#other').change(function(){
    $('#otherrace').parent().css( 'visibility', this.checked ? 'visible' : 'hidden' );
});

or use display:none instead of visibility:hidden and do this:
Example: http://jsfiddle.net/patrick_dw/K3kvE/1/
$('#other').change(function(){
    $('#otherrace').parent().toggle( this.checked );
});

The way you were using .toggle() was as a "toggle event", which means you were effectively assigning a click event that toggles between executing the functions you pass it.
Because it is the parent of otherrace that is being hidden, you need to traverse up to it using .parent(), then set its visibility property to hidden or visible depending on the state of the checkbox.
The second solution changes from using visibility property to using display so that toggle() can be called in a different manner. The way it is being called now, it toggles between show() and hide(), which set the display property from none to its original setting and back.


text:
Q: microsoft.codeanalysis.csharp 'obj' is null on at least one execution path Такая проблемма: одно из полей в моей модели может быть null. первые два я проверяю.
но на третье (obj.Phone) microsoft.codeanalysis.csharp ругается.
Что нужно сделать, чтоб была возможность передавать null параметр?
command.Parameters.AddWithValue("@Description", obj?.Description);
command.Parameters.AddWithValue("@Address", obj?.Address);
command.Parameters.AddWithValue("@Phone", obj.Phone);

A: Необходимо было добавить дополнительную проверку. Так как бд должна принимать именно DBNull.Value, а не обычный null (в противном случае свалится с ошибкой The parameterized query expects the parameter which was not supplied.)
(object)obj?.Phone ?? DBNull.Value


text:
Q: Latex - Cross referencing showing as question mark for certain figures and tables- IEEE Access-Overleaf \begin{figure*}[h]
    \adjustimage{width=1.2\textwidth,center}{Images/xyz.pdf}
    \caption{my_caption}
    \label{fig:xyz}
\end{figure*}

Using figure*, as otherwise the figure will not properly span over 1 column in a 2 column ieee format.
Fig. \ref{fig:xyz} used for cross referencing.
This issue is with specific figures and table only, though all are declared same way.


text:
Q: Gravitational waves multipole moments I have read about Quadrupolemoments of Gravitational waves and found out that they can be calculated via the following formula:
$$
{I}_{ij}^T = \int \rho(\mathbf{x}) \left[r_i r_j - \frac{1}{3} r^2 \delta_{ij}\right]  d^3 r.
$$
I have understood the derivation given in Bernard Schutz, but I am wondering why we are integrating over $\rho(r)$ and not over $T$, the stress-energy tensor. Is there any reason why only the $T^{00}$ component is used?
Another question I have is that if I'd calculated the monopole, dipole and octupole moments, would their contribution to the perturbation be given by
$$
\bar{h}_{ij}(t,r) = \frac{2 G}{c^4 r} \ddot{F} \quad ?
$$
With F being the monopole, dipole or quadrupole moment. Because I do not see the reason behind the second derivative.