text:
Q: Should I release client in Knex.js? I'm using PostgreSQL with pg. Configuration is as follows:
const { Pool } = require("pg");
const { dbUser, dbHost, database, dbHmac, dbPort } = require("../config");

const dbConfig = {
  user: dbUser,
  host: dbHost,
  database,
  password: dbHmac,
  port: dbPort,
  max: 10,
  idleTimeoutMillis: 30000
 };

 var pool = new Pool(dbConfig);
 module.exports = pool;

At present the pool is used as follows:
app.post("/deleteCognitoUserBasedOnEmail", async function (req, res) {
let isUserAdminRes, email = req.body.email;
try {
   isUserAdminRes = await client.query(
   `select is_admin from end_user where email = $1`,[email]
   );
}
catch (e) {
  client.release();
  console.error("Error occurred : " + e);
  return res.status(500).send({ errorMessage: "Internal Server Error. " + e.message });
}
client.release();
return res
  .status(status)
  .send({ responseMessage });
 }

As one can see I have to release the client everywhere. There are complex functions in my project which take and pass the client as an argument. This way at times tracking client became difficult. I decided to switch to knex.js.
Is there any such restriction in Knex.js? I read about the .destroy() method in knex.js but it is to be used when you won't need the connection. But in my project, the APIs will be hit multiple times throughout the day, every day.

A: In case of knex.js, the numerous examples all omit connection management; it is non-existent in user code. It's just not mentioned in the docs, because you don't do it. Thus, it's documented by absence.
If you prefer hard evidence, here's the code that actually executes queries in knex.js - note how ensureConnection sets up a connection before and releases it after the queries: https://github.com/knex/knex/blob/8cfad286f246aff7455784b51751fdd17ba24c4c/lib/execution/runner.js#L27


text: Q: how do I change my monitor number? I have two monitors and i have set one of the as my primary display but apps and games keep opening on the other monitor. Would this be because my primary monitor is labeled as monitor 2. If so how do i change it and or stop apps from opening on the wrong monitor? I have done some googling but nothing fixes my problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: the (2,2,1) boundedness of a "product" operator This question is from MO: https://mathoverflow.net/questions/191551/the-2-2-1-boundedness-of-a-product-operator
It seems easy but turns out very difficult.
Let $\{E_j\}_{j\in\mathbb{Z}}$ and $\{F_k\}_{k\in\mathbb{Z}}$ be two collections of pairwise disjoint sets in $\mathbb{R}$. Let $C(j,k)$ be a bounded function (e.g. $|C(j,k)|<1$) defined on $\mathbb{Z}^2$. For Schwartz functions $f$ and $g$, consider the operator
$$ T(f,g)=\sum_{j\in \mathbb{Z}}\sum_{k\in \mathbb{Z}}C(j,k)f_j g_k $$
where $f_j$ and $g_k$ are defined by $\hat{f_j}=\hat{f}1_{E_j}$ and $\hat{g_k}=\hat{g}1_{F_k}$.
It seems that $T$ is similar to the product operator $fg$ or a paraproduct. So we may have $\|T(f,g)\|_1\le C\|f\|_2\|g\|_2$ for some absolute constant $C$ and I'm trying to prove it. If the function $C(j,k)$ is independent of one of $j$ and $k$, then I can write the double sum as a product of two single sums and proceed with Cauchy-Schwarz and Plancherel. The real difficulty is that $C(j,k)$ depends on both $j$ and $k$. Any ideas?


text:
Q: Infinite or unknown? If you have $0$ clients on Monday, and $5$ clients on Tuesday, how many times have the number of clients you had grown from Monday to Tuesday?

$A$ - Infinite times
$B$ - Unknown
$C$ - Undefined

A: To ask "how many times have the number of clients you had grown from Monday to Tuesday" is the same to ask what is the value of: $$\dfrac{\mathrm{Clients}(\mathrm{Tuesday})}{\mathrm{Clients}(\mathrm{Monday})}=\frac50$$
In the context of the real numbers, or natural numbers if you prefer, this is undefined. We cannot divide by the actual number zero.
Note that it is common to say "infinity" because $\lim\limits_{n\to0}\frac5n=\infty$. However this simply tells us that the ratio is larger than any other number, it is not an actual number or ratio per se.

A: Go with "c - Undefined".
Translating the word problem to a precise statement I find it to mean the following:

Let $x = 0$ and $y=5$. If $y=kx$, then what is $k$?

Solving this equation would involve division by zero, so the answer is undefined, i.e. there is no such $k$.


text:
Q: Issue with special characters I am facing an issue where special characters are not being printed properly on my webpage.
So, I am making an ajax query, with python script at backend :
$.ajax({
    url: BACK_END_LOC + 'get_search_results',
    data: ({keyword1: keyword1,
            keyword2: keyword2,
            start_time: encodeURI(start_time),
            end_time: encodeURI(end_time),
            dataset: $("#dataset").val()
            }),

    success: function(data) {
        response = eval('(' + data + ')');
        if (response.error_code == 0) {
            render_event_search_results(response.data);
        } else {
        alert('Error_code:' + response.error_code + ', Error_msg:' + response.error_msg);
        }
    },

Python is returning a json object:
def get_search_results(req, keyword1, keyword2, start_time, end_time, dataset):
s = keyword1 + "," + keyword2

# get filtered events
results = get_filtered_events(dataset, keyword1, keyword2, start_time, end_time)

try:
    r = {'error_code': 0, 'error_msg': 'OK', 'data': results}

except Exception, e:
    raise e
    r = {'error_code': 1, 'error_msg': 'Oops'}

return simplejson.dumps(r)

Now, one field of this object has special characters. When I try to print this field on html "alert(gEvents[0].signature)", it is being printed as : \u0432\u0438\u0434\u0435\u043e_storm
How can I get it printed like :видео_storm, which is the actual text.

A: replace
return simplejson.dumps(r)

with
return simplejson.dumps(r,ensure_ascii=False)


text:
Q: How do you use Windows cmd to run JavaScript on specific page? For example, you could go to the login page of Facebook with Chrome, open the console and type
document.getElementById("email").value = "myemailaddress@example.com";
document.getElementById("pass").value = "hunter42";
document.getElementById("login_form").submit();

and it would log you in (assuming correct login information).
How would you do this from the Windows cmd or with a batch file?
Automating logging into a website is my main obstacle for creating an automation where a script sends me a text message when I receive a new grade on my school's web portal.
I've experimented with doing a form submission with cURL in PHP, but the login form is very complex with a lot of hidden fields and whatnot.
Personal project aside, I really want to know if you're able to run a JS Script on a specific web page because there are a ton of circumstances where this could be useful.
Thanks!

A: You're not going to be able to do it from the command line (which includes the run dialog). Your best bet is to find a headless browser framework like Selenium or PhantomJS. I've used PhantomJS, CasperJS, and NightmareJS to much success in the past and would recommend them especially if you're familiar with JavaScript already.


text:
Q: GetType() with "simple" typenames I am trying to read an xml-file where beyond other parameters the type of a field can be given. Example:
<elements>
   <element>
      <elementType>int</elementType>
   <element>
      <elementType>string</elementType>
   </element>
<elements>

Now I want to get the type by using type.GetType(value) where value is "int" or "string" for example. It works with "System.String" or "System.Int32" for example but I do not want the users to enter the exact type. Can this be done in an elegant way (no switch-case-nonsene)?

A: No, you need to have some switch-case-"nonsense" or a dictionary that does the mapping for you.
Those are not .NET types, those are the C# keywords that map to .NET types.

A: To my knowledge, there is no way to do this.  The full list of type aliases can be found here.  You can easily include a dictionary of types to alias string names in your solution.  Here is the current list:

*

*bool
: System.Boolean

*byte
: System.Byte

*sbyte
: System.SByte

*char
: System.Char

*decimal
: System.Decimal

*double
: System.Double

*float
: System.Single

*int
: System.Int32

*uint
: System.UInt32

*long
: System.Int64

*ulong
: System.UInt64

*object
: System.Object

*short
: System.Int16

*ushort
: System.UInt16

*string
: System.String


text:
Q: Finding which function cause the error message while processing a table by processing (Process Full,Process Data) a table (every table) in my cube, I get the following error:
Failed to save modifications to the server. Error returned: 'A function 'MAX' has been used in a True/False expression that is used as a table filter expression. This is not allowed.
A function 'MAX' has been used in a True/False expression that is used as a table filter expression. This is not allowed.
The credentials provided for the SQL source are invalid. (Source at XXXX;XXXX.). The exception was raised by the IDbCommand interface.

How can I find which function cause this error?

A: Query the $SYSTEM.MDSCHEMA_MEASURES DMV, which lists measures in a Tabular model.  The Expression column contains the definition of each measure, and you can use this to find any measures that have the MAX function that was specified in the error message.  SSAS DMVs can either be queried from an MDX query editor window in SSMS or another tool such as Dax Studio.  Dax Studio contains a listing of DMVs, and if you don't already use it I'd recommend looking into this.  You here find more information on this here.  You can also execute your
measure in Dax Studio, which can help with
debugging it.  You will also want to verify that the account you're using has the proper permissions on the SQL Server objects used by your Tabular model.


text:
Q: Kernel of a group homomorphism Is it true that for a group homomorphism $\phi: G\to H$, $\phi(e_G)$ necessarily equals $e_H$?

A: Notice that since $\phi$ is a homomorphism, $$\phi(e_{G})=\phi(e_{G}\star_{G} e_{G})=\phi(e_{G})\star_{H}\phi(e_{G})$$
Can you do it from here?

A: Yes.
$\phi(x)=\phi(x*_1e_G)=\phi(x)*_2\phi(e_G) ,\  \forall x\in G$
Hence $ \phi(e_G) $ is identity in H.
Thus $\phi(e_G)=e_H$


text:
Q: Cannot instantiate implementation type AuditRepository[T] for service type IAuditRepository[T] I'm getting an error message when trying to add dependency injection:
Cannot instantiate implementation type AuditRepository[T] for service type IAuditRepository[T]
I've researched all the possible reason that can cause this error, including an abstract class for the implementation, but this does not apply to me.
Program.cs
builder.Services.AddScoped(typeof(IAuditRepository<>), typeof(AuditRepository<>));

IAuditRepository.cs
public interface IAuditRepository<T> where T : class
{
   Task<Audit> GetByEntity(T entity);
}

AuditRepository.cs
public class AuditRepository<T> : IAuditRepository<T> where T : class
{
   private readonly AppDbContext context;

   public AuditRepository(AppDbContext context)
   {
      this.context = context;
   }

   public async Task<Audit> GetByEntity(T entity)
   {
      ...
   }
}

Note: I have many entities so it would not be practical to do something like:
builder.Services.AddScoped(typeof(IAuditRepository<CustomerAccount>), typeof(AuditRepository<CustomerAccount>));
builder.Services.AddScoped(typeof(IAuditRepository<Quote>), typeof(AuditRepository<Quote>));
builder.Services.AddScoped(typeof(IAuditRepository<Address>), typeof(AuditRepository<Address>));
....
....

A: I found the issue...the the DI code was effectively being done twice. The code below must've been the first time it got registered. And then my code registered explicitly a 2nd time. Additionally the code below was not registering it as a generic.
private static IEnumerable<Assembly> Assemblies
    {
        get
        {
            var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;
            List<Assembly> assemblies = new List<Assembly>
            {
                Assembly.LoadFrom(Path.Combine(path, "Business.dll")),
                Assembly.LoadFrom(Path.Combine(path, "DataAccess.dll")),
                Assembly.LoadFrom(Path.Combine(path, "WebServices.dll")),
                Assembly.LoadFrom(Path.Combine(path, "DataAccess.dll")),
            };
            return assemblies;
        }
    }

public static IServiceCollection RegisterCustomServices(this IServiceCollection services)
    {
        Assemblies
            .SelectMany(a => a.GetTypes().Where(t => t.IsClass && !t.IsAbstract)).ToList()
            .ForEach(classType => classType
                .GetInterfaces()
                .Where(interfaceType => interfaceType.Namespace.EndsWith(".Interfaces", StringComparison.InvariantCulture)).ToList()
                .ForEach(interfaceType => RegisterInterface(services, interfaceType, classType)));


text:
Q: jQuery.ajax - Duplicate Content After Posting Data Back To The Same Page Problem 1: My content overlaps itself twice after I post some data back to the same page using jQuery.ajax(). The reason why I'm posting data back to the same page is because I need to pass my JavaScript values to the PHP side.
Question: How do I edit my code such that there will only be 1 copy of my content, before and after posting of data to the same page?

Problem 2: You may have noticed there is a $("#test").html(data); in my bingo function and a  in my body. I can't seem to remove them if not the passing of Javascript values to the PHP side would not work as shown by my print_r().

Question: Is there any way I can remove them but still pass my values from JavaScript to PHP using jQuery.ajax()?

bingo.php

            <?php
            if (!isset($_POST['varA']) && !isset($_POST['varB']))
            {
            ?>

                <?php
            }
            else
            {
                print_r($_POST['varA']);
                echo " - ";
                print_r($_POST['varB']);
            }
            ?>

        <input type="text" value="meow"/>

A: Omg that is so messy! Try the following code anyway:
<?php
if (isset($_POST['varA']) && isset($_POST['varB'])) {
    print_r($_POST['varA']);
    echo " - ";
    print_r($_POST['varB']);
} else {
?>

        <input type="text" value="meow"/>

<?php
}
?>

A: If you wish to keep your ! in your conditions, you can do it the other way round also.
<?php
if (!isset($_POST['varA']) && !isset($_POST['varB'])) {
?>

        <input type="text" value="meow"/>

<?php
}
else {
    print_r($_POST['varA']);
    echo " - ";
    print_r($_POST['varB']);
}
?>


text:
Q: Storing a 'Client' in a struct on Arduino I am trying to store a Client into a struct called IRCClient.
The compiler gives me:
ArduinoIRCd_pde.cpp.o: In function `global constructors keyed to mac':
ArduinoIRCd_pde.cpp:167: undefined reference to `Client::Client()'
collect2: ld returned 1 exit status

Here's the struct:
struct IRCClient {
    char *nick;
    char *user;
    char *host;
    char *name;
    int lastping;
    Client client;
};

A: From the Client documentation, it seems that the Client class does not have a default constructor (ie with no parameters).
You have to specify an IP and a TPC port where to connect :
byte server[] = { 64, 233, 187, 99 }; // Google

Client client(server, 80);

A: As it was already written, the Client class seems to need parameters when it is constructed. So I see 2 possibilities to store a Client instance in your structure.
Actually on my Arduino setup (1.0) it seems I cannot directly use Client, Client is a pure virtual class, it was replaced by EthernetClient.
1. Using EthernetClient (best one in my mind, but with Arduino 1.0)
Depending on your needs, maybe EthernetClient is better. It has a default constructor.
http://arduino.cc/en/Reference/EthernetClient
2. Using a constructor in your struct:
struct IRCClient {
    char *nick;
    char *user;
    char *host;
    char *name;
    int lastping;
    Client client;
    IRCClient(byte * server, int port) : client(server,port) { }
};

byte server[] = { /* ip address */ };
IRCClient ircClient(server, 80);

(I could not test this solution, as I said earlier, Client is a pure virtual class in Arduino 1.0).
3. Using pointers
You can have a structure with a pointer to your Client:
struct IRCClient {
    char *nick;
    char *user;
    char *host;
    char *name;
    int lastping;
    Client *client;
};

And then, when you create your client, you store it by getting its address:
byte server[] = { /* ip address */ };
Client client(server, 80);
IRCClient ircClient;
ircClient.client = &client;

However be very careful while doing that: if your client is destroyed (end of a function scope, ...) ircClient.client will point toward... nothing.
And you need to be familiar with pointers to correctly manipulate the stored object.


text:
Q: Is it safe to use fastcall in a shared library? For example, let's say I have a function that will swap bytes in a 32 bit value for you:
uint32_t byte_swap(uint32_t in);

Well it seems silly to push that 32-bit value onto the stack and pop it off again, especially if we're going to be calling this function a lot, so let's pass it in through ECX:
#if __FASTCALL_SUPPORTED_   /* Whatever this may be */
#define FASTCALL __attribute__((fastcall))
#else
#define FASTCALL
#endif

uint32_t FASTCALL byte_swap(uint32_t in);

Now my question is, is it safe to compile that function into a shared library for distribution?  If the user uses a different compiler to compile their program and links against this, will the function still be called properly?

A: __attribute__((fastcall)) is a gcc extension; as such, it may not be usable if the caller is not using gcc as well. Moreover, in the sample you gave, if __FASTCALL_SUPPORTED_ is not defined, you'll end up with a call with the wrong calling convention - bad idea.
One way to deal with this may be using a fallback wrapper. In your .c file:
#include "foo.h"

uint32_t FASTCALL byte_swap(uint32_t in) {
    /* code ... */
}

uint32_t byte_swap__slowcall(uint32_t in) {
    return byte_swap(in);
}

And in your .h file:
#if __FASTCALL_SUPPORTED_   /* Whatever this may be */
#define FASTCALL __attribute__((fastcall))
#else
#define FASTCALL
#define byte_swap byte_swap__slowcall
#endif

uint32_t FASTCALL byte_swap(uint32_t in);

Also, note that on Linux, a fast byteswap implementation is available in <byteswap.h> as bswap_32. On x86 machines, it will compile down to inline assembler, and a single instruction on high enough -march= settings.


text:
Q: Database is not being automatically created in Spring boot I have an Spring boot Api that uses jpa with postgresql, and is supossed to automatically create the the tables when i run the Application.
But the following error messages appears:
>
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.globalsys.apicep.model.Cep.Cidade in com.globalsys.apicep.model.Cidade.ceps
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:844) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:795) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:53) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1693) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1661) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:286) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.1.jar:5.3.1]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.1.jar:5.3.1]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.1.jar:5.3.1]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

This is my application.properties
server.port=8080
spring.datasource.url=jdbc:postgresql://localhost:5432/dbcep
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=romulo
spring.jpa.open-in-view=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

A: So good news! The problem is a reference in the mapped by properties that i thought is nothing wrong at first.
In the OneToMany anootation i put in this way referencing the table itself!
@OneToMany(mappedBy = "Cidade", cascade = CascadeType.ALL)
    private List<Cep> ceps;

Turns out you can not refer to the table itself! Instead you need to refer the property in the other side of relationship that is the owner of relationship!
 @ManyToOne
    private Cidade cidade;

In the Cep class model!


text:
Q: AngularJS tooltips/popovers with ng-repeated content I am using Foundation 5 with AngularJS in my project. I have the following use case:

*

*Click on a 'div' which is inside an ng-repeat.

*Fetch a list specific to that div in response to the click.

*Show that list in an ng-repeat in a tooltip/popover of that div(which was clicked).

How do I go about generating that tooltip?
I tried:

*

*this library but I encountered some issues as mentioned in this question.

*angular-foundation, but the popovers here don't have a popover-template functionality(like in ui.bootstrap).

AND I don't want to use ui.bootstrap because I am using Foundation 5 (Its a bad idea, right?).

A: Cannot say what "approach" exactly you need, in your particular case (fetch a list of something after something else has been clicked) - but you can always generate the content of the tooltip on the fly :
TEST

function :
$scope.buildToolTip = function() {
   var list = ''
   for (var i=0;i<3;i++) {
      list+='
element #'+i+'
';
   }
   return '
'+list+'
'
}

now use the outcome of "Fetch a list specific to that div in response to the click" instead of the demonstration loop - you have the fetched list stored in a $scope variable somewhere anyway, I assume?
http://plnkr.co/edit/3P9PSN2FsRyViCVlqReg?p=preview


text:
Q: Codesign error - SecKey API returned: -67671 When I try to run codesign of a particular app, I get an error:
/Users/xxx/xxxxxx/xxxxx.app: replacing existing signature
SecKey API returned: -67671 (null)/Users/xxx/xxxxxx/xxxxx.app
unknown error -1=ffffffffffffffff
Any idea what this means?

A: In my case needed to do the following:

*

*in the Keychain Access right click on the Private Key (if it is not seen, expand the Certificate by clicking on the little triangle near it)

*Choose Get Info

*Go to Access Control tab, choose "Allow all applications to access this item"

*Click Save changes button, input the username/passwords if prompted
Also note the Certificate/Key could be not only in you login keychain, but also in the System keychain. Do the same for both if required.


text:
Q: Vertical scroll add/remove class between two points I have got a basic code working on my local machine
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">

$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll >= 620) {

    $("#slidetwo").addClass("fixed");
} else {
     $("#slidetwo").removeClass("fixed");
    }
});

However i want the class to be removed if scroll after a certain point how is this doable - I have added (scroll <= 1000)  in hope but failed
if (scroll >= 620) (scroll <= 1000) {

Thanks

A: You need to use and operator in if statement:
if (scroll >= 620 && scroll <= 1000) {

Complete Code.
$(window).scroll(function() {
 var scroll = $(window).scrollTop();
 if (scroll >= 620 && scroll <= 1000)
  $("#slidetwo").addClass("fixed");
 else
  $("#slidetwo").removeClass("fixed");
});


text:
Q: Plotting particles with coordinates from a multidimensional array I'm pretty new to Python which is why I wasn't able to solve my problem even though similar questions have been asked and there are plenty of documentations about this topic out there. So please have mercy with a programming-newbie.:)
Actually all I want to do is plotting particles in a movie-like style. I have all the coordinates for every particle and every step already listed in a list which contains two-dimensional arrays: one for every time step contains further arrays with the coordinates.
Later we are planning to put geometrical shapes into the flow to simulate how vortexes ect. emerge.
I've managed to plot my results with matplotlib in a for-loop which is working but not looking smoothly. Perfect would be if I was able to save the result as a video.
I greatly appreciate any help!


text:
Q: Is it possible to convert ReactJs JS(Virtual DOM) to JSX? i.e) ES5 to ES6 I have done reactjs script using virtual DOM method. Now i need to convert it to JSX format. Is there any tool or plugin is available for this conversion.
Example :
From
var profile = React.createElement("div", null,
 React.createElement("img", { src: "avatar.png", className: "profile" }),
 React.createElement("h3", null, [user.firstName, user.lastName].join(" "))
);

to
var profile =

{[user.firstName, user.lastName].join(' ')}

;

Note : Babel official website is converting JSX to JS.

A: Check react-codemod.
That package includes a script called create-element-to-jsx that converts .createElement calls to jsx elements.
You can use it like this (quoting from the link):
jscodeshift -t react-codemod/transforms/create-element-to-jsx.js <path>


text:
Q: Почему из #value первого поля в форме вырезаются пробелы? Есть форма и кнопка выше нее. При нажатии на кнопку выводятся значения для первого и второго (нулевого и первого) полей - email и username.

document.querySelector("#validate").addEventListener("click", function(event) {
  console.log(document.querySelector("form").elements[0].value);
  console.log(document.querySelector("form").elements[1].value);
});
<button id="validate">Validate Form!</button>
<form action="" method="POST" autocomplete="off">

Email

    <input type="email" name="email" id="email">

Username

    <input type="text" name="username" id="username">

Password

    <input type="password" name="password" id="password">

Password Confirmation

    <input type="password" name="password-conf" id="password-conf">

    <input type="submit" name="commit" value="Submit">
    <input type="submit" name="commit2" value="Submit2">
    <input type="submit" name="commit3" value="Submit3">

</form>

Вопрос: почему, если ввести и в первое и во второе поля пробелы, то результат для первой строки - ничего, а для второй - эти введенные пробелы?
Замечание: даже если строка не содержит только пробелы, а начинается с пробелов, а заканчивается каким-нибудь набором символов, то пробелы из начала первой строки все равно исчезают.
Браузер - Chrome 58.

A: type="email" https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email

Any trailing and leading whitespace is removed from each address in
  the list.
Пробельные символы в начале и в конце каждого адреса автоматически удаляются.


text:
Q: Getting error while run angular/compiler-cli command Try to run following command for implement AOT in angular2
npm install @angular/compiler-cli typescript@next @angular/platform-server @angular/compiler

but gives me error, also can you give me step by step how i compile application for AOT
Also how i can run the node_modules/.bin/ngc -p tsconfig-aot.json
command
UNMET PEER DEPENDENCY typescript@2.1.0-dev.20161012 invalid
npm WARN @angular/compiler-cli@0.6.4 requires a peer of typescript@^2.0.2 but none was installed.
npm WARN @angular/compiler-cli@0.6.4 requires a peer of @angular/core@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/core@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/common@2.0.2 but none was installed.
npm WARN @angular/platform-server@2.0.2 requires a peer of @angular/platform-browser@2.0.2 but none was installed.
npm WARN @angular/compiler@2.0.2 requires a peer of @angular/core@2.0.2 but none was installed.
npm WARN @angular/tsc-wrapped@0.3.0 requires a peer of typescript@^2.0.2 but none was installed.

A: This error is caused by unmet dependencies. You should install a newer version of angular2.
After that, run the command again.
Browse root path of your project and run the command below.
node_modules/.bin/ngc -p tsconfig-aot.json

You can get a detailed explanation from here.


text:
Q: XML Parsing in phone7 How to parse the elements of only Main_Screen node in the below XML.
<?xml version="1.0" encoding="utf-8" ?>

<plist version="1.0">
<Main_Screen>
        <row>
            <btn_name>Buyer Programs</btn_name>

        </row>
        <row>
            <btn_name>Seller�s Programs</btn_name>

        </row>
<Main_Screen>
<Buyer>
       <row>
           <btn_name>buy_bac</btn_name>

       </row>
       <row>
           <btn_name>buy_hme</btn_name>

     </row>
<Buyer>
<Seller>
   <row>
       <btn_name>buy_bac</btn_name>

   </row>
   <row>
       <btn_name>buy_hme</btn_name>

 </row>
<seller>
<Lender>
   <row>
       <btn_name>buy_bac</btn_name>

   </row>
   <row>
       <btn_name>buy_hme</btn_name>

 </row>
<lender>
<abcd>
   <row>
       <btn_name>buy_bac</btn_name>

   </row>
   <row>
       <btn_name>buy_hme</btn_name>

 </row>
<abcd>

</plist>

I tried the below code but all elements are getting parsed i want to parse only the elements below main_screen node,
 XDocument loadedData = XDocument.Load("HelpScreenData.xml");

        var data = (from query in loadedData.Descendants("row")

                    select new tutstat
                    {
                        btn_name = (string)query.Element("btn_name"),
                        strng = (string)query.Element("strng"),
                    }).ToList();

plz direct me,thank u!

A: It sounds like it's as simple as using Root.Element("Main_Screen") before the call to Descendants:
XDocument loadedData = XDocument.Load("HelpScreenData.xml");

var data = loadedData.Root
                     .Element("Main_Screen")
                     .Descendants("row") // Or .Elements("row")
                     .Select(x => new tutstat
                             {
                                btn_name = (string) x.Element("btn_name"),
                                strng = (string) x.Element("strng"),
                             })
                     .ToList();

I've changed this from a query expression to a simple stack of method calls as the query expression was only adding noise.
You should also fix all your names to comply with .NET conventions and be more explanatory.


text:
Q: What were the C idioms for polymorphism and inheritance before the concepts were made explicit? Suppose I have the usual class Animal abstract class and the class Dog : public Animal class Cat : public Animal that makes it a concrete class you can instantiate an object from. Suppose further that you have a function foo(Animal a), taking either cats or dogs as objects. C++ used to, in the early days, compile to C, and would build a vTable maintaining the objects there.
But a student of mine asked me this question: before these concepts were usual talk among programmers, how did they actually do it in their day-to-day coding in C? What was (is?) the idiomatic way to program these concepts in C?
I've sifted through the linux kernel, and other OSS projects, but I haven't been able to find a clear pattern: sometimes it's unions (for different structs), sometimes it's function pointers, etc. but I would like a straight answer from knowledgeable people in industry who've done and have a lot of experience with C.
In one sentence: what is idiomatic C for inheritance and polymorphism?

A: Simple programs, such as those written for school assignments, implement polymorphism using a structure that consists of a union and optionally an enum as the type discriminators. Each "method" then contains a switch statement that calls into the function appropriate for the subtype. Obviously this doesn't scale to more systems that require being able to add subclasses without changing the definition of the base class.
Polymorphism itself is easily expressed with function pointers that receive an explicit self argument. Open-ended inheritance can be achieved with the "inherited" structure embedding its superclass:
struct base {
   // ... members here ...
};

struct inherited {
  struct base base;
  // ... inherited members here ...
};

Pointers to struct inherited may be safely cast to struct base *, a practice explicitly blessed by the C standard. These casts are typically hidden behind macros, which may even perform runtime type checking, where possible.
Implementing this is quite unwieldy, since there are no templates, no automatic invocation of destructors, no exceptions, and no STL. In other words, error handling and destructor invocation must be carefully handled by the programmer, and type variance must be handled either by callbacks at run-time (consider the difference between std::sort() and qsort()) or by hard to maintain preprocessor tricks.
Despite the difficulties, it is certainly possible to implement a meaningful subset of C++ functionality in C, and even a semblance of simplicity of C in the process. To study real-world examples of this approach being taken to production level, take a look at the implementation of the CPython interpreter, or the glib object system used by GTK+.

A: I saw code that used #defines to create abstract names in the source and include files.  for example, the same routine might be re-used to deal with bytes, shorts, ints, floats, and doubles.  The code was messy and hard to understand.

A: Before the advant of object oriented programming, applications were using procedural code where functionality was "encapsulated" in a hierarchy of functions with the ones at the top of the hierarchy working with abstractions and becoming more and more concrete and detailed as we go down the hierarchy. Some API provide ways to create structures that can only be manipulated via handles. Example: In C, file handles hide the details of dealing with files.
As for doing OO in C, I believe it was never a viable option without proper language support with the appropriate constructs. What you would get was not worth the pain involved in faking OO with pointers to functions.


text:
Q: PDFBox API: How to change font to handle Cyrillic values in an AcroForm field I need help with adding Cyrillic value to a field using the PDFBox API. Here is what I have so far:
PDDocument document = PDDocument.load(file);
PDDocumentCatalog dc = document.getDocumentCatalog();
PDAcroForm acroForm = dc.getAcroForm();
PDField naziv = acroForm.getField("naziv");
naziv.setValue("Наслов"); // this part right here
naziv.setValue("Naslov"); // it works like this

It works perfect when my input is in Latin Alphabet. But I need to handle Cyrillic inputs as well.
How can I do it?
p.s. this is the exception I get:
Caused by: java.lang.IllegalArgumentException: U+043D ('afii10079') is not available in this font Helvetica encoding: WinAnsiEncoding

A: The code below adds an appropriate font in the acroform default resource dictionary, and replaces the name in the default appearances. PDFBox recreates the appearance stream of the fields using the new font when you call setValue().
public static void main(String[] args) throws IOException
{
    PDDocument doc = PDDocument.load(new File("ZPe.pdf"));
    PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
    PDResources dr = acroForm.getDefaultResources();

    // Important: the font is Type0 (allows more than 256 glyphs) and NOT SUBSETTED
    PDFont font = PDType0Font.load(doc, new FileInputStream("c:/windows/fonts/arial.ttf"), false);

    COSName fontName = dr.add(font);
    Iterator<PDField> it = acroForm.getFieldIterator();
    while (it.hasNext())
    {
        PDField field = it.next();
        if (field instanceof PDTextField)
        {
            PDTextField textField = (PDTextField) field;
            String da = textField.getDefaultAppearance();

            // replace font name in default appearance string
            Pattern pattern = Pattern.compile("\\/(\\w+)\\s.*");
            Matcher matcher = pattern.matcher(da);
            if (!matcher.find() || matcher.groupCount() < 2)
            {
                // oh-oh
            }
            String oldFontName = matcher.group(1);
            da = da.replaceFirst(oldFontName, fontName.getName());

            textField.setDefaultAppearance(da);
        }
    }
    acroForm.getField("name1").setValue("Наслов");
    doc.save("result.pdf");
    doc.close();
}

Update 4.4.2019: to save some space, it may be useful to remove the appearance before calling setValue:
acroForm.getField("name1").getWidgets().get(0).setAppearance(null);

to check whether there are unused fonts in the AcroForm default resources, see this answer.
Update 7.4.2019: you may experience poor performance if the font is very large (e.g. ArialUni) and many fields are to be set (PDFBOX-4508). In that case, save and reload the file before calling setValue.
To find out whether a font supports an intended text, call PDFont.encode() and check for IllegalArgumentException.


text:
Q: How can you ask for user input when also using a text file in unix shell in c++? I run my code using a.out < file.txt and I read all of the file when I try to use cin >> variable to ask the user for input it does nothing.

A: When you invoke your program with a.out < file.txt, you're asking the shell to pipe the file.txt content in as the standard input for a.out instead of letting the keyboard provide standard input.  If that doesn't suit you, then add a command line argument to specify the filename, use an ifstream to open it and read from that instead of cin, the use cin for the keyboard input.
For example:
int main(int argc, const char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "usage: " << argv[0] << " <filename>\n";
        exit(1);
    }
    const char* filename = argv[1];
    if (std::ifstream in(filename))
    {
        // process the file content, e.g.
        std::string line;
        while (getline(in, line))
            std::cout << "read '" << line << "'\n";
    }
    else
    {
        std::cerr << "unable to open \"" << filename << "\"\n";
        exit(1);
    }
    // can still read from std::cin down here...
}

A: If you need additional user input after your stdin, you have to open your controlling terminal which is convinently named "/dev/tty". Example:
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
  ifstream tin("/dev/tty");
  ofstream tout("/dev/tty");

  tin.tie(&tout);

  while (true) {
    string input;

    tout << "> ";
    getline(tin, input);

    if (input == "quit")
      break;
  }

  return 0;
}

To convince yourself that above will not read redirected file, a simple test:
$ echo "quit" | ./a.out
>


text:
Q: How to return to the 1st VC from the last navigated VC I am using only segue to navigate in my app.
I just like to know if I navigate from 1st-VC to V2 to V3 then to 4th-VC, how can I navigate back to 1st VC from 4th-VC directly without going back to V3, V2 then VC1?
Thanks.
In my current app, I use this to navigate back to the previous VC
(using unwind):
@IBAction func unwindToViewController (sender: UIStoryboardSegue){

    }

Is this good practice?

A: you may use below code -
func popToRoot() {
        self.navigationController?.popToRootViewControllerAnimated(true)
}

A: You can create IBAction in 4th-VC and call popToRootViewControllerAnimated method.

A: I know of three options:
The first (and probably the best) is to use an unwind segue. They are greatly explained in details here (SO question)
The second one, if your VC1 is the root view controller, is to simply use this line in your VC4:
self.navigationController?.popToRootViewControllerAnimated(true);

The last one is to manually set the ViewControllers stack to the state that you want (note, that you're going to get references to your VCs somehow). For example, "go three VCs back" (sorry, autocomplete suddenly broke down in Xcode for Swift, so Objective-C only):
UINavigationController *navigationController = self.navigationController;
NSMutableArray *newVCs = [navigationController.viewControllers mutableCopy];

//This part would be more elegant in Swift, of course
[newVCs removeLastObject];
[newVCs removeLastObject];
[newVCs removeLastObject];

[navigationController setViewControllers:newVCs animated:YES];

The first solution is the best, because it is the most flexible. And it doesn't make you hardcode your VCs stack. But it really depends on your requirements. The second one is by far the easiest to implement, so if you need to go back to the root VC, it is the way to go. As for the third one, it's somewhat easier to implement than the first one, but I think that the first one is the most correct.


text:
Q: add code snippet in magento core I'm running magento 1.4 and I'm trying to display an overlayer banner on all the pages in my magento store. In which file should I add the code snippet for the banner so that the it gets displayed on all pages?
BTW: the code snippet is actually some a short php if function + an OpenX Javascript Tag

A: From this search:

*

*Go to /admin/cms_block/ and add a block. Remember the identifier.

*In your code add <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('identifier')->toHtml() ?>
There you go…

A: For javascript to be included on every page have a look at page.xml layout <default> section. For PHP code see which blocks are included on the page and create a block after (or before) one of them


text:
Q: Bring up but don't assign address with Netplan I have an interface I want to bring up at boot but otherwise leave unconfigured. No DHCP, no static IP. Is there a way to do this with Netplan in 18.04?
I tried the following (where enp10s0f1 is the device in question) but it still just leaves the interface down:
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
  version: 2
  renderer: networkd
  ethernets:
    enp10s0f0:
      dhcp4: yes
    enp10s0f1:
      dhcp4: no

The reason this matters is I have LXD containers using that interface via macvlan bridging, so the interface needs to be up, but it doesn't need (and I'd rather not have) an IP address on the host. I'd really prefer not to need to remember ip link set up enp10s0f1 when I reboot.
Update:
I found this bug report in Netplan's Launchpad that looks related, but as best as I can tell, it's for the opposite case: tell Netplan to configure an interface but don't automatically bring it up. However, it does sort of suggest that what I want to do isn't possible yet either. Is that the case? Is there any workaround besides abandoning Netplan?

A: Edit, mid-2019: The bug that caused this has been fixed.
With this bug fix, it is now possible to have an interface brought up without an address by adding it with an empty configuration: {}.
Using the example from the question, doing this with enp10s0f1 would look like this:
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
  version: 2
  renderer: networkd
  ethernets:
    enp10s0f0:
      dhcp4: yes
    enp10s0f1: {}

Original answer:
This is in fact a bug in Netplan: bug #1728134, bug #1763608. One of the netplan devs has acknowledged the latter, but it's not clear whether or not a fix will be provided.
One workaround would be to manually create a systemd unit to bring the interface up. Create a file /etc/systemd/system/manual-iface.service with the following contents:
[Unit]
Description=Service to bring up/down unconfigured nic enp10s0f1
After=network.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/sbin/ip link set enp10s0f1 up
ExecStop=/sbin/ip link set enp10s0f1 down

[Install]
WantedBy=multi-user.target

Then, enable it to run at boot:
sudo systemctl enable manual-iface.service

And you're good to go. You should see enp10s0f1 comes up automatically next time you boot.
Alternatively, if you don't want to do that, reverting to ifupdown is still an option, as the question states. Fallback is described here. To summarize, install ifupdown, and then you can do the configuration using the traditional /etc/network/interfaces (which is well-documented across the web).

A: As a workaround, if only IPv4 address is required, IPv6 can be configured via DHCP which automatically enables the interface:
# cat /etc/netplan/10-eth1.yaml
network:
  version: 2
  renderer: networkd
  ethernets:
    eth1:
      dhcp4: false
      dhcp6: true
      optional: true


text:
Q: Glitch when interactively dismiss a modal view controller I am using UIViewControllerAnimatedTransitioning and UIPercentDrivenInteractiveTransition to interactively dismiss a modally presented view controller. Nothing too fancy. But I noticed there is occasionally a small glitch just when the interaction starts. It becomes more noticeable if it is animated with .curveEaseOut option. Same thing happens with some online tutorial I am following (https://www.thorntech.com/2016/02/ios-tutorial-close-modal-dragging/). You can see the glitch in the gif when I drag it down for the first time. Any suggestions?

MyDismissAnimator
class SlideInDismissAnimator: NSObject, UIViewControllerAnimatedTransitioning {

    // ...

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

        guard let toVC = transitionContext.viewController(forKey: .to),
        let presentedVC = transitionContext.viewController(forKey: .from) else {return}

        let presentedFrame = transitionContext.finalFrame(for: presentedVC)
        var dismissedFrame = presentedFrame
        dismissedFrame.origin.y = transitionContext.containerView.frame.size.height

        transitionContext.containerView.insertSubview(toVC.view, belowSubview: presentedVC.view)
        }
        let duration = transitionDuration(using: transitionContext)

        UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
            presentedVC.view.frame = dismissedFrame
        }) { _ in
            if transitionContext.transitionWasCancelled {
                toVC.view.removeFromSuperview()
            }
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}

MyInteractor
class SwipeInteractionController: UIPercentDrivenInteractiveTransition {

    var interactionInProgress = false
    private var shouldCompleteTransition = false
    private weak var viewController: UIViewController!

    init(viewController: UIViewController) {
        self.viewController = viewController
        super.init()
        let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
        viewController.view?.addGestureRecognizer(gesture)
    }

    @objc func handleGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
        let translation = gestureRecognizer.translation(in: gestureRecognizer.view!.superview!)
        var progress = (translation.y / viewController.view.bounds.height)
        progress = CGFloat(fminf(fmaxf(Float(progress), 0.0), 1.0))

        switch gestureRecognizer.state {
        case .began:
            interactionInProgress = true
            viewController.dismiss(animated: true, completion: nil)

        case .changed:
            shouldCompleteTransition = progress > 0.3
            update(progress)

        case .cancelled:
            interactionInProgress = false
            cancel()

        case .ended:
            interactionInProgress = false
            if shouldCompleteTransition {
                finish()
            } else {
                cancel()
            }
        default:
            break
        }
    }
}

A: For interative dissmiss, the animation delay must be greater than 0 on iOS 11.
ref: https://github.com/jonkykong/SideMenu/blob/master/Pod/Classes/SideMenuTransition.swift#L510

A: I'm pretty sure this is a bug with the UIPercentDrivenInteractiveTransition, but I was able to resolve this:
The bug occurs when the progress is not updated as soon as possible after dismiss() is called. This happens because the pan gesture recognizer's .changed state is only triggered as you're dragging. So if you're dragging slowly, between the time .begin is called and the first .changed is called, the dismiss transition will start to animate.
You can see this in the simulator by very slowly dragging on the view, pixel by pixel, until .begin is called. As long as .changed doesn't  get called again, the transition will actually complete itself and you'll see the view animate all the way down and transition complete.
However, simply calling update(progress) after .dismiss() doesn't work either, I believe because the dismiss animation hasn't begun yet. (until the next runloop or something)
My "hack" solution was to dispatch async with a very tiny amount of time, effectively setting the progress and halting the animation before it begins.
case .began:
    interactionInProgress = true
    viewController.dismiss(animated: true, completion: nil)
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) {
        self.update(progress)
    }

A: If you use custom dismissal transition animator you should not add view of toViewController as subview to container view of transitionContext. It's already in hierarchy. That bug took place im my same case, but i used both dismissal and appear custom animations. I think for only custom dismissal animation this takes place, too.
Delete this line:
transitionContext.containerView.insertSubview(toVC.view, belowSubview: presentedVC.view)

All you should do this case - change frame of fromViewController in animation block to what you want.

A: I solved the same issue by "embracing" the glitch.
The problem is the old view is moved down a bit before the interactor kicks in. Then the control is given to the interactor that resets the position to the beginning of the animation moving it back.
If the interactor begins the animation at the same position where the old view is when it is given control, then the glitch is almost un-noticeable.
To do this I removed the easing curve parameter from UIView.animate, and applied my own easing function to the progress before calling update(progress).
My custom easing function has an offset parameter that compensate the movement happening before the interactor takes control.
You have to find the correct amount for the offset parameter depending on the transition duration that you apply. For a transition duration of 0.3 the sweet spot is an offset of 0.05.
You can download a working example here: https://github.com/francosolerio/InteractiveModal
Easing functions
struct Curves {
    static func quadraticEaseIn<T: FloatingPoint>(t: T) -> T {
        return t * t
    }

    static func quadraticEaseOut<T: FloatingPoint>(t: T) -> T {
        return 1 - quadraticEaseIn(t: 1 - t)
    }

    static func QuadraticEaseInOut<T: FloatingPoint>(t: T) -> T {
        if t < 1/2 {
            return quadraticEaseIn(t: t * 2) / 2
        } else {
            return 1 - quadraticEaseIn(t: (1 - t) * 2) / 2
        }
    }

    static func quadraticEaseOut<T: FloatingPoint>(t: T, offset: T) -> T {
        return quadraticEaseOut(t: t + offset)
    }
}

Animator
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                fromVC.view.frame = finalFrame
            },
            completion: { _ in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        )

Interactor
var progress = Curves.quadraticEaseOut(t: translation.y / viewController.view.bounds.height, offset: 0.05)
        progress = CGFloat(fminf(fmaxf(Float(progress), 0.0), 1.0))

A: I'm having the exact same issue where the dismiss animation starts "on its own" (disregarding any interaction) before being controlled by the UIPercentDrivenInteractiveTransition.
Then I thought the dismiss animation that's taking place in those initial milliseconds is actually your own custom animation provided by your implementation of :
animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?

So what you can do is increase the duration of your custom animation, something like 10 seconds, and the initial jittering no longer happens.
In order for the "post interaction" animation to occur at a regular speed (ie. when you let go of your view controller), you increase the completion speed or your UIPercentDrivenInteractiveTransition instance with the following line:
percentDrivenTransition.completionSpeed = 10.0

Without it, the remainder of your animation would take several seconds, and that's not what we want here.
Hope that helps.


text:
Q: Lua Pattern: %b{}? optional balanced braces possible I want to have optional balanced braces to be part of my match. Is that possible with just the normal patterns?
My Test Code looks like this:
for m in string.match('str{},str2{str3{}},str4,str5{a{}b{}}', '[^,]-%b{}') do
  print(v)
end

the output is:
str{}
str2{str3{}}
str5{a{}b{}}

the missing part is str4
I thought the pattern [^,]-%b{}? would do it but %bxy and ? are both pattern items so of course it does not work, but is there a way to do it anyway?
My workaround for now is:
local stored
for e in string.gmatch(str, '[^,]+') do
  if stored then
    e = stored .. ',' .. e
  end
  if string.match(e, '^[^{}]+$') or string.match(e, '^[^{}]*%b{}[^{}]*$') then
    print(e)
    stored = nil
  else
    stored = e
  end
end

A:
%b{}? optional balanced braces possible

No. You'd need to split by comma and handle the way you did this.
One way to simplify may be to replace ([^}]), with \1{}, first and then apply your processing without any special cases.

A: A possible workaround is to replace commas inside braces with zeroes (and restore them after comma-splitting).
local str = 'str{},str2{str3{}},str4,str5{a{},b{}}'
for m in str:gsub('%b{}', function(b) return b:gsub(',', '\0') end):gmatch'[^,]+' do
   m = m:gsub('%z', ',')
   print(m)
end

Output:
str{}
str2{str3{}}
str4
str5{a{},b{}}


text:
Q: How can you tell if a Sql Server Stored Procedure returns records Within tsql I'm calling a tsql stored procedure that returns a record set. I want to be able to tell if the record set is empty or not empty.
For some reason @@rowcount always returns 1.
What is the best way to do this?
One more thing I'm not in a position to edit this stored procedure.

A: Use @@rowcount in the inner stored proc, pass back out as an output paramter.
Use @@rowcount immediately after the SELECT in the inner stored proc. And call like this:
EXEC dbo.InnerProc @p1, ..., @rtncount OUTPUT

or...
Use RETURN @@rowcount in the inner stored proc immediately after the SELECT. And call like this:
EXEC @rtncount = dbo.InnerProc @p1, ...

Edit:
If you can't edit the proc, you have to load a temp table and manipulate that.
CREATE TABLE #foo (bar int...)

INSERT #foo
EXEC MyUntouchableProc @p1
SELECT @@ROWCOUNT

@@ROWCOUNT fails because it only shows the last statement count, not the last SELECT. It could be RETURN, END (in some cases), SET etc

A: Use @@ROWCOUNT
From msdn:
Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.
Here's an example:
USE AdventureWorks2008R2;
GO
UPDATE HumanResources.Employee
SET JobTitle = N'Executive'
WHERE NationalIDNumber = 123456789
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';
ELSE
PRINT @@ROWCOUNT + ' records updated';
GO

If you are using .net and making use of a SqlDataReader you can make use of .HasRows method or the .count of those records.  The other thing you could do is pass an output parameter to your sproc, store the value in the out parameter within your sproc.  Then when you return to .net you will have this value (the number of records affected by the sproc).
From MSDN:

Statements that make a simple
  assignment always set the @@ROWCOUNT
  value to 1. No rows are sent to the
  client. Examples of these statements
  are: SET @local_variable, RETURN,
  READTEXT, and select without query
  statements such as SELECT GETDATE() or
  SELECT 'Generic Text'.

Also make sure you SET NOCOUNT ON

A: Edit
You want to calculate @@rowcount immediately after the SELECT statement.  If anything happens in between, the @@rowcount will be updated for each new statement.  You could evalute @@rowcount inside the stored procedure and pass back as an output parameter.
Edit
Also make sure you SET NOCOUNT ON.
Or
Run a select count(*) from... against the underlying data set in the stored procedure.  You could spit that out as an output parameter.

A: Select @@rowcount:
After executing the stored procedure.


text:
Q: Как вывести в цикле for базу sql Например я подключаюсь к базе
conn = sqlite3.connect("base.db")
cursor = conn.cursor()
cursor.execute("SELECT url, age FROM logins")
for line in cursor.fetchall():
    print(line)

Но он выводит всё в одну строку
Можно мне как то вывести что бы шел цикл for что то вроде
url age
url age
url age

Мне нужно проверять в каждой строке на слово
Например выводить только все строки в которых есть url

A: Если я правильно понял суть того что вам надо.
Создал тестовую бд. Данные в нее занес руками в sqllitestudio:
import sqlite3

conn = sqlite3.connect('parser.sqlite', check_same_thread = False)
cursor = conn.cursor()
with conn:
    cursor.execute("CREATE TABLE IF NOT EXISTS `logins` (`url` STRING ,`age` STRING)")
    conn.commit()

cursor.execute("SELECT url, age FROM logins")
for row in cursor.fetchall():
    if row[0]: #проверка что строка в столбце url не пустая
        print("{0} {1}".format(row[0], row[1]))

cursor.close()

результат в консоли:
url1 age1
url2 age2


text:
Q: when I startup Intellij Idea 14.1,it will run some java.exe processes
when I startup Intellij Idea 14.1,it will  run some java.exe processes.
  The following result

*

*> java.exe  4580  C:\Program Files\Java\jdk1.6.0_45\jre\bin\java.exe

*> java.exe  8660  C:\Program Files\Java\jdk1.7.0_80\bin\java.exe

I install JDK 1.6 and JDK 1.7

*

*The following is my configuration:

JAVA_HOME:C:\Program Files\Java\jdk1.6.0_45

I don't know why is this? Thank you very much!

A: Java.exe it's a background process, includes the JDK as well as the Application Programming Interface that enables to run Java based programmes. Also read about JVM.


text:
Q: Add new filter to Map function in couchbase I have documents stored in couchbase in the following format:
{
"id" : 1,
"type" : "queueStat",
"timestampIN" : 1524131000000,
"timestampOut" : 1524131925000
}

I have a queue, timestamp IN & OUT get updated when entering and leaving the queue.
The Map function is :
function (doc, meta) {
    if (doc.id && doc.type && doc.type === "queueStat" ){
        emit([doc.id, doc.timestampIN]);
    }
}

My used query has a StartKey and an EndKey, which are based on document ID and the timestamp IN.
This works really fine, now I want to add a new filter based on the time spent in the queue. I did the following changes:
The map:
  function (doc, meta) {
        if (doc.id && doc.type && doc.type === "queueStat" ){
            emit([doc.id, doc.timestampIN, doc.timestampOUT-doc.timestampIN]);
        }
    }

When calling this new Map function, with for example:
http://192.168.1.41:8092/default/_design/queue/_view/CalculateDiff?stale=false&startkey=["1", 1524131000000, 0]&endkey=["1", 1524131925000, 0]

it does not take my 3rd added filter in consideration :(


text:
Q: Can one find out which MySQL-queries were slow? I use the PHP function mysql_stat() to obtain information about my MySQL database.
There is an entry Slow queries, which in my case is 94 (of 301729 queries). Is there a log-file that contains more information about the queries? (time, execution time, the query itself,...)?
14 Hours ago I set up a new server, with 4 times more RAM,... but still I have 0.031154% slow queries, which is basically the same as before, I think that's very high. I really like to find out, which are the slow queries, and how to optimize them. What is an acceptable ratio of slow queries?

A: You can enable log-slow-queries in my.cnf. That writes the slow queries to a log.
log_slow_queries = /var/log/mysql/mysql-slow.log

I think you should never have queries slower than .2 seconds if the user needs to wait. When executing crons where no users are involved, it does not matter that much. But if you use the same database / table, the query of the cron can slow down the normal query (locking / i/o).
You can optimize your databse by setting the right indexes, and use EXPLAIN to try different queries.


text:
Q: Page stretching on...and on...and on Amazingly, the title basically explains it. We have a page that our client made which we are in the process of recreating.
The pages height just keeps going until (I am assuming this) the browser hits it's limit. I have tried firebug and W3 validator and they have both not helped.
Could this be down to unclosed tags? Or maybe the fact that this generator that she has used has stuck ID's on script tags, THE HORROR!.
Any suggestions would be great, I need to try everything here. Thanks.

A: In your page source at line 193 there's this:

LINKS

Don't know what's setting that style to that position, but this is what's causing the problem.  If you look in the very bottom right of your page you'll see LINKS
Is there any reason for this div to exist?  You could just remove it or remove the absolute position elements of the style.

A:

LINKS

This. Is insane!!
Is just like the whole rest of the Position Absolute's that are throughout the html.
Even when there's overflow hidden, the declaration says: top 1 million 239 thousand 620 pixels HEIGHT and the declaration for Left is as obscure as a Medieval Manuscript.
If you delete that sentence the html fits in the body. Hope you fix the rest of crazy declarations as well.

A: I don't know. Maybe it's the 3 after the  tag (well, probably not). Try fixing the errors reported by the W3C validator.


text:
Q: How relevant is LHC to quantum gravity? Premise: the LHC is obviously mapping unseen territory in high energies, and therefore it's always possible to imagine far out results.
Excluding completely unexpected outcomes - is the LHC performing any experiment that could help with string theory or m-theory? For example:

*

*direct super-strings or m-theory predictions to be tested or confuted

but also

*

*measurements that would help "shape" string/m-theory into something more concretely testable or practical than the current blurry incarnation?

A: This article from CERN Courier is about string-theory and experimental tests of it, and about LHC. It is not really technical but it also links to various references and articles.
And for more technical info, you can browse the list of String Theory Seminar of the TH department at CERN and search for "LHC"; very interesting.

A: Well, there's no reason to believe in supersymmetry, beyond some theoretical niceness to it, so if they see THAT at the LHC, then string theory gets a big boost, as there is no way other than supersymmetry to produce fermions in string theory.
The other thing that might be relevant to quantum gravity is that if there are large extra dimensions (as in, large compared to the Planck length, but smaller than detectable by things like the Cavendish experiment).  If that is the case, then the 'fundamental' gravitational constant may be much larger than Newton's constant (they differ by a factor of the volume of the large extra dimensions), and quantum gravitational effects would be accessible at the LHC.


text:
Q: Why is Sass not compiling my classes correctly? I'm creating a web and use Sass mainly for variables with colors. However, when I nested my color classes in SCSS, it compiled into CSS with whitespaces and thus, it doesn't work. Is it some sort of formatting issue, or something else? I'm also inserting my code for better understanding.

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

My SCSS:
h1, h2, h3, h4, h5, h6 {
    .orange {
        &color: $orange;
    }

    .darkgreen {
        &color: $dark-green;
    }

    .lightgreen {
        &color: $light-green;
    }

    .red {
        &color: $red;
    }

    .blue {
        &color: $blue;
    }

    .lightblue {
        &color: $light-blue;
    }
}

My compiled, but non-functional CSS:
h1 .orange, h2 .orange, h3 .orange, h4 .orange, h5 .orange, h6 .orange {
      color: #F27F1B;
    }
    h1 .darkgreen, h2 .darkgreen, h3 .darkgreen, h4 .darkgreen, h5 .darkgreen, h6 .darkgreen {
      color: #49BF72;
    }
    h1 .lightgreen, h2 .lightgreen, h3 .lightgreen, h4 .lightgreen, h5 .lightgreen, h6 .lightgreen {
      color: #81D959;
    }
    h1 .red, h2 .red, h3 .red, h4 .red, h5 .red, h6 .red {
      color: #F23C50;
    }
    h1 .blue, h2 .blue, h3 .blue, h4 .blue, h5 .blue, h6 .blue {
      color: #009ECE;
    }
    h1 .lightblue, h2 .lightblue, h3 .lightblue, h4 .lightblue, h5 .lightblue, h6 .lightblue {
      color: #04ADBF;
    }

`

A: remove the & from the CSS property:
.orange {
    &color: $orange;
}

the & is used in Sass/Scss to concatenate the parent class, not the CSS property.
h1, h2, h3, h4, h5, h6 {
    &.orange {
        color: $orange;
    }
...
}

I highly suggest you not to nest those classes under the headings (h1,h2,h3...)
What would happen if you need those classes in a paragraph or a span in the future?
You would need to create copies of these classes over and over again.
I would choose an approach like bootstrap, creating simple helper classes, and using them when you need them (on every element):
.color-white {
  color: #FFFFFF;
}

You could also create all those classes from a loop, without having to have to create them manually:
$color-collection: ('white' '#FFFFFF'), ('black' '#000000');
@each $color in $color-collection {
  $color-name: nth($color, 1);
  $color-value: nth($color, 2);
  .color-#{$color-name} {
    color: #{$color-value};
  }
}

Would generate this CSS:
.color-white {
  color: #FFFFFF;
}

.color-black {
  color: #000000;
}


text:
Q: Probability Question - A large number, $N$ , people go to a convention at a hotel. Each person is assigned one of $N $ hotel rooms.... A large number of people, $N$, go to a convention at a hotel.  Each person is assigned one of the $N$ hotel rooms.  Before going to the convention, everyone gives their room key to the doorman.  On the way out, the doorman hands the keys back at random. What is the probability that at least one person is given his/her original key?
The general equation I have worked out should be,
$$P(X \geq 1) = 1 - P(X=0)$$
$$P(X=0) = (1-(1/N))^N$$
Adding up all the probabilities that one person gets the right key.  I have checked with the answer key and this is a solution.  However, it does not work for the case where $N = 2$.
The probability that at least one person gets the right key should be $50% $ ,but this equation returns $75%$ .  Can anyone explain what logical error I am making?

A: The error in your method lies in the fact that you treat "$A$ getting the wrong key " and "$B$ getting the wrong key" as independent events.  They aren't.  For instance, if you only have two people then knowing that the first one gets the wrong key makes it certain that the second also gets the wrong key.
To solve the problem, use Derangements.  The keys people are given can be thought of as a permutation of the names, so your question becomes "what is the probability that a (uniformly) randomly chosen permutation is a derangement?"  for which the answer is clearly $$\frac {!n}{n!}$$
Note that for large $n$ this approaches $\frac 1e$ so, again for large $n$, the numerical probability is about $36.79\%$


text:
Q: facebook friend selector not appearing/does not load? I am using the below mentioned code to show a friend-selector list, but it's not loading anymore. It used to work some time back.
It does show that it's loading with the typical facebook style ajax loading animation and after some time nothing happens. Only the button appears, but not the input field in which user can type the friends name. What do I need to do to make the input field appear?
<fb:fbml>
  <form action="submit.php" id="testForm" method="post">
  <fb:friend-selector name="uid" idname="ids"></fb:friend-selector>
  <input name="submit" type="submit" value="Add" class="inputbutton" />
  </form>
</fb:fbml>

A: FBML is deprecated.  Try using the current API and see if that fixes your issue.


text:
Q: Python twisted reactor - address already in use I'm following a tutorial http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server for creating a sample using socket programming in Mac OS X enviromment.
I'm writing using post 80 for reactor.listenTCP(80, factory).
When I run the server.py file, getting an error:
File "server.py", line 10, in <module>
    reactor.listenTCP(6, factory)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/posixbase.py", line 436, in listenTCP
    p.startListening()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/tcp.py", line 641, in startListening
    raise CannotListenError, (self.interface, self.port, le)
twisted.internet.error.CannotListenError: Couldn't listen on any:80: [Errno 48] Address already in use.

Source code is as follow:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor

class IphoneChat(Protocol):
    def connectionMade(self):
        self.factory.clients.append(self)
        print "clients are ", self.factory.clients

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run()

If I'm using another port no like 6 etc, it is working fine.
I just wanted to know, how can I use port 80 for the same application.

A: I encountered this issue too, actually, just now.
Here is what I did:
MacBook-Air:Desktop user$ sudo lsof -i:80
COMMAND  PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
Python  1276 root    3u  IPv4 ******      0t0  TCP *:http (LISTEN)
MacBook-Air:Desktop user$ sudo kill 1276
MacBook-Air:Desktop user$ sudo python server.py
Iphone Chat server started

Then everything goes well.

A: For me the issue was that apache was already listening on port 80.  Seems like a lot of people google through this post and other ones with this issue but I don't see this particular answer offered.  It was what worked for me so I thought that I would add to it in case it helps:
Running Mac/Mavericks but the issue would occur on any other system where Apache runs by default ... or one might forget it's running.
Did
sudo lsof -i TCP:80 | grep LISTEN

Got
httpd      20 root    4u  IPv6 0x1d12a12e12345b12      0t0  TCP *:http (LISTEN)
httpd     109 _www    4u  IPv6 0x1d12a12e12345b12      0t0  TCP *:http (LISTEN)
httpd     437 _www    4u  IPv6 0x1d12a12e12345b12      0t0  TCP *:http (LISTEN)
httpd     438 _www    4u  IPv6 0x1d12a12e12345b12      0t0  TCP *:http (LISTEN)
httpd     439 _www    4u  IPv6 0x1d12a12e12345b12      0t0  TCP *:http (LISTEN)

did
sudo apachectl stop

And the server worked just fine on port 80 after that.

A: You can't listen port if another application already bound socket to this port. For example read socket.bind

A: Open Activity Monitor, search for Python and kill the process. You probably messed up with closing a server once.


text:
Q: Extract a file path or file name from a string in C# Take following string as an input:
var input = @"The file is: ""c:\sampleDirectory\sample subdirectory\sampleFileName.txt\"" which is a text file";

How can I extract only the file path from the above string.
Using Regex or a similar approach is preferred.

A: Edited:
It can be done with LastIndexOf as answered by eocron.
But here is a regex solution :
Match match = Regex.Match(input, @"""(.*)\\(.*\..*)[\\]?""", RegexOptions.IgnoreCase);

if (match.Success)
{
    string path = match.Groups[1].Value;
    string filename = match.Groups[2].value;
}

A: If your input patterns looks exactly like this, you could easily do this without Regex:
var magic1 = 14;//index of first quotation mark
var magic2 = 22;//suffix index of last quotation mark
var result = str.Substring(magic, str.Lenght-magic2-magic1);


text:
Q: Is it possible to manage Vagrant machines via a custom name? I usually can do operations over my boxes via:
vagrant <command argument> <box id>

However, I find this kinda tedious as I actually must remember the ID each machine got.
Can't I assign a custom name to any machine the way I can manage them by vagrant <command argument> <custom name>?
Update
I added this to the Vagrantfile:
config.vm.define "customname" do |customname|
end

And that brought a machine with such name visible from vagrant status, however I can't call vagrant ssh customname yet ...

A: Yes, it's possible, and you're on the right track with your update.
The box name which is used in Vagrant commands comes from the config name, as you've updated. You can see more examples under the documentation for Multi-Machine
You can also control the name as seen by VirtualBox: Configuration - VirtualBox Provider
In your update it looks like you've defined it as "customname" correctly. After creating that VM, you should be able to vagrant ssh customname. If that's not working, you may need to destroy and recreate it once (after the name changed).


text:
Q: Filtering data with spatie query builder using trait I put logic from my function index() of UserController in trait taht i created:
public function index()
{
    $this->authorize('view', Auth::user());
    $users = QueryBuilder::for(User::class)
        ->allowedIncludes('kids','roles','articles','recordings')
        ->allowedFilters('first_name', 'last_name', 'email')
        ->get();
    return UserResource::collection($users);
}

and this is my trait :
<?php
namespace App\Http\Traits;

use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;

trait Filterable
{
  public function filter()
  {
    $users = QueryBuilder::for(User::class)
            ->allowedIncludes('kids','roles','articles','recordings')
            ->allowedFilters('first_name', 'last_name', 'email')
            ->get();
            return $users;
  }
}

So now my function index() looks like this:
use Filterable;

    public function index()
    {
        $this->authorize('view', Auth::user());
        $users = $this->filter();
        return UserResource::collection($users);

Now when i do this in my postman
{{url}}/api/users?filter[first_name]=anna
it works and it returns anna from my database but when I try
{{url}}/api/users?include=roles
it return every user from database but does not include roles.
Can somebody help me with this?

A: This is taken straight from the github page: https://github.com/spatie/laravel-query-builder#custom-filters
Custom filters
use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;

class FiltersUserPermission implements Filter
{
    public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('permissions', function (Builder $query) use ($value) {
            $query->where('name', $value);
        });
    }
}

use Spatie\QueryBuilder\Filter;

// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
    ->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
    ->get();
// $users will contain all users that have the `createPosts` permission


text:
Q: Include Subquery into SQL CASE Statement Below query is used to get the number of Blocked test cases from ALM. Is it possible to include this query inside a CASE statement such that the output of the CASE Statement is "COUNT(LINK.LN_ENTITY_ID)"?
SELECT  BUG.BG_BUG_ID, COUNT(LINK.LN_ENTITY_ID) AS COUNT_TC, TESTCYCL.TC_STATUS FROM BUG
LEFT JOIN ALL_LISTS
ON BG_SUBJECT = AL_ITEM_ID
INNER JOIN LINK
ON BG_BUG_ID = LN_BUG_ID
LEFT JOIN TESTCYCL
ON TESTCYCL.TC_TEST_ID = LINK.LN_ENTITY_ID AND LINK.LN_ENTITY_TYPE = 'TESTCYCL'
WHERE TESTCYCL.TC_STATUS = 'Blocked'
GROUP BY BG_BUG_ID, TESTCYCL.TC_STATUS

A: SELECT  BUG.BG_BUG_ID,
       SUM(CASE TESTCYCL.TC_STATUS WHEN ="Blocked" THEN 1 ELSE 0 END) AS COUNT_TC,
       TESTCYCL.TC_STATUS
  FROM BUG
    LEFT JOIN ALL_LISTS
    ON BG_SUBJECT = AL_ITEM_ID
    INNER JOIN LINK
    ON BG_BUG_ID = LN_BUG_ID
    LEFT JOIN TESTCYCL
    ON TESTCYCL.TC_TEST_ID = LINK.LN_ENTITY_ID AND LINK.LN_ENTITY_TYPE = 'TESTCYCL'
    GROUP BY BG_BUG_ID

This query will display the total no. of bug with status="blocked" for each BUG_ID.(Assuming that you need).
Hope this helps


text:
Q: Powershell executed within .csproj and running elevated could not access host file Situation:
I am running Visual Studio as administrator.
I use the script to initialize my solution. One of the initialization tasks is to set host file entries.
I execute a powershell script in the csproj file during the build process in the target BeforeBuild:
<Target Name="BeforeBuild">
<PropertyGroup>
  <InitScriptPath Condition=" '$(InitScriptPath)' == '' ">$(SolutionDir)Scripts\InitKentico.ps1</InitScriptPath>
  <KenticoVersion Condition=" '$(KenticoVersion)' == '' ">10.0.0</KenticoVersion>
  <KenticoProjectName Condition=" '$(KenticoProjectName)' == '' ">Kentico10WebAppDemo</KenticoProjectName>
  <KenticoWebsiteBinding Condition=" '$(KenticoWebsiteBinding)' == '' ">local.kentico10webappdemo.com</KenticoWebsiteBinding>
  <InitScriptCommand Condition=" '$(InitScriptCommand)' == '' ">%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe -command "& { &'$(InitScriptPath)' '$(ProjectDir)' '$(SolutionDir)' '$(KenticoVersion)' '$(KenticoProjectName)' '$(KenticoWebsiteBinding)'; exit $lastexitcode }"</InitScriptCommand>
</PropertyGroup>
<Message Text="Running Init PowerShell Script: $(InitScriptPath) with command $(InitScriptCommand)" Importance="high" />
<Exec Command="$(InitScriptCommand)" />

I check within my powershell if the script is executed as administrator:
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

if (-not($myWindowsPrincipal.IsInRole($adminRole))) {
    Write-Host "Must be executed as administrator!"
    exit 1
}

I use the following script to edit the host file:
$file = Join-Path -Path $($env:windir) -ChildPath "system32\drivers\etc\hosts"
$data = Get-Content -Path $file
$entriesBlockHeader = "### MyWebsite ###";
$hostEntry1 = "127.0.0.1`tmy-website.com"
$hostEntry2 = "127.0.0.1`twww.my-website.com"
$entriesBlock = [System.Environment]::NewLine + $entriesBlockHeader
$entriesBlock = $entriesBlock + [System.Environment]::NewLine + $hostEntry1
$entriesBlock = $entriesBlock + [System.Environment]::NewLine + $hostEntry2
$data = $data + $entriesBlock
$data | Out-File -FilePath $file

My Issue:
When it comes to change the host file, the script throws an exception because permissions are denied.
I do not understand why this happens. The script is executed as administrator, so it should have the needed permissions.
When I execute the script in the Powershell ISE (as administrator) it works like a charm. Only if executed from the csproj file in Visual Studio (as administrator) it is not working.


text:
Q: Finding the list of network requests a javascript file initiated during a page load Is there a way to find network requests initiated by a javascript file, while looking at the code itself (e.g., checking the file through a local proxy)?
I think this is possible once loading a page completes, e.g., using Chrome devtools to look at request initiator chain, but could not think of (nor found) a methodology that I can do while the page is being parsed and loaded before the scripts is executed.
Would there be any work done for a similar purpose?


text:
Q: awk/sed/perl one liner to edit json file We want to add the folwing lines:
export KAFKA_HEAP_OPTS="-Xmx8g -Xms8g"

and:
export KAFKA_JVM_PERFORMANCE_OPTS=" -XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80"

in "content" line
can we get suggestion how to edit the file with awk,sed,perl one liner , etc
example of the json before update
{
  "href" : "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
  "items" : [
    {
      "href" : "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
      "tag" : "version1527250007610",
      "type" : "kafka-env",
      "version" : 8,
      "Config" : {
        "cluster_name" : "HDP",
        "stack_id" : "HDP-2.6"
      },
      "properties" : {
        "content" : "\n#!/bin/bash\n\n# Set KAFKA specific environment variables here.\n\n# The java implementation to use.\nexport JAVA_HOME={{java64_home}}\nexport PATH=$PATH:$JAVA_HOME/bin\nexport PID_DIR={{kafka_pid_dir}}\nexport LOG_DIR={{kafka_log_dir}}\nexport KAFKA_KERBEROS_PARAMS={{kafka_kerberos_params}}\nexport JMX_PORT=9997\n# Add kafka sink to classpath and related depenencies\nif [ -e \"/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\" ]; then\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/lib/*\nfi\n\nif [ -f /etc/kafka/conf/kafka-ranger-env.sh ]; then\n. /etc/kafka/conf/kafka-ranger-env.sh\nfi",
        "is_supported_kafka_ranger" : "true",
        "kafka_log_dir" : "/var/log/kafka",
        "kafka_pid_dir" : "/var/run/kafka",
        "kafka_user" : "kafka",
        "kafka_user_nofile_limit" : "128000",
        "kafka_user_nproc_limit" : "65536"
      }
    }
  ]

expected output ( example of the json after update )
{
  "href" : "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
  "items" : [
    {
      "href" : "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
      "tag" : "version1527250007610",
      "type" : "kafka-env",
      "version" : 8,
      "Config" : {
        "cluster_name" : "HDP",
        "stack_id" : "HDP-2.6"
      },
      "properties" : {
        "content" : "\n#!/bin/bash\n\n# Set KAFKA specific environment variables here.\n\n# The java implementation to use.\nexport JAVA_HOME={{java64_home}}\nexport PATH=$PATH:$JAVA_HOME/bin\nexport PID_DIR={{kafka_pid_dir}}\nexport LOG_DIR={{kafka_log_dir}}\nexport KAFKA_KERBEROS_PARAMS={{kafka_kerberos_params}}\nexport JMX_PORT=9997\n# Add kafka sink to classpath and related depenencies\nif [ -e \"/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\" ]; then\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/lib/*\nfi\n\nif [ -f /etc/kafka/conf/kafka-ranger-env.sh ]; then\n. /etc/kafka/conf/kafka-ranger-env.sh\nfi\nexport KAFKA_HEAP_OPTS=\"-Xmx8g -Xms8g\"\nKAFKA_JVM_PERFORMANCE_OPTS=\"-XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80\n"",
        "is_supported_kafka_ranger" : "true",
        "kafka_log_dir" : "/var/log/kafka",
        "kafka_pid_dir" : "/var/run/kafka",
        "kafka_user" : "kafka",
        "kafka_user_nofile_limit" : "128000",
        "kafka_user_nproc_limit" : "65536"
      }
    }
  ]

other example of the content line after update
 "content" : "\n#!/bin/bash\n\n# Set KAFKA specific environment variables here.\n\n# The java implementation to use.\nexport JAVA_HOME={{java64_home}}\nexport PATH=$PATH:$JAVA_HOME/bin\nexport PID_DIR={{kafka_pid_dir}}\nexport LOG_DIR={{kafka_log_dir}}\nexport KAFKA_KERBEROS_PARAMS={{kafka_kerberos_params}}\nexport JMX_PORT=9997\n# Add kafka sink to classpath and related depenencies\nif [ -e \"/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\" ]; then\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/lib/*\nfi\n\nif [ -f /etc/kafka/conf/kafka-ranger-env.sh ]; then\n. /etc/kafka/conf/kafka-ranger-env.sh\nfi\nexport KAFKA_HEAP_OPTS=\"-Xmx8g -Xms8g\"\nKAFKA_JVM_PERFORMANCE_OPTS=\"-XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80\n"",

A: Perl solution using the JSON module:
perl -MJSON -we '
    $json = JSON->new->pretty->canonical;
    open $fh, "<", shift or die $!;
    $j = $json->decode(do { undef $/; <$fh> });
    $j->{items}[0]{properties}{content} .= qq(\nexport KAFKA_HEAP_OPTS="-Xmx8g -Xms8g"\nexport KAFKA_JVM_PERFORMANCE_OPTS=" -XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M -XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80");
    print $json->encode($j);
' -- file.json > new.json

I had to fix your expected file (export was missing for the second variable, plus some whitespace issues) and canonicalise it to get the exactly same output.

A: Not a one-liner, but ...
$ new_lines='\\nexport KAFKA_HEAP_OPTS=\\"-Xmx8g -Xms8g\\"\\nexport KAFKA_JVM_PERFORMANCE_OPTS=\\" -XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80\\"'
$ new_content=$( jq '.items[0].properties.content' file.json | sed 's/"$/'"$new_lines"'"/')
$ jq '.items[0].properties.content = '"$new_content" file.json
{
  "href": "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
  "items": [
    {
      "href": "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
      "tag": "version1527250007610",
      "type": "kafka-env",
      "version": 8,
      "Config": {
        "cluster_name": "HDP",
        "stack_id": "HDP-2.6"
      },
      "properties": {
        "content": "\n#!/bin/bash\n\n# Set KAFKA specific environment variables here.\n\n# The java implementation to use.\nexport JAVA_HOME={{java64_home}}\nexport PATH=$PATH:$JAVA_HOME/bin\nexport PID_DIR={{kafka_pid_dir}}\nexport LOG_DIR={{kafka_log_dir}}\nexport KAFKA_KERBEROS_PARAMS={{kafka_kerberos_params}}\nexport JMX_PORT=9997\n# Add kafka sink to classpath and related depenencies\nif [ -e \"/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\" ]; then\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/lib/*\nfi\n\nif [ -f /etc/kafka/conf/kafka-ranger-env.sh ]; then\n. /etc/kafka/conf/kafka-ranger-env.sh\nfi\nexport KAFKA_HEAP_OPTS=\"-Xmx8g -Xms8g\"\nexport KAFKA_JVM_PERFORMANCE_OPTS=\" -XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80\"",
        "is_supported_kafka_ranger": "true",
        "kafka_log_dir": "/var/log/kafka",
        "kafka_pid_dir": "/var/run/kafka",
        "kafka_user": "kafka",
        "kafka_user_nofile_limit": "128000",
        "kafka_user_nproc_limit": "65536"
      }
    }
  ]
}

To verify the new content readably:
$ printf "$new_content\n"
"
#!/bin/bash

# Set KAFKA specific environment variables here.

# The java implementation to use.
export JAVA_HOME={{java64_home}}
export PATH=$PATH:$JAVA_HOME/bin
export PID_DIR={{kafka_pid_dir}}
export LOG_DIR={{kafka_log_dir}}
export KAFKA_KERBEROS_PARAMS={{kafka_kerberos_params}}
export JMX_PORT=9997
# Add kafka sink to classpath and related depenencies
if [ -e "/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar" ]; then
  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar
  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/lib/*
fi

if [ -f /etc/kafka/conf/kafka-ranger-env.sh ]; then
. /etc/kafka/conf/kafka-ranger-env.sh
fi
export KAFKA_HEAP_OPTS="-Xmx8g -Xms8g"
export KAFKA_JVM_PERFORMANCE_OPTS=" -XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80""

A: This is a simple fix with Perl appending the lines to the line (each line) with content without parsing the JSON doc. This is a one-liner (copy and paste into your command line). I guess you want this:
<in perl -nple'$_.="\\nexport KAFKA_HEAP_OPTS=\"-Xmx8g -Xms8g\"\\nexport KAFKA_JVM_PERFORMANCE_OPTS=\" -XX:MetaspaceSize=96m -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M -XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80\"\\n\""
if/^\s+"content"/ '

Here in at the beginning is the input file. You're getting the output on the screen, which you can adjust easily. You could also have Perl modify the file in place using the -i switch. (Learn about it first.)
The output is this:
{
  "href" : "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
  "items" : [
    {
      "href" : "http://master02:8080/api/v1/clusters/HDP/configurations?type=kafka-env&tag=version1527250007610",
      "tag" : "version1527250007610",
      "type" : "kafka-env",
      "version" : 8,
      "Config" : {
        "cluster_name" : "HDP",
        "stack_id" : "HDP-2.6"
      },
      "properties" : {
        "content" : "\n#!/bin/bash\n\n# Set KAFKA specific environment variables here.\n\n# The java implementation to use.\nexport JAVA_HOME={{java64_home}}\nexport PATH=$PATH:$JAVA_HOME/bin\nexport PID_DIR={{kafka_pid_dir}}\nexport LOG_DIR={{kafka_log_dir}}\nexport KAFKA_KERBEROS_PARAMS={{kafka_kerberos_params}}\nexport JMX_PORT=9997\n# Add kafka sink to classpath and related depenencies\nif [ -e \"/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\" ]; then\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/ambari-metrics-kafka-sink.jar\n  export CLASSPATH=$CLASSPATH:/usr/lib/ambari-metrics-kafka-sink/lib/*\nfi\n\nif [ -f /etc/kafka/conf/kafka-ranger-env.sh ]; then\n. /etc/kafka/conf/kafka-ranger-env.sh\nfi",\nexport KAFKA_HEAP_OPTS="-Xmx8g -Xms8g"\n export KAFKA_JVM_PERFORMANCE_OPTS=" -XX:MetaspaceSize=96m -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M -XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80"\n"
        "is_supported_kafka_ranger" : "true",
        "kafka_log_dir" : "/var/log/kafka",
        "kafka_pid_dir" : "/var/run/kafka",
        "kafka_user" : "kafka",
        "kafka_user_nofile_limit" : "128000",
        "kafka_user_nproc_limit" : "65536"
      }
    }
  ]

As you can see, I did a correction here:
export KAFKA_HEAP_OPTS="-Xmx8g -Xms8g"\nexport KAFKA_JVM_PERFORMANCE_OPTS=" -XX:MetaspaceSize=96m -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M -XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80"\n

I changed the -XX option layout and the ending is -XX:MaxMetaspaceFreeRatio=80"\n, and not - XX:MaxMetaspaceFreeRatio=80\n", as you required. So change this if that's what you really want. Also the newline before the shebang is what I'd remove. But I've left this for you.

A: sed one liner.
$ sed -i '/"content"/s/",$/\\nexport KAFKA_HEAP_OPTS=\\"-Xmx8g -Xms8g\\"\\nKAFKA_JVM_PERFORMANCE_OPTS=\\"-XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80\\n"",/' myfile

A: With jq:
v1='export KAFKA_HEAP_OPTS="-Xmx8g -Xms8g"'
v2='export KAFKA_JVM_PERFORMANCE_OPTS=" -XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80"'

jq --arg v1 "$v1" --arg v2 "$v2" '.items[].properties.content += $v1 + "\n" + $v2 + "\n"' infile.json

A:  perl -lpe '
    BEGIN {
       my $a = q[export KAFKA_HEAP_OPTS="-Xmx8g -Xms8g"];

       my $b = q[export KAFKA_JVM_PERFORMANCE_OPTS=" -XX:MetaspaceSize=96m -XX:+UseG1GC-XX:MaxGCPauseMillis=20 - XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M-XX:MinMetaspaceFreeRatio=50 - XX:MaxMetaspaceFreeRatio=80"];

       push @A, s/[\\"]/\\$&/gr for $a, $b;
    }

    /^\h*"content"/ and
       $_ =
          join q[],
             join(q[\n],
                split(/",?$/), @A),
             /(",?)$/;
 '    json-file

Working :
Store the data to be added in scalar variables using the single quote operator to avoid backslashing.

Change all backslashes, double quotes to their escaped versions.

Then in the target line, split it on  ", |,
   and join the elements plus array @A contents with the literal string \n and ending with the closing quotes.


text:
Q: I'm unable to get heatmap.js to work even for a simple heatmap I'm a JavaScript newbie and I am trying to use the open source heatmap.js framework (by Patrick Wied) to create a heatmap, but it doesn't show up even for the most basic of heatmaps. Here is the test code that I am using.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Heatmap Test Code</title>
</head>
<body>
<canvas id="heatMap" width = "1024" height = "742" style="position:absolute; left: 0; top: 0"></canvas>
<script type="text/javascript" src="js/heatmap.js">

var heatmapInstance = h337.create({
container: document.getElementById('heatMap')
});

var testData = {
        max: 100,
        min: 0,
        data: [{x: 807, y: 583, count: 65}, {x: 597, y: 285, count: 51}, {x: 217, y: 449, count: 73}, {x: 377, y: 656, count: 58}, {x: 467, y: 509, count: 47}, {x: 487, y: 164, count: 46}, {x: 247, y: 194, count: 35}]
};

heatmapInstance.setData(testData);
</script>
</body>
</html>

Please would someone show me where I'm going wrong. Thanks!

A: Quite a few small mistakes:

*

*You need to put a wrapper element around your canvas and set that as the container.

*You also should put the external script and the inline script in separate script tags.

*The value of the data points should be called value not count
Leading to:
...
<body>
    <div id='container' style='position: relative; height: 742px'>
        <canvas id="heatMap" width = "1024" height = "742" style="position:absolute; left: 0; top: 0"></canvas>
    </div>
    <script type="text/javascript" src="js/heatmap.js"> </script>
    <script>
    var heatmapInstance = h337.create({
        container: document.getElementById('container')
    });
    ...

Minimal working sample: http://jsbin.com/latepa


text:
Q: Why does this code only loop twice? I have a loop which goes through each item a list and adds it to the database. The code below is a method which I call when a button is clicked on a WPF form. It gets an ID value and a list of Steps(DTO) from app.xaml.cs and puts the data from the list into a database.
using (SQLiteConnection sqConnection = getDatabaseConnection())
{
    SQLiteCommand addItemCommand = sqConnection.CreateCommand();
    sqConnection.Open();
    SQLiteTransaction stepTrans;
    // Start a local transaction
    stepTrans = sqConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
    // Assign transaction object for a pending local transaction
    addItemCommand.Transaction = stepTrans;
    addItemCommand.Connection = sqConnection;

     foreach (Step step in StepsGlobal)
        {
           string sqAddItem = String.Format
                ("INSERT INTO Steps(ID, RecipeID, Description, StepTime, Dependency, Priority, Type) Values(null, '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')",
                recipeID, step.Description, step.StepTime, step.Dependency, step.Priority, step.Type);

            addItemCommand.CommandText = sqAddItem;
            addItemCommand.ExecuteNonQuery();
            stepTrans.Commit();
        }

However, It only works for the first two items and I get the following error if the list contains more than two items.
A first chance exception of type 'System.ArgumentNullException' occurred in
System.Data.SQLite.dll
System.ArgumentNullException: Value cannot be null.
Parameter name: No connection associated with this transaction
   at System.Data.SQLite.SQLiteTransaction.IsValid(Boolean throwError)
   at System.Data.SQLite.SQLiteTransaction.Commit()
   at Project.Methods.addStepsToDatabase()

A: Best guess is that stepTrans.Commit...commits the transaction and invalidates the object. You will need to begin a new transaction after you commit the current one.