text:
Q: mybatis collection resultset maaping issue. Getting empty collection resultset I'm new to mybatis and facing an issue with getting a collection in a resultset. The resultset is defined as below:
<resultMap type="User" id="userMap">
        <id column="id" property="id" />
        <result property="userName" column="user_name" />
        <result property="enabled" column="enabled" />
        <result property="firstName" column="first_name" />
        <result property="lastName" column="last_name" />
        <result property="email" column="email" />
        <result property="password" column="user_password" />
        <result property="passwordSalt" column="user_password_salt" />
        <result property="lastLogin" column="last_login_time" />
        <result property="creationTime" column="creation_time" />
        <result property="lastEdit" column="last_edit_time" />
        <result property="validTill" column="valid_till" />

        <collection property="roles" javaType="ArrayList" ofType="Role" column="id">
            <id property="id" column="role_id" />
            <result property="name" column="role_name" />
            <result property="description" column="role_description" />
        </collection>

    </resultMap>

And the Java code looks like this
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
    throws AuthenticationException
  {
    UsernamePasswordToken upToken = (UsernamePasswordToken)token;

    User user = null;
    user = new UserService().getWithRole(upToken.getUsername());
    if (user == null) {
      throw new UnknownAccountException("Login name [" + upToken.getUsername() + "] not found!");
    }
    if (!user.getEnabled().booleanValue()) {
      throw new DisabledAccountException("Login name [" + upToken.getUsername() + "] is disabled!");
    }
    if (user.getRoles().size() == 0) {
      throw new AuthenticationException("There is no role assigned for you");
    }
    if ((user.getValidTill() != null) && (user.getValidTill().getTime() < new Date().getTime())) {
      throw new ExpiredCredentialsException("Your account has expired!");
    }
    _logger.debug("Found user with username [" + upToken.getUsername() + "]");
    return new SimpleAuthenticationInfo(user, user.getPassword(), new SimpleByteSource(user.getPasswordSalt()), getName());
  }

Here, while logging in I'm getting stuck at the Exception saying There is no role assigned to you
About the code being right, it was working perfectly but I cannot make any change as I just have the WAR which I'm de-compiling using JD. The function getWithRole() fires the following query
<select id="getWithRole" resultMap="userMap" parameterType="User">
    SELECT * FROM view_boss_user_role
    <trim prefix="WHERE" prefixOverrides="AND | OR ">
        <if test="id != null">id = #{id}</if>
        <if test="userName != null">AND user_name = #{userName}</if>
        <if test="firstName != null">AND first_name = #{firstName}</if>
        <if test="lastName != null">AND last_name = #{lastName}</if>
        <if test="email != null">AND email = #{email}</if>
    </trim>
</select>

and the structure of the view is like this
CREATE OR REPLACE VIEW public.view_boss_user_role(
    id,
    user_name,
    enabled,
    first_name,
    last_name,
    email,
    user_password,
    user_password_salt,
    last_login_time,
    creation_time,
    last_edit_time,
    valid_till,
    role_id,
    role_name,
    role_description)
AS
  SELECT boss_user.id,
         boss_user.user_name,
         boss_user.enabled,
         boss_user.first_name,
         boss_user.last_name,
         boss_user.email,
         boss_user.user_password,
         boss_user.user_password_salt,
         boss_user.last_login_time,
         boss_user.creation_time,
         boss_user.last_edit_time,
         boss_user.valid_till,
         boss_role.id AS role_id,
         boss_role.name AS role_name,
         boss_role.description AS role_description
  FROM boss_user,
       boss_role,
       boss_role_user_map
  WHERE boss_role_user_map.user_id = boss_user.id AND
        boss_role.id = boss_role_user_map.role_id;

A sample output looks like this
"id"    "user_name" "enabled"   "first_name"    "last_name" "email" "user_password" "user_password_salt"    "last_login_time"   "creation_time" "last_edit_time"    "valid_till"    "role_id"   "role_name" "role_description"
"1" "adminuser" "True"  "Admin" "User"  "adminuser@domain.com"  "SEli9hsMTTxGgjrlCz48+5w1CaMnUe/8xJJ0enOZ2ag="  "mBPa0wNPjvnGK3gzDMOHOg=="  "28-05-2017"    "28-05-2017"    "28-05-2017"    "31-05-2018"    "1" "ADMIN" "Administrator user"

I'm stuck with this error and I'm quite sure that it is the understanding of mybatis which is limiting me. Please enlighten me


text:
Q: Non-integer combination A linear combination, $ax + by +...=z$ where $a, b,..., z \in \mathbb{Z}$. It is bound to yield an integer by the closure property of integer under the addition operation. This fact is used in computing gcd among others.
I want to know about properties of non-integer combination, i.e. given $a, b, ...\in \mathbb {Z}$; but the multipliers $x, y, .. $ not all $\in \mathbb{Z}$. I hope that they must be enjoying similar properties, as they are comprised of rationals, and the rationals are closed under addition too.
If so, then how these properties can be used where the linear combinations do not hold.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: Mapping dictionary over multiple np.arrays How do i map a dictionary over lists of np.ndarrays?
I have a dictionary containing a range of keys and values. It looks something like this:
{1: 0.5,
 2: 0.51,
 3: 0.34,
 4: 0.38,
 5: 0.4,
 6: 0.27,}

In addition, i have a list object containing a range of numpy arrays which looks like this:
[array([1,2,3]),
 array([4,3,5,6]),
 array([1,4,6,2,3])]

I want to map the dictionary over the arrays to replace each value in each array with its corresponding key value in the dictionary. It will yield something like this:
[array([0.5,0.51,0.34]),
 array([0.38,0.34,0.4,0.27]),
 array([0.5,0.38,0.27,0.51,0.34])]

Finally i want to take the mean of each array in the above structure and append this value to a data frame.
Any suggestions?

A: This is one solution.
import numpy as np

d = {1: 0.5,
 2: 0.51,
 3: 0.34,
 4: 0.38,
 5: 0.4,
 6: 0.27,}

lst = [np.array([1,2,3]),
 np.array([4,3,5,6]),
 np.array([1,4,6,2,3])]

lst2 = list(map(np.vectorize(d.get), lst))

# [array([ 0.5 ,  0.51,  0.34]),
#  array([ 0.38,  0.34,  0.4 ,  0.27]),
#  array([ 0.5 ,  0.38,  0.27,  0.51,  0.34])]


text:
Q: Mito how to save multiple Date/Time Types I have some files that using different date types:
some only have year "2020", others have month "2020-12", and still, some have date:"2020-12-21"
So I want to use interval.
Like this:
(define-table test-date ()
  ((date :col-type :interval
         :initarg :date
         :accessor date)))
(create-dao 'test-date
            :date "2020 years")
(date (find-dao 'test-date))=>((:MONTHS 24240) (:DAYS 0) (:SECONDS 0) (:USECONDS 0))

Q1. Is this is how interval supposed to use?
Q2. How to get year?

A: Your use of interval is smelly. Look, you store a year and you are getting a duration in months. interval is used to store durations, and is particularly used in date arithmetic: date + INTERVAL expr unit. So I don't think you want to use it here to store a date format.
You could:

*

*either store a date and transform an incomplete date to a full one: "2020" would become "2020-00-00" if that is acceptable for your logic,

*either store a string and use a validator function of your own (you could use Mito's inflation/deflation mechanism to retrieve your data in the right data format),

*either use more date fields (year, month, day…) that are nullable.

Recipes for dates and time manipulation: https://lispcookbook.github.io/cl-cookbook/dates_and_times.html


text:
Q: ARM v7 cache behavior and usage I'm tweaking u-boot to support Cyclone V SX PCIe + NVMe. I got it working through a series of hacks to version 2020.10 socfpga fork.
I have two issues that need to be resolved:

*

*u-boot doesn't appear to understand that PCI address space and Host address space are not necessarily the same and when the nvme fetches the address assigned to the PCIe port, the PCI driver assumes that the address read maps directly into main memory. It doesn't. It's mapped to another address completely. I have a hack in place to deal with this. I'm going to try to add a feature to the Device Tree utilities within u-boot to do address translation without breaking existing functionality.

*There are significant issues with the way the nvme driver handles clearing and invalidating cache to pick up changes to memory after the NVMe has executed a command. The doorbell registers need to be cleared on the outgoing and invalidated on the incoming during polling and that is, almost entirely wrong in various ways.
Here's where I need guidance.
There are two bits of code in u-boot to handle cache clearing / invalidation. One is part of the arm v7 core code and the other is pl310 controller code. The arm v7 code thinks a cache line is 64 bytes, the pl310 code thinks a cache line is 32 bytes. Wtf?
Both codes are being used by the nvme code. I think the clear goes through pl310 and the invalidate goes through arm v7, but I may have that backwards at this point, I'm still learning and could have easily mixed them up.
The issue with the nvme driver is simple: It asks to clear an address range which is not cache aligned and both of the codes choke and do the wrong thing and ultimately do not clear or invalidate the cache where it needs to be cleared and invalidated. In the case of the pl310, it rounds up the start address and doesn't do anything and in the case of the arm v7 code, if the start and stop, after aligning them to 64 byte boundaries, are the same, the code does nothing.
I've hacked this by forcing the alignment to 64 bytes in the nvme code and ensuring that it over clears the cache by adding one to the stop if it is the same as start in the case of the arm v7 call.
If you're still following me. Thanks, I really appreciate it.
What is the right way to fix this. None of this code is mine. It seems to me that there are bugs in the cache code. The pl310 should not add one to the start address, perhaps it should add it to the stop address, depending on how the for loop is written. The for loop for invalidating in the arm v7 code should run at least once to ensure it clears the start location. So the invalidate loop should be <=, not <.
I could post this code if anyone is interested, just let me know.
But the big question is: why are there two ways to clear / invalidate cache and why are both being used? It seems to me that since the Cyclone V uses a pl310 cache controller, it's code should be used for both clear and invalidate. This is configured via #define for determining which code is called and something tells me that this should be fixed as well.
Opinions? Options? Ideas?
I'm open, please let me know your thoughts.

A: Since you're on something based on v2020.10 you're missing all of the cache related changes here: https://source.denx.de/u-boot/u-boot/-/commit/d0c04926cd054cf7360ec15913ac17a465f32603
As for the rest of what you raise, the U-Boot mailing list if the right forum and please make sure to CC the relevant people that have worked on the code before.  The scripts/get_maintainer.pl tool will help with that.


text:
Q: compare two dataGridView cell with date value? in my c# windows form i have a dataGridView that loads the data from a table,
The dataGridView has 8 columns two of them have date value
borrow_date and return_date.
I want to compare the of that two columns if the date of any return_date cell is greater that the date of borrow_date cell, make the background of that cell red or make it's fore color red.

A: Below code will help you
<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
   {
    DataRowView drv = e.Row.DataItem as DataRowView;
    Object ob = drv["return_date"];
    Object ob1 = drv["borrow_date"];

    if (!Convert.IsDBNull(ob) && !Convert.IsDBNull(ob1) )
    {
       DateTime date1return_date;
        DateTime date2borrow_date;

         if (DateTime.TryParse(ob.ToString(), out date1return_date) &&
                   DateTime.TryParse(ob1.ToString(), out date2borrow_date))
         {
             if (date1return_date > date2borrow_date)
             {
                 TableCell cell = e.Row.Cells[1]; // Get your required cell
                 cell.BackColor = System.Drawing.Color.Red;
             }
         }
    }
  }

A: Use DateTime to compare date.
DateTime Structure

A: You can do it by different ways:
1 Looping the entire grid once all data was loaded
foreach (DataGridViewRow row in grid.Rows)
     if (Convert.ToInt32(row.Cells["borrow_date"].Value) < Convert.ToInt32(row.Cells["return_date"].Value))
     {
         row.DefaultCellStyle.BackColor = Color.Red;
     }

2 doing it as each row gets loaded.
private void gridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
   if (Convert.ToInt32(row.Cells["borrow_date"].Value) < Convert.ToInt32(row.Cells["return_date"].Value))
     {
         row.DefaultCellStyle.BackColor = Color.Red;
     }
}


text:
Q: Scala Shapeless - Iterating/reading each item of Generic.Repr or converting it to HList I'm learning shapeless and referring a tutorial from here. Which says,

Generic is a simple way to convert case class and product types (like
  tuples) to HList, and vice-versa:

import shapeless.Generic

case class UserWithAge(name: String, age: Int)
val gen = Generic[UserWithAge]
val u = UserWithAge("Julien", 30)

val h = gen.to(u)

Now if I print h, I will get Julien :: 30 :: HNil. But, I'm unable to read each element from h such as h.head , h.tail will not work and there aren't any methods available in h. Here, h is type of gen.Repr and I couldn't figure out a way to convert it into HList either. So, how can I read each element from h?

A: In this case the type of gen.to(u) is gen.Repr, which if you look at the type of gen actually expends to String ::  Int :: HNil, so it's already a HList!
scala> import shapeless.Generic
import shapeless.Generic

scala> case class UserWithAge(name: String, age: Int)
defined class UserWithAge

scala> val gen = Generic[UserWithAge]
gen: shapeless.Generic[UserWithAge]{type Repr = shapeless.::[String,shapeless.::[Int,shapeless.HNil]]} = anon$macro$3$1@4ff329b8

scala> val u = UserWithAge("Julien", 30)
u: UserWithAge = UserWithAge(Julien,30)

scala> val h = gen.to(u)
h: gen.Repr = Julien :: 30 :: HNil

scala> h.head
res0: String = Julien

scala> h.tail
res1: shapeless.::[Int,shapeless.HNil] = 30 :: HNil

In the general case, the Repr type of a Generic will be either a HList or a Coproduct. For examples of how to generically program over these, see shapeless-type-class-derivation-2015-demo.


text:
Q: How to execute code after sending HttpResponse I currently evaluate if we should switch our application from using Tomcat to akka-http. In tomcat we could send the http response by setting the status on a HttpServletResponse object and write the response body to its PrintWriter, do flush() and execute arbitrary (possible long running) code afterwards (e.g. persist the request body). So the latency for that request was independent of the code that came after flushing the response.
Is it possible to achieve the same with akka-http (Akka Version 2.4.9)?
I know that there is the completeWithFuture(java.util.concurrent.CompletionStage value) directive in Akka's Routing DSL, but as far as I know all CompletionStages will be executed before sending the response.


text:
Q: Given $a,b,c,k>0$ and Maximize $f(x)=x^ay^bz^c$ for $x,y,z \in [0, \infty)$ on $A=\{\,(x,y,z)\mid x^k+y^k+z^k=1\,\}$
Given $a,b,c,k>0$ Maximize $f(x)=x^ay^bz^c$ for $x,y,z \in [0, \infty)$ on $A=\{\,(x,y,z)\mid x^k+y^k+z^k=1\,\}$

So I used $g(x,y,z)=x^k+y^k+z^k-1$ with the Lagrange method and obtained through some manipulation:
$f(x)= \lambda k/(a+b+c)$ but I can't really find what is $\lambda$.

A: We consider $$\Lambda(x,y,z)=x^ay^bz^c-\lambda(x^k+y^k+z^k-1) $$
and by applying $\frac\partial{\partial x}$, $\frac\partial{\partial y}$, $\frac\partial{\partial z}$ are led to the equations
$$\begin{align}ax^{a-1}y^bz^c-k\lambda x^{k-1}&=0\\
bx^ay^{b-1}z^c-k\lambda y^{k-1}&=0\\
cx^ay^{b}z^{c-1}-k\lambda z^{k-1}&=0\\
\end{align}$$
If we add $x\cdot(i)+y\cdot(ii)+z\cdot (iii)$ we obtain your result
$$ (a+b+c)\,\underbrace{x^ay^bz^c}_{f(x,y,z)}-k\lambda=0$$
which is interesting, but not (immediately) helpful (especially as $\lambda$ is the only value we are not interested in).
But substituting this back to eliminate $k\lambda$ from it is helpful: We obtain from the first equation
$$ax^{a-1}y^bz^c-(a+b+c) x^{a+k-1}y^bz^c=0$$
and so (provided $x,y,z\ne 0$, which we may assume as the maximum of $f$ will certainly not be zero)
$$x=\sqrt[k]{\frac a{a+b+c}}. $$
Accordingly, we also find
$$y=\sqrt[k]{\frac b{a+b+c}},\quad z=\sqrt[k]{\frac c{a+b+c}}. $$
So finally the maximum value of $f$ under the given conditions is
$$\sqrt[k]{\frac{a^{a}b^{b}c^{c}}{(a+b+c)^{a+b+c}}}. $$


text:
Q: How to clone a django reporsitory into a virtualenv I've got a virtualenv set up for a django app. So far I've installed all my packages via pip when the virtualenv is activated, but I now need to clone one from bitbucket. Is there a special way to do this or do I just need to open a terminal, goto venv/lib/python2.7/site-packages and run the clone command?
Here's the repository i'm trying to clone https://bitbucket.org/basti/python-amazon-product-api/src

A: Use the -e flag and specify a git repo:
pip install -e git://github.com/manojlds/mylib.git#egg=mylib

The url above can be bitbucket, github etc.

-e, --editable <VCS+REPOS_URL[@REV]#EGG=PACKAGE>
                                Install a package directly from a checkout. Source will be checked
                                out into src/PACKAGE (lower-case) and installed in-place (using
                                setup.py develop). You can run this on an existing directory/checkout
                                (like pip install -e src/mycheckout). This option may be provided
                                multiple times. Possible values for VCS are: svn, git, hg and bzr.

A: clone repository,

*

*if your app is has setup.py, then run python setup.py install
when virtual env is actived.

*else copy this app inside you django project and add name of it your INSTALLED_APPS in settings.py
or you can use pip install -e <repo_addr>, see doc.


text:
Q: how to sorting dojo/multiselect list I have a two MultiSelect lists, can the left list be sorted after I move any value from right list to left?
button= new Button({
    label: "move left",
    onClick: lang.hitch(this, function(){
    dijit.byId(leftListId).addSelected(dijit.byId(rightListId));
})

A: You can't, at least not directly. The MultiSelect is one of the simplest widgets I think and is just a wrapper.
This means that there are no special features included and if you want to have a sort functionality you will have to make one by yourself.
The best way of making one by yourself is by extending the widget. An example:
declare("dijit/form/MultiSelect", [MultiSelect], {
    sort: function() {
        var domNodes = Array.prototype.slice.call(this.containerNode.children);
        domNodes.sort(function(a, b) {
            if (a.innerHTML < b.innerHTML) {
                return -1;
            } else if (a.innerHTML == b.innerHTML) {
                 return 0;
            } else {
                return 1;
            }
        });
        this.containerNode.innerHTML = "";
        array.forEach(domNodes, function(node) {
           this.containerNode.appendChild(node);
        }, this);
    }
});

What this does is pretty easy. We add a function called sort() and then we just retrieve a list of all children, sort these children with the sort() function of an array and then we remove all children and add the sorted children.
To use it you can now do something like: dijit.byId(leftListId).sort() right after you executed your addSelected().
An example JSFiddle can be found here.


text:
Q: Cannot read property 'find' of undefined, dexie async await Проблема возникает из-за того, что получение данных из бд происходит медленно, без async\await получается, что чтение из бд слишком медленное.
В componentWillMount() вылезает ошибка Cannot read property 'find' of undefined, потому что getfieldsets() не успевает отработать к этому времени (как я понимаю)
async function fieldsetsWork(){
    //объявление переменных
    var k=0;
    var string = '';
    var def = getFields().map((it,i)=>({
            name:it.name,
            hidden: false,}));
    var stringDef ='';
    for (var i=0;i<def.length;i++){
        stringDef = stringDef + def[i].name;
    }
    // проверка на существование филдсетов пользователя
    var pushDbUser = Dexie.async(function* (){
        try {
            var p = yield db.table('fieldsets').each(function(element){
                if (element.f_Uname.includes(global.currentUser.value.login.toString())){
                    fieldsets_.push(element);
                    k++;
                }});
            yield p;
            yield console.log('null',fieldsets_);
            yield console.log(fieldsets_[0]);
        } finally { return 0; }
    })

    await pushDbUser().catch(e => console.error(e));

    // проверка версии
    if (k !== 0){
        for (var i=0;i<fieldsets_[0].data.length;i++){
        string = string +fieldsets_[0].data[i].name; }
        if (string == stringDef){ k = k;
        }else k = 0;
    };
    await console.log(k);
    // если нет филдсетов добавляем дефолтные
    var pushFDB = Dexie.async(function* (){
        try {
            var p = yield db.table('fieldsets').each(element =>{
            console.log(element)
                if (element.f_Uname.includes('default')){
                fieldsets_.push(element);
                console.log(element);
            }})
            yield p;
            yield console.log('null2',fieldsets_);
            yield console.log(fieldsets_[0]);
            yield console.log('0');
        } finally { return 0; }
    })
    if (k===0){
        await console.log('k=0')
        await pushFDB().catch(e => console.error(e));
        }
    await localStorage.setItem('requirements_fieldsets', JSON.stringify(fieldsets_))
    var p = await fieldsets_.forEach(fieldset=>
        fieldset.data.forEach(field=> field.def = getFields().find(it=> it.name===field.name)));
    fieldsets =  p;
     return  fieldsets_;
}
fieldsetsWork();

export function getFieldsets(force){
    if(force){
        const fieldsets_ = fieldsetsWork(); //JSON.parse(localStorage.getItem('requirements_fieldsets'));
        fieldsets_.forEach(fieldset=>
            fieldset.data.forEach(field=> field.def = getFields().find(it=> it.name===field.name)));
        fieldsets = fieldsets_
    }
    return fieldsets
}

componentWillMount(){
        this.setState(old=>({
            ...old,
            fieldset: getFieldsets().find(it=>it.favourite)
        }));
    }

A: У вас есть два варианта, при данной структуре организации кода.
Вызвать await fieldsetsWork(). Тогда остальная часть кода не будет выполняться, будет ожидать. На самом деле не очень хороший вариант.
async function fieldsetsWork(){
    //объявление переменных
    var k=0;
    var string = '';
    var def = getFields().map((it,i)=>({
            name:it.name,
            hidden: false,}));
    var stringDef ='';
    for (var i=0;i<def.length;i++){
        stringDef = stringDef + def[i].name;
    }
    // проверка на существование филдсетов пользователя
    var pushDbUser = Dexie.async(function* (){
        try {
            var p = yield db.table('fieldsets').each(function(element){
                if (element.f_Uname.includes(global.currentUser.value.login.toString())){
                    fieldsets_.push(element);
                    k++;
                }});
            yield p;
            yield console.log('null',fieldsets_);
            yield console.log(fieldsets_[0]);
        } finally { return 0; }
    })

    await pushDbUser().catch(e => console.error(e));

    // проверка версии
    if (k !== 0){
        for (var i=0;i<fieldsets_[0].data.length;i++){
        string = string +fieldsets_[0].data[i].name; }
        if (string == stringDef){ k = k;
        }else k = 0;
    };
    await console.log(k);
    // если нет филдсетов добавляем дефолтные
    var pushFDB = Dexie.async(function* (){
        try {
            var p = yield db.table('fieldsets').each(element =>{
            console.log(element)
                if (element.f_Uname.includes('default')){
                fieldsets_.push(element);
                console.log(element);
            }})
            yield p;
            yield console.log('null2',fieldsets_);
            yield console.log(fieldsets_[0]);
            yield console.log('0');
        } finally { return 0; }
    })
    if (k===0){
        await console.log('k=0')
        await pushFDB().catch(e => console.error(e));
        }
    await localStorage.setItem('requirements_fieldsets', JSON.stringify(fieldsets_))
    var p = await fieldsets_.forEach(fieldset=>
        fieldset.data.forEach(field=> field.def = getFields().find(it=> it.name===field.name)));
    fieldsets =  p;
     return  fieldsets_;
}
await fieldsetsWork();

export function getFieldsets(force){
    if(force){
        const fieldsets_ = fieldsetsWork(); //JSON.parse(localStorage.getItem('requirements_fieldsets'));
        fieldsets_.forEach(fieldset=>
            fieldset.data.forEach(field=> field.def = getFields().find(it=> it.name===field.name)));
        fieldsets = fieldsets_
    }
    return fieldsets
}

componentWillMount(){
        this.setState(old=>({
            ...old,
            fieldset: getFieldsets().find(it=>it.favourite)
        }));
    }

Есть другой вариант, получше. Не вызывать отдельно fieldsetsWork, а запустить getFieldsets с  параметром force=true. Также переделать fieldsetsWork на асинхронную.
async function fieldsetsWork(){
    //объявление переменных
    var k=0;
    var string = '';
    var def = getFields().map((it,i)=>({
            name:it.name,
            hidden: false,}));
    var stringDef ='';
    for (var i=0;i<def.length;i++){
        stringDef = stringDef + def[i].name;
    }
    // проверка на существование филдсетов пользователя
    var pushDbUser = Dexie.async(function* (){
        try {
            var p = yield db.table('fieldsets').each(function(element){
                if (element.f_Uname.includes(global.currentUser.value.login.toString())){
                    fieldsets_.push(element);
                    k++;
                }});
            yield p;
            yield console.log('null',fieldsets_);
            yield console.log(fieldsets_[0]);
        } finally { return 0; }
    })

    await pushDbUser().catch(e => console.error(e));

    // проверка версии
    if (k !== 0){
        for (var i=0;i<fieldsets_[0].data.length;i++){
        string = string +fieldsets_[0].data[i].name; }
        if (string == stringDef){ k = k;
        }else k = 0;
    };
    await console.log(k);
    // если нет филдсетов добавляем дефолтные
    var pushFDB = Dexie.async(function* (){
        try {
            var p = yield db.table('fieldsets').each(element =>{
            console.log(element)
                if (element.f_Uname.includes('default')){
                fieldsets_.push(element);
                console.log(element);
            }})
            yield p;
            yield console.log('null2',fieldsets_);
            yield console.log(fieldsets_[0]);
            yield console.log('0');
        } finally { return 0; }
    })
    if (k===0){
        await console.log('k=0')
        await pushFDB().catch(e => console.error(e));
        }
    await localStorage.setItem('requirements_fieldsets', JSON.stringify(fieldsets_))
    var p = await fieldsets_.forEach(fieldset=>
        fieldset.data.forEach(field=> field.def = getFields().find(it=> it.name===field.name)));
    fieldsets =  p;
     return  fieldsets_;
}
fieldsetsWork();

export async function getFieldsets(force){
    if(force){
        const fieldsets_ = await fieldsetsWork(); //JSON.parse(localStorage.getItem('requirements_fieldsets'));
        fieldsets_.forEach(fieldset=>
            fieldset.data.forEach(field=> field.def = getFields().find(it=> it.name===field.name)));
        fieldsets = fieldsets_
    }
    return fieldsets
}

componentWillMount(){
        this.setState(old=>({
            ...old,
            fieldset: await getFieldsets(true).find(it=>it.favourite)
        }));
    }


text:
Q: Зависание Ubuntu 18.04 при загрузке Сразу скажу, что являюсь новичком в использовании Linux. У меня возникла такая проблема, что иногда виснет система на том месте, где нужно выбрать профиль входа в систему. Перезагрузка помогает, но через какое-то время опять виснет на том же месте.
Системный раздел установлен на SSD, если это важно. Стоит Ubuntu 18.04.2 LTS, никакой другой системы не стоит. Ноутбук ASUS 556UQ.
Если нужны будут какие-то логи или информация, то опишите какие именно и как их получить.
UPD: добавил логи

Также должен добавить что у меня стоит в ноутбуке сломанная дискретная видеокарта, однако lspci | grep VGA видит только интегрированую. Но всё же, есть вероятность что в дискретке тоже может быть причина проблемы и таких логов?

A: Помог совет @PavelGridin, после удаления nouveau в логах больше не было огромного количества ошибок и система начала запускаться быстрее и без зависания.


text:
Q: How to set table dimensions and spacing in word using apache poi in java I am trying to generate a word document with a table. There is only one page page and it has 5 rows and 2 columns. I am using the letter page and the size is 8.5" x 11". And I gave the margins to the program.
Here is my code,
    XWPFDocument xWPFDocument = new XWPFDocument();

    CTSectPr cTSectPr = xWPFDocument.getDocument().getBody().addNewSectPr();
    CTPageMar cTPageMar = cTSectPr.addNewPgMar();
    cTPageMar.setLeft(BigInteger.valueOf(475));
    cTPageMar.setTop(BigInteger.valueOf(720));
    cTPageMar.setRight(BigInteger.valueOf(446));
    cTPageMar.setBottom(BigInteger.valueOf(605));

    XWPFTable xWPFTable = xWPFDocument.createTable(5, 2);
    xWPFTable.getCTTbl().getTblPr().unsetTblBorders();

    xWPFTable.setTableAlignment(TableRowAlign.CENTER);
    xWPFTable.setWidth("100%");

And I am setting cell width and row height using the following code. But I am not noticing any change.
    XWPFTableRow xWPFTableRow;

    for (int i = 0; i < 5; i++) {
        xWPFTableRow = xWPFTable.getRow(i);

        xWPFTableRow.setHeight(2880);
        xWPFTableRow.getCell(i).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(6033));
    }

What I am looking for is how to set Horizontal and Vertical Spacing also is there a way to set Horizontal and Vertical Pitch using Apache POI?

A: The current apache poi 4.1.2 provides a method setWidth(java.lang.String widthValue) where widthValue can be a String giving a percentage width in XWPFTable as well as in XWPFTableCell.
Setting the cell spacing is not supported directly until now. So underlying ooxml-schemas classes must be used for this.
Complete example:
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

public class CreateWordTableCellSpacing {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("The table");

  int cols = 3;
  int rows = 3;
  XWPFTable table = document.createTable(rows, cols);

  table.setWidth("100%");
  table.getRow(0).getCell(0).setWidth("20%");
  table.getRow(0).getCell(1).setWidth("30%");
  table.getRow(0).getCell(2).setWidth("50%");

  //set spacing between cells
  table.getCTTbl()
   .getTblPr()
   .addNewTblCellSpacing()
   .setType(
     org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth.DXA
   );
  table.getCTTbl()
   .getTblPr()
   .getTblCellSpacing()
   .setW(java.math.BigInteger.valueOf(
     180 // 180 TWentieths of an Inch Point (Twips) = 180/20 = 9 pt = 9/72 = 0.125"
   ));

  paragraph = document.createParagraph();

  FileOutputStream out = new FileOutputStream("CreateWordTableCellSpacing.docx");
  document.write(out);
  out.close();
  document.close();

 }
}


text:
Q: WP7 app that saves user settings Sorry, this is a noobish question, but I was wondering where I would start if I wanted to create an app that saved the users settings from each time the app was openned. For example if I had a user who wanted to enter their favorite book into a text box and then that was saved to some array list that would save their previous entries what would be the best way to go about this task? Thank you for your time and looking and help! Also I would be doing this in c#.

A: You can use IsolatedStorageSettings to store preference data. You can refer following link:
http://msdn.microsoft.com/en-us/library/cc221360(v=vs.95).aspx
Below is sample code snippet:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
// txtInput is a TextBox defined in XAML.
if (!settings.Contains(key))
 {
     settings.Add(key, value);  // adding new value
     settings.Save();
 }

A: Properties.Settings
In your application configuration file. Use the project properties section to add parameters.
Right click "" in Visual studio -> Click "Properties" -> On the left pane of project properties tab you can find "Settings" section.

A: your options are :
Database:
-http://www.codeproject.com/Tips/378657/Quickest-Way-to-Create-a-NET-Database-Application
-Or file storage.
-Or XML file.

A: While many things are different for WP8, the persistent settings mechanisms are backwardly compatible. Do the relevant part of this course: http://www.microsoftvirtualacademy.com/training-courses/windows-phone-8-apps-development-jumpstart
I'd ask why you are writing new code for an obsolete platform but I expect the reason is that you own a WP7. While there are undoubtedly many WP7 units around giving good service, the people still using them are people who resist buying stuff, so they are not your market. I heartily recommend picking up a Nokia Lumia 520, which can be had new for $AU150 and probably even cheaper in the US. Or you could go upmarket if you have the cash and inclination.
Unlike a budget Android phone, a budget WP8 phone has a very similar user experience to a high end phone; the differences are primarily absence of sensors like magnetic compass, RFID and gyros. The 520 isn't silky like my 920, but it's quite usable, whereas the budget Android phone I use for testing apps is truly a horror. Which is, I imagine, the reason the 520 is taking the European budget smartphone market by storm.


text:
Q: sharing video on ios using fb sdk I am very new to programming in iOS and therefore, the question might seem rather stupid but I really do not know what is wrong.
So, I was following sharing in iOS on the https://developers.facebook.com/docs/sharing/ios and I was successful in sharing link, and photo. But I have no idea why I cannot share a video. I am not using UIImagePickerControllerReferenceURL but instead, I am using [[NSBundle mainBundle] URLForResource:@"xyz" withExtension:@"mp4"] for the videoURL.
Is this the reason why the sharing button doesn't work?
My aim is to let users share content from the app directly. So I do not want them to use UIImagePickerControllerReferenceURL.
Here is the code:
NSURL* videoURL = [[NSBundle mainBundle] URLForResource:@"xyz" withExtension:@"mp4"];
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;

FBSDKShareButton *button = [[FBSDKShareButton alloc] init];
button.center = self.view.center;
button.shareContent = content;
[self.view addSubview:button];

And file xyz.mp4 is in a Media Folder.

A: NSURL* videoURL = [[NSBundle mainBundle] URLForResource:@"xyz" withExtension:@"mp4"];

replace with this
NSURL* videoURL = [[NSBundle mainBundle] URLForResource:@"xyz" ofType:@"mp4"];

[self saveToPhotoAlbum:videoURL];

After that save this video to photo library as Facebook required asset library url.
-(void)saveToPhotoAlbum:(NSURL*)url
{
NSLog(@"srcURL: %@", url);

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    ALAssetsLibraryWriteVideoCompletionBlock videoWriteCompletionBlock =
    ^(NSURL *newURL, NSError *error) {
        if (error) {
            NSLog( @"Error writing image with metadata to Photo Library: %@", error );
        } else {
            NSLog( @"Wrote image with metadata to Photo Library %@", newURL.absoluteString);
            url_new  = newURL;
        }
    };

    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:url])
    {
        [library writeVideoAtPathToSavedPhotosAlbum:url
                                    completionBlock:videoWriteCompletionBlock];
    }
}

then
FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc] init];
NSURL *videoURL = url_new;
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
shareDialog.shareContent = content;
shareDialog.delegate = self;
[shareDialog show];


text:
Q: How can I avoid the player from moving through walls? The problem is that the objects that make the space station are too many over 1000 objects. So it's hard to go one by one and add a collider to it.
The player have a Rigodbody and I'm using it to detect when entering a door and collide with the door collider and then open the door/s .
I marked with red circle one part of the space station for example that don't have any collider on it. So the player can move through it.
This is the screenshot also of the player inspector settings :

A: From what I understood from your question is that you don't want the player to pass through the walls. So then when you import an FBX there are import options with a checkbox asking if you want to generate colliders. Just check that off and hit apply.

A: If you only add colliders to walls you'll still very likely hit into the wall when you stand too close. Read the doc about navmesh, it bakes walkable space and autogenerates margin for non-walkable objects. It's thorough enough.
Also check Youtube channels (there are a lot).


text:
Q: Delete a file on a remote machine using bash script I want to basically copy files from remote machines, and after copying, delete them.
I have managed to copy the files using expect and scp.
Also, managed to delete the files outside of the script, but not able to use the ssh command inside the script.
This is what I have
#!/usr/bin/expect -f
log_user 1
set timeout -1
set pass "pass"

spawn scp  user@remote.machine.com:Desktop/LoginCheck/Login/* .
expect {
          password: {send "$pass\r" ; exp_continue}

}
ssh user@remote.machine.com 'rm -rf Desktop/LoginCheck/Login/*'
expect {
          password: {send "$pass\r" ; exp_continue}

}

So the scp section of code works.
But the ssh and rm -rf
this is the error for ssh
invalid command name "ssh"
    while executing

Can someone provide a working script?

A: Shouldn't the ssh command be a new spawn?  By the way, just reading the wikipedia article on expect, one of the "cons" listed is:

A less obvious argument against Expect is that it can enable
  sub-optimal solutions. For example, a systems administrator needing to
  log into multiple servers for automated changes might use Expect with
  stored passwords, rather than the better solution of ssh agent keys.
  The ability to automate interactive tools is attractive, but there are
  frequently other options that can accomplish the same tasks in a more
  robust manner.

Sounds like you're doing exactly the example sub-optimal solution.  If you were using a proper ssh key pair, you wouldn't need expect at all.

A: Replace ssh with spawn ssh - ssh is not a built-in command of expect.

A: You just missed the spawn in front of the ssh line:
spawn ssh user@remote.machine.com 'rm -rf Desktop/LoginCheck/Login/*'

You should also add a wait line before it, potentially checking for the exit code of scp.
In any case, don't use expect to automate ssh, use ssh keys and sh scripts like the other posters described.


text:
Q: Many to many self reference without id numbered I want to make a relationship between two Tags entities, but I don't like the typical way it is handled in the RDBMS databases.
Like here: https://stackoverflow.com/a/35784048/1624397
INSERT INTO RECOMMENDED_BOOKS (Book_id1, Book_id2) VALUES (1, 2)
INSERT INTO RECOMMENDED_BOOKS (Book_id1, Book_id2) VALUES (1, 3)

Book_id1, Book_id2...
Or another "bad" example I'm looking for an alternative to (which makes sense in this case, anyway):
Self-referencing to a User friendsWithMe and myFriends.
If I do something like tag_id1 and tag_id2 I either will be forced to search for whether there is a relation between both twice, or be forced to keep redundant data.
Is there any alternative solution?
Preferably the solution was storage-agnostic.

A: If I understand correctly, you have a problem with symmetric relationships since there are two ways to represent any pair of associated tags. Recording both ways result in redundant data, e.g. (1, 2) represents the same relationship as (2, 1). Recording only one of the two, without a symmetry-breaking rule, requires more complex queries, e.g. WHERE (tag_id1, tag_id2) IN ((1, 2), (2, 1)).
The trick is to introduce a symmetry-breaking rule, e.g. tag_id1 <= tag_id2. When inserting / updating data, you have to enforce the rule. That's easy if your DBMS supports check constraints, if not, you can consider using a trigger to do the same.
This simplifies queries - you can sort the arguments you want to search for so that you only have to search for a single permutation, e.g. (1, 2).
Perhaps one day we'll have DBMSs with optimized storage engines for symmetric relationships, trees, and so on.

A: I'm not aware of a way to solve many-to-many table without data redundancy and have simple queries in relational databases.
You could cheat and create a view that duplicates the data on query time, and it would look something like this:
CREATE VIEW VW_Friends
AS
SELECT PersonID, FriendID
FROM Friends
UNION
SELECT FriendID, PersonID
FROM Friends

I believe that would be slow and not-very-intuitive and I wouldn't generally recommend it, but it is a possible solution.
In your place I would go with redundant data, because that would be optimized for SELECTing data and in most cases table like this will have many more reads than writes.
If that is not the case and you have more writes than reads - don't duplicate the data and have awkward SELECTs with queries on both columns.
I hope this helps.


text:
Q: What is the best way to check correct dtypes in a pandas dataframe as part of testing? Before pre-processing and training a model on some data, I want to check that each feature (each column) of a dataframe is of the correct data type. i.e. if a dataframe has columns col1, col2, col3, they should have types int, float, string respectively as I have defined them (col1 can't be of type string, the order matters).
What is the best way to do this if

*

*The columns have various types - int, float, timestamp, string

*There are too many columns (>500) to manually write out / label each column data type

Something like
types = df.dtypes # returns a pandas series
if types != correct_types:
    raise TypeError("Some of the columns do not have the correct type")

Where correct_types are the known data types of each column - these would need to be in the same order as types to ensure each column type is correctly matched. It would also be good to know which column is throwing the error (so maybe a for loop over the columns is more appropriate?)
Is there any way to achieve this, and if so what is the best way to achieve this? Maybe I am looking at the issue the wrong way - more generally, how do I ensure that the columns of df are of the correct data type as I have defined them?

A: You can use pd.DataFrame.dtypes to return a series mapping column name to data type:
df = pd.DataFrame([[1, True, 'dsfasd', 51.314],
                   [51, False, '56345', 56.1234]],
                  columns=['col1', 'col2', 'col3', 'col4'])

res = df.dtypes

print(res)

col1      int64
col2       bool
col3     object
col4    float64
dtype: object

The values of this series are dtype objects:
print(res.iloc[0])

dtype('int64')

As a series, you can filter by index or by value. For example, to filter for int64 type:
print(res[res == np.dtype('int64')])

col1    int64
dtype: object

You can also compare the series to another via series1 == series2 to create a Boolean series mapping. A trivial example checking the series with itself:
# in reality, you will check res versus a custom series_valid
print(res == res)

col1    True
col2    True
col3    True
col4    True
dtype: bool

If any values in your comparison is False, you can raise an error:
if (res != series_valid).any():
    indices = (res != series_valid).index.tolist()
    raise TypeError("Some columns have incorrect type: {0}".format(indices))


text:
Q: Apply a function to a range of cells in a spreadsheet The answers in topics with similar titles haven't given me much of a resolution to my particular problem, but possibly I am not asking the right question. It might help knowing I'm an absolute noob when it comes to spreadsheets, so finding my way around is next to nil.
Currently I can set a basic function in the first cell A1 =ROW()
Simple right? Well now here comes the complication. If I click on the bottom right of the cell and start dragging I can then apply that very same function to a whole range of cells. Let's say I apply it from A1:A10. Every cell within this group now has the same function.
Hooray! We did it, right? I applied a function to a range of cells each with their own output. But wait, if I then go back to the original cell and change its formula none of the other cells change with it. GRRRRR!!!!
There are a couple of fixes I've come up with but don't necessarily know how to implement. The first is to have every cell link back to the original cell and reference its function. This would be useful if I wanted to randomly scatter dependent cells about the document. The other would be much more useful in an orderly group where you know the exact dimensions by specifying in the original cell the size of the array you want to apply the function to.
With that said, let me hear your thoughts.

The closest I've come to an answer is to use FORMULA() which returns the formula used by a cell as text. Unfortunately all answers on evaluating the text resort to scripting. How strange! I thought something like this would be common. Might as well get to scripting.

Hold on, I may have spoke too soon. An array can be made with =MUNIT(), but it's only square. Drats!

Ok... I'm hoping the zebra stripes will eventually become its own answer unless someone else beats me to it. So a simple array can be made with ={1,2;3,4} where commas separate values by column and semicolons for values by row except to generate it you have to press Control+Shift+Enter (because reasons?). I'm thinking now that I'll need to have functions that can generate lists of values based on a single function for each row, and pray that it'll work. So, back to looking. (Wow this is taking forever)

The way I was hypothesizing can't even generate a 1x1, e.g., ={ROW()} returns Err:512 which is a formula overflow.

Alright, in summary so far I've narrowed down the two options,
1) link every cell to the original formula
2) populate an array with a single formula

each with their own incomplete answer,
a) use FORMULA() to return the formula of a cell as text
b) create a hypothetical array like so ={LIST_OF_VALUES()}

These both require a strange form of the nonexistent EVALUATE() function to 'function' correctly. Isn't that fun?

Google Sheets handles case b by allowing ={ROW()}Control+Shift+Enter to generate =ArrayFormula({ROW()}). Working with the general case of any sized array being filled with a single function doesn't exist in the world of spreadsheets it seems. That's very saddening because I can't think of a much better tool for what I want to do. Copy paste it is until I need to use macros.

A: Depending on your specific use case, creating a user-defined function may help:

*

*use the Basic IDE to create your function;

*apply it to any cells on any sheet;

*modifying the Basic code will affect all cells where the function is used.

I've elaborated the steps in an answer on superuser.

A: Sure, you could write some complex code to update functions, but wouldn't the easy way be just to drag it to the same range of cells the same way you did before? It should properly overwrite the existing code in there, and if it doesn't, you can just as easily delete the outdated code and drag the new code in.

A: Probably the best approach is to simply drag the amended formula over the range of cells (as advised by OldBunny2800). This is less error prone and easier to maintain than a custom macro.
Another option would be to use an array function. Then you only have to edit the function once, and the same edit will be automatically applied to the whole range of cells in that array function.


text:
Q: Passing Dynamic Data to Bootstrap Modal Angular 4 I have a list of objects that I am am passing information from to a bootstrap modal. Modal looks like this:
  <button
class="btn btn-primary btn-xs"
data-toggle="modal"
data-target="#matchModal"
(click)="matchSearch()">
Select</button>

    <button type="button" class="close" data-dismiss="modal" aria-
  label="Close">×</button>

Card Matches

      <input type="checkbox">

{{matchBrandCard.title}}

{{matchBrandCard.uuid}}

    <button type="button" class="btn btn-info">Create</button>
    <button type="button" class="btn btn-success">Merge</button>
    <button type="button" class="btn btn-default" data-
 dismiss="modal">Close</button>

Update
In my component:
matchBrandCards: Card[] = [];

matchSearch() {
this.clientCardsService.fetchBrandCards(this.clientCards.title).subscribe(
  clientCards => {
    this.matchBrandCards = clientCards;
  }
);

}
clientCards is the list that provides the necessary parameters for my http request to then create matchBrandCards.
My problem is that the information gets passed to the modal the first time correctly but when I select other items from the list, the modal does not update with the new selected information. Everything is working with updating the matchBrandCards that I iterate over to create the list in the modal but the displayed values stay the same. Looking for a way to achieve my desired functionality.
Suggestions || tips would be much appreciated.

A: Change your matchBrandCards to a subject and use async:

in the containing component:
public matchBrandCards$ = new Subject();

and then when you have an update:
updateHandler(values) {
  this.matchBrandCards$.next(values);
}


text:
Q: Grails RemoteFunction params syntax I'm trying to pass a couple of parameters to a remoteFunction in grails but I'm struggling to format it correctly
I want to pass in the value of a piece of data on the page plus the value of the text box that I have just tabbed out of, so in my onblur I have something along the lines of :
onblur=${remoteFunction(action:'dave',  update:'pack'+it.id,
         params:[denom:document.getElementById(denomValue+${it.id}).value ,
         amount:this.value ])}

This doesn't compile - neither do any permutations I can come up with with varying numbers of single quotes and escape characters ..
I think what is really stumping me is thatI don;t really understand what I am trying to create here. Is it like using JSP code to create JavaScript which iwill be later executed? When does this expression get evaluated - it is at the time the page is compiled - or is a=it at the time that oblur gets called?
Any help greatly appreciated.

A: It looks like you've mixed up server-side code with client-side code.
The Grails code will be evaluated when the page is being "built" to be sent to the client browser.
The Javascript code will be evaluated once the page has been delivered to the browser.
With this in mind let's take a look at your onblur assignment:
onblur=${remoteFunction(
         action:'dave',
         update:'pack'+it.id,
         params: [denom: document.getElementById(denomValue+${it.id}).value,
                  amount: this.value ])}

Given the ${remoteFunction...} call is a Grails tag, it will be evaluated on the server, generate a fixed string, then be sent to the client. Everything inside the call must be valid Groovy code.
Look at the params map, you've added some Javascript in the denom value, inside the Groovy code:
document.getElementById(denomValue

then you try to add a value from Groovy
+${it.id}

then some Javascript again
).value

The Groovy compiler will try to evaluate the Javascript as Groovy code and fail.
If you need to access client-side parameters in Javascript you'll need to handle the Javascript yourself (and not use the remoteFunction tag), for example to handle the remote call:
var path=${createLink(action:'dave',
                      params: [amount:this.value])}
           + "&denom="
           + document.getElementById(denomValue+${it.id}).value

You'll also need to handle the remote response yourself using Javascript to update the 'pack' elements. You could always look at what the remoteFunction call generates, copy it into the page and edit it to do what you want.
HTH

A: Or you can pass the parameters separated by '&' like
params:'\'param1=\'+this.value+\'&booleanParam2=true\''

A: You can actually still use the remote function tag, you just have to write the parameters in a javascript object string, so this actually works quite well in stuff that I work with.
var denomValue = document.getElementById(denomValue+${it.id}).value;
onblur=${remoteFunction(
     action:'dave',
     update:'pack'+it.id,
     params: '{denom: denomValue, amount: this.value}'
     )}

A: <button type="button" class="btn btn-success" id="value-pie" onClick="ajaxFunction(this.value)">Confirmar</button>

<script>
function ajaxFunction(id){
     var obs = $("#observacion").val()
     var parameters = { "serieId":id,
                        "observacion":obs
                      }
     <g:remoteFunction controller="control"
                  action="ajax"
                  method="GET"
                  onSuccess="updateModal(data)"
                  params="parameters"/>
}
</script>

A: I had the same problem but all answers above did not help as the value I want to get are the selected value from the selection dropdown as well as the obj instance inside table that was being iterated. below was the solution.
<g:select
                                             from="${list}"
                                      optionKey="value"
                                      optionValue="key"

                                      onchange="getValue(this.value, ${instance.id})"/>

    <script type="text/javascript">
              function getValue(Id1, Id2)
              {

                  $.ajax({
                      type: 'POST',
                      url: '/app/controller/functionToCall',
                      data: { someId: Id1, otherId:Id2},

                  });

              }


text:
Q: Adding new class to project programmatically I read files from disc in my Java project. I find my hohoho.java file on D:/ and it's in File format, then I would like to add it as a class to existing package with my main class (Up.java). It should look like this - package -> Up.java, Hohoho.java.
And it should be done programmatically of course. I will use this .java file and it's functions in my Up.java.
Do you know any easy way to do this?
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;

public class Up{

public static void main(String[] args) {

    File root = new File("..\\.");
    File myfile = null;

    try {

        String[] extensions = {"java"};
        boolean recursive = true;

        Collection files = FileUtils.listFiles(root, extensions, recursive);

        for (Iterator iterator = files.iterator(); iterator.hasNext();) {
            File file = (File) iterator.next();
            String path = file.getAbsolutePath();
            System.out.println("File = " + path);

            String[] tokens = path.split("\\\\");

            for (String t : tokens)
              if (t.equals("Hohoho.java")){
                  myfile = file;
              }
            }

        System.out.println("Client class: " + myfile.getAbsolutePath());

    } catch (Exception e) {
        e.printStackTrace();
    }

   }
}

A: Use Java Compiler API to compile source code into bytecode.

After that use ClassLoader to load compiled class into jvm and you're be able to execute methods of that class.

If you sure, that compiled class implements specific interface - you can cast it to target interface and call methods directly, otherwise - you're need to use Reflection

A: If you only need to load a .class file, per your comment, you should be able to just use something like the following (assuming no security issues in your setup):
    String path = "/path/to/your/classfiles/root/"; //not including the package structure
    ClassLoader loader = new URLClassLoader(new URL[]{new URL("file://" + path)}, Up.class.getClassLoader());

    Class clazz = loader.loadClass("foo.Hohoho"); //assuming a package "foo" for that class
    Object loadable = clazz.newInstance();
    Field field = loadable.getClass().getField("someField");  //or whatever - (this assumes you have someField on foo.Hohoho)

    System.out.println(field.get(loadable));

(I dropped all exception handling in the above).  As @stemm pointed out, this is going to be painful to work with, just using pure Reflection.
Also, a quick test of invoking the java compiler, in the least complicated way possible, from within the VM follows.  So, if case you do need to go from source, you can build off this:
    String sourcePath = "/path/to/your/javafiles/root/";
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int success = compiler.run(null, null, null,  sourcePath + "foo/Loadable.java");//can't get "-sourcepath","path" to go, for some reason.

    System.out.println("success = " + success); //should be 0; Sys err should have details, otherwise


text:
Q: Render a row's dataTable after clicking its commandLink I have a commandLink in pageBlockTable.  When I click it, I want the dataTable in the same pageBlockTable to render.
At present I can render all records when I click on the commandLink.
My requirement is to render just that particular record's dataTable.
Here is my VF page.
<apex:page controller="repeatcontroller1" sidebar="false">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable value="{!CallplanAccounts}" var="status" border="0" cellpadding="6"    cellspacing="13" columnsWidth="3">

            <apex:column headerValue="Name">
                {!status.acc.Name}
            </apex:column>

            <apex:column headerValue="Status">
                {!status.acc.Active__c}
            </apex:column>

            <apex:column >
                <apex:commandLink action="{!Callstatus}" id="renderit" >
                    CallString<apex:param name="cmid" value="{!status.acc.id}" assignTo="{!approveid}" />
                </apex:commandLink> <br/>

                <apex:pageblocksection collapsible="false" rendered="{!visible_comment =='show'}" >

                    <apex:dataTable value="{!status.acc.Call__r}" var="cm" >
                        <apex:column headerValue="Callstring name" >
                            {!cm.name}
                        </apex:column>

                        <apex:column headerValue="Origianl values" >
                            {!cm.Original_Call__c}
                        </apex:column>

                        <apex:column headerValue="Updated values" >
                            <apex:outputField value="{!cm.Updated_Call__c }" >
                                <apex:inlineEditSupport event="ondblClick" showOnEdit="saveButton" / >
                            </apex:outputfield>
                        </apex:column>
                    </apex:dataTable>
                </apex:pageblocksection>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>

A: It really all depends on the list that is being used to render the datatable. At present you are using status.acc.call__r. This, presumably, is unaffected by the specific commandLink that is clicked (status.acc.id).
Instead, consider using a custom list that is generated by the controller specifically in response to the controller's approveid variable (to which status.acc.id is bound). Then, you would simply populate this list in the CallStatus action method.

A: Given that you'd need to specify a unique ID for the rerender I think you're out of luck with this one. The only real way to achieve the result you want would be to use a different architecture for the page, rolling your own version of the page block table where you can control the rendering.
One option that could work well here is javascript remoting, where you could replace/update the specific entry for the updated record when the call to the apex method completes.


text:
Q: Bash script deletes first row in csv during editing with 'cut' I have little problem with my bash script. The script is cloning repositories to my local folder and then search for files with specified extensions in those repositories (results are CSVtemporary2/ASSETS-LIST-"$dir".csv) , then edits results (cuts first 4 elements of paths, results are:/CSVtoGD2/"$dir".csv)
In the CSV there are paths to files in every single row ex. /users/krzysztofpaszta/temporaryprojects/gamex/car1.png
/users/krzysztofpaszta/temporaryprojects/gamex/sound1.mp3
(...)
Every part of the script is working fine but after cutting the first 4 elements of paths the first row is deleted.. I do not know why this is happening.
So results should be:
/car1.png
/sound1.mp3
(...)
But results are:
/sound1.mp3
(...)
I do not know why this is happening.
So in other words, files CSVtemporary2/ASSETS-LIST-"$dir".csv are fine but then, files
/CSVtoGD2/"$dir".csv have first row deleted.. Someone has idea why this is happening?
#!/bin/bash
rm -vrf /Users/krzysztofpaszta/CSVtoGD2/*
rm -vrf /Users/krzysztofpaszta/CSVtemporary2/*
cd /Users/krzysztofpaszta/temporaryprojects
for repo in $(cat /users/krzysztofpaszta/repolinks.csv); do
    git clone "$repo"
    dir=${repo##*/}
    find /users/krzysztofpaszta/temporaryprojects/"$dir" -name "*.fnt" -o -name "*.png" -o -name "*.ttf" -o -name "*.asset" -o -name "*.jpeg" -o -name "*.tga" -o -name "*.tif" -o -name "*.bmp" -o -name "*.jpg" -o -name "*.fbx" -o -name "*.prefab" -o -name "*.flare" -o -name "*.ogg" -o -name "*.wav" -o -name "*.anim" -o -name "*.mp3" -o -name "*.tiff" -o -name "*.otf" -o -name "*.hdr" >> /users/krzysztofpaszta/CSVtemporary2/ASSETS-LIST-"$dir".csv
    while read in ; do
      cut -d'/' -f6- >> /users/krzysztofpaszta/CSVtoGD2/"$dir".csv #| awk 'BEGIN{print"//"}1' - adding first empty row is not the solution, first row with text is still deleted
    done < /users/krzysztofpaszta/CSVtemporary2/ASSETS-LIST-"$dir".csv
done
#rm -vrf /Users/krzysztofpaszta/temporaryprojects/*
#echo Repo deleted

A: Your syntax
while read in ; do
    cut -d'/' ^f6- >> /users/krzysztofpaszta/CSVtoGD2/"$dir".csv
done < /users/krzysztofpaszta/CSVtemporary2/ASSETS-LIST-"$dir".csv

will not work as you expect.
The read command reads the first line of the csv file
assigning a variable in to it.
Then the remaining lines are fed to cut command via stdin.
Instead you can say;
while IFS= read -r line; do
    cut -d'/' ^f6- <<< "$line" >> /users/krzysztofpaszta/CSVtoGD2/"$dir".csv
done < /users/krzysztofpaszta/CSVtemporary2/ASSETS-LIST-"$dir".csv

Actually you don't even need to use the while loop:
cut -d'/' ^f6- < /users/krzysztofpaszta/CSVtemporary2/ASSETS-LIST-"$dir".csv > /users/krzysztofpaszta/CSVtoGD2/"$dir".csv

Besides there are many points to be improved:

*

*There may be a typo in either of the pathnames /Users or /users.

*You can use the while .. read .. loop instead of
for repo in $(cat path/to.csv)

*You don't need to create a temporary file for the output of find.
You can feed the output directly to cut command via a pipeline.


text:
Q: Python Virtual Environment Batch File Execution failing on Windows and not giving correct result I have created the batch file to create python virtual environment and run the Gauge command but its failing.
I want to create Virtual Environment then activate it and then i want to run last Gauge command

*

*pip install virtualenv

*cd c:\pyrates

*mkdir TSU-Virtual-Environment

*cd TSU-Virtual-Environment

*python -m venv TSU-MINI-PROJECT

*timeout 5

*cmd /k "cd \d C:\Pyrates\TSU-Virtual-Environment\TSU-MINI-PROJECT\Scripts & activate.bat & timeout 5 & pip install -r requirements.txt & cd \d c:\Pyrates & gauge run --env Editor --tags 'wp_usersToCSV' specs"

*pause

Error:
C:\Pyrates\scripts>pip install virtualenv
Requirement already satisfied: virtualenv in c:\python37\lib\site-packages (20.0.35)
Requirement already satisfied: appdirs<2,>=1.4.3 in c:\python37\lib\site-packages (from virtualenv) (1.4.4)
Requirement already satisfied: filelock<4,>=3.0.0 in c:\python37\lib\site-packages (from virtualenv) (3.0.12)
Requirement already satisfied: six<2,>=1.9.0 in c:\python37\lib\site-packages (from virtualenv) (1.15.0)
Requirement already satisfied: distlib<1,>=0.3.1 in c:\python37\lib\site-packages (from virtualenv) (0.3.1)
Requirement already satisfied: importlib-metadata<3,>=0.12; python_version < "3.8" in c:\python37\lib\site-packages (from virtualenv) (2.0.0)
Requirement already satisfied: zipp>=0.5 in c:\python37\lib\site-packages (from importlib-metadata<3,>=0.12; python_version < "3.8"->virtualenv) (3.3.2)
WARNING: You are using pip version 20.1.1; however, version 20.2.4 is available.
You should consider upgrading via the 'c:\python37\python.exe -m pip install --upgrade pip' command.

C:\Pyrates\scripts>cd c:\pyrates

c:\Pyrates>mkdir TSU-Virtual-Environment
A subdirectory or file TSU-Virtual-Environment already exists.

c:\Pyrates>cd TSU-Virtual-Environment

c:\Pyrates\TSU-Virtual-Environment>python -m venv TSU-MINI-PROJECT

c:\Pyrates\TSU-Virtual-Environment>timeout 5

Waiting for 0 seconds, press a key to continue ...

c:\Pyrates\TSU-Virtual-Environment>cd TSU-MINI-PROJECT

c:\Pyrates\TSU-Virtual-Environment\TSU-MINI-PROJECT>timeout 5

Waiting for 0 seconds, press a key to continue ...

c:\Pyrates\TSU-Virtual-Environment\TSU-MINI-PROJECT>cd Scripts

c:\Pyrates\TSU-Virtual-Environment\TSU-MINI-PROJECT\Scripts>timeout 5

Waiting for 0 seconds, press a key to continue ...

c:\Pyrates\TSU-Virtual-Environment\TSU-MINI-PROJECT\Scripts>cmd /k "cd \d C:\Pyrates\TSU-Virtual-Environment\TSU-MINI-PROJECT\Scripts & activate.bat & timeout 5 & pip install -r requirements.txt & cd \d c:\Pyrates & gauge run --env Editor --tags 'wp_usersToCSV' specs"
The filename, directory name, or volume label syntax is incorrect.

Waiting for 0 seconds, press a key to continue ...
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'
WARNING: You are using pip version 20.1.1; however, version 20.2.4 is available.
You should consider upgrading via the 'c:\pyrates\tsu-virtual-environment\tsu-mini-project\scripts\python.exe -m pip install --upgrade pip' command.
The filename, directory name, or volume label syntax is incorrect.
Specs directory specs does not exists.

(TSU-MINI-PROJECT) c:\Pyrates\TSU-Virtual-Environment\TSU-MINI-PROJECT\Scripts>


text:
Q: Find Max Amount and second max amount for each listings I have a table of bids that I want to query information.
Table structure is:  id, item_id, price, date, user_id
Many user place bids on this table.  I need to find a list of all the item_id with the max   price received and also the second max price receive for the same item.
Here is what I have so far
SELECT item_id, MAX(price) as MAX, (SELECT MAX(price) FROM TABLE GROUP BY item_id, LIMIT 1,1) FROM TABLE WHERE date > 2013-01-01 GROUP BY item_id

What am I missing
This is the result I am getting
item_id    MAX    USER_ID    MAX(PRICE)
1          17222     122       22500
2          15888     161       22500

For all my next items, The second is always  22500, how can I get the real second value for the second best bid?

A: Ok this is tested. Try it:
SELECT t1.item_id,
MAX(t1.price) AS MAX1,
(SELECT t2.price FROM TABLE AS t2 WHERE t2.item_id = t1.item_id ORDER BY t2.price DESC LIMIT 1,1) AS MAX2
FROM TABLE AS t1
WHERE t1.date > 2013-01-01
GROUP BY t1.item_id

A: Here is an alternative mechanism, using a substring_index()/group_concat() trick.  Presumably, you also want the user with the maximum price, which your query does not do.  Try this:
select item_id, max(price) as maxprice,
       substring_index(group_concat(user_id order by price desc), ',', 1) as user_id,
       substring_index(substring_index(group_concat(price order by price desc),
                                       ',', 2),
                       ',', -1) as secondprice
from t
group by item_id;


text:
Q: Block email to addresses that do not exist in postfix We have postfix setup as a gateway to filter and relay mail to our Exchange server. Without setting up LDAP, is there a way for me to define a list of valid addresses so postfix can reject everything that is to our domain, but not to a valid user or alias?
i.e., I want to specify a list of valid emails. If RCPT TO is to anything other than these emails, reject it. I plan on using fail2ban to firewall off these IPs for an hour as punishment for a directory harvest attack attempt.

A: This ended up being remarkably simple.
In a nutshell:

*

*Export a list of your email addresses from exchange using PowerShell.

*Clean that list up so it can be post mapped.

*Create a rule that verifies recipients against that list.

Specifically:
In Exchange EMS, run this command:
Get-Mailbox -Resultsize Unlimited | Ft EmailAddresses

If your email list is huge, then you might want to be a little less forgiving with this command and get yourself a CSV file. This worked for me because we only had around 50, and it was easy to pare this down using Sublime Text and regular expressions.
Using this list, I removed everything from the list except the SMTP addresses, leaving one per line.
Next, in Sublime, I added "OK" to each line after the addresss. Example:
foo@bar.com  OK

Then, I copied this to the Postfix server as /etc/postfix/access-inbound
Then, I ran the following command:
root@gateway:/etc/postfix/# postmap /etc/postfix/access-inbound

This creates access-inbound.db in the directory it is run. (Note above! I did this in /etc/postfix).
Now, all that's left, is to tell Postfix to verify senders using this file. I did this in smtpd_recipient_restrictions. Note, the directive below has a lot of stuff in there. I left the other configs in there for context. First, this config compares the sender to a whiltelist, and then executes a deliver action for that whitelisted sender. Then, it does all the other checks.
Finally, at the bottom, you see:
check_recipient_access hash:/etc/postfix/access-inbound,

This tells postfix: "If the recipient is in this list, accept the mail". (Actually, it says: "if the recipient is in this list, do what the list says. But, in this case, all our valid emails have an "OK" response, so the former is easier to think about for n00b searchers).
Finally, at the bottom, you see reject. This means: "If you have gotten to the bottom of all these checks, and NONE of the checks above gave you an "OK" to accept the mail, reject it.
smtpd_recipient_restrictions = check_sender_access mysql:/etc/postfix/whitelist.cf,
    check_sender_access mysql:/etc/postfix/shortcircuit.cf,
    reject_unverified_recipient,
    reject_invalid_hostname,
    reject_unauth_pipelining,
    reject_unknown_recipient_domain,
    reject_unauth_destination,
    permit_mynetworks,
    permit_sasl_authenticated,
    check_recipient_access hash:/etc/postfix/access-inbound,
    reject


text:
Q: Batch Message Consumption for JMSItemReader-Spring Batch I'm working on a POC where requirement is to consume messages in a batch from a JMS queue and pass it to processor and writer in chain as per Spring batch Step..Spring Batch provides JMSItemReader as a out of box functionality  but looks like it consumes messages one by one until there are no messages left in queue or receiver timeout is reached...As far as Chunk based step is concerned, Items are read into chunks,which are processed and then written within transaction as a chunk into another datastore..Here JMSItemReader doesn't read items in a batch..Is there any solution in Spring Batch world to consume messages in a batch from a queue to improve overall performance of an application?
I tried a lot of documentation but didn't find any appropriate solution for this use case..appreciate your help..Thank you

A: I believe the BatchMessageListenerContainer is what you are looking for. It allows you to read messages in batches.
Note that this is not part of the standard library of readers/writers, but you can use it as is if you want or take inspiration and adapt it as needed.


text:
Q: How do growing event horizons affect observations of objects falling into black holes? There are many questions on this forum about objects falling into black holes. Most of them describe that to distant observers, the objects never quite reach the event horizons and appear to be frozen just outside. For example:
 How can anything ever fall into a black hole as seen from an outside observer?
Answers often refer to the Schwarzchild metric, even though that describes a static situation which isn't strictly applicable to in-falling objects. We know from studies of black-hole mergers (Revisiting Event Horizon Finders
 ) that in more realistic scenarios, event horizons can start growing before objects actually cross them.
This seems to suggest (perhaps naively) that outside observers could possibly see objects disappear behind event horizons in a finite time, since the event horizon may be larger than previously assumed.
That view might be countered by noting that the gravitational time dilation would also be changing along with the event horizon, with the result that the disappearance would still take an infinite time.
I don't expect that such a complicated situation could have a definitive answer without resorting to numerical relativity calculations, but would like to know what conclusions have been reached about the effects of event horizon growth.
It has been suggested in comments, that this question is a possible duplicate of Does an expanding event horizon "swallow" nearby objects? However, that question involves the merger of two black holes, and therefore has two event horizons, while this question is for the somewhat simpler case of aa object falling into a single black hole. I'm not sure if the answers would be different, but I believe this is still a separate question.

A: In relativity one needs to make a distinction between "an outside event happening at a time $t$ by the clock of an observer $\beta$" and "an observer $\beta$ sees an event happening at time $t$ by her clock". The first situation means that event happens within the slice of a constant time $t$ in the observer's frame of reference, while the second implies that there is a null geodesics connecting the event with the observer at time $t$.
With that in mind,

*

*By taking the backreaction into consideration (in this situation it means that the horizon would be growing) an object would cross the event horizon in finite time by the clock of an outside observer (with any reasonable scheme of defining slices of constant outside time in the vicinity of black hole, such as Fermi–Walker frames)

*Signals propagating with the speed of light from the event of "object crosses the event horizon" would by definition never reach an outside observer. Signals from events immediately preceding would reach the outside observer arbitrarily late and extremely redshifted, so in practice an observer would only see an object outside the event horizon for some time until the signals from it get redshifted beyond any possibility of detection.


text:
Q: UWP: Garbage collection Gen 2 still happens inside a NoGCRegion In my UWP app I need to perform a critical section for few seconds, when I need to be sure that the Garbage collector is not invoked.
So, I call
const long TOTAL_GC_ALLOWED = 1024L * 1024 * 240; // 240 MB, it seems max allowed is 244 for Workstations 64 bits
    try
    {
        bool res = GC.TryStartNoGCRegion(TOTAL_GC_ALLOWED);
        if (!res)
            s_log.ErrorFormat("Cannot allocate noGC Region!");
    }
    catch (Exception)
    {
        s_log.WarnFormat("Cannot start NoGCRegion");
    }

Unfortunately, even if the method GC.TryStartNoGCRegion() returns true, I still see the same amount of GarbageCollection of Gen 2 as in the case when I don't call this method.
Please also notice that I am trying on a machine with 16 GB of RAM, of which only 9GB are used by the whole O.S. when I was doing my tests.
What am I doing wrong?
How can I achieve to suppress the GC (for a limited amount of time)?


text:
Q: Magnetic flux from maximum induced emf as a function of angular velocity? I've done an experiment where I have a small rotating coil in a uniform magnetic field and I've measured the induced emf in the rotating coil as a function of time for several different angular velocities (constant in each case) of the rotating coil. The equation that describes the relation between the induced emf voltage and time is derived as follows (starting with magnetic flux where $N$ is the number of turns of the rotating coil, $B$ is the external, uniform magnetic field, and $A$ is the area of the rotating coil):
$$\Phi_B=NBA\cos{\theta}$$
$$\frac{d\Phi_B}{dt}=-NBA(\sin{\theta})\frac{d\theta}{dt}$$
And by Faraday's Law we have the induced emf as a function of time:
$$\varepsilon=\omega NBA(\sin{\omega t+\theta_0})$$
Now, if I graph the peak voltage (amplitude of $\varepsilon=\omega NBA$) for each of the different tested angular velocities for the rotating coil $\omega$, I get a linear relationship as expected. I'm wondering what the slope of this graph represents and its units? I would think $\omega NBA$ as a function of $\omega$ implies the slope is $NBA$, right? If so, its units should be Volt-seconds or Webers? But since this graph is peak voltage as a function of angular velocity in rad/sec shouldn't the units of the slope be $\frac{V\cdot s}{radian}$? How do I account for the radian part? I'm confused about what this slope means?


text:
Q: Where does it specify that you need 000-default.conf in apache2.4.x I deleted this file 000-default.conf and put my own in instead. In the default apache2.conf  line 219
IncludeOptional sites-enabled/*.conf

however when I restart apache
apache2: Syntax error on line 219 of /etc/apache2/apache2.conf: Could not open configuration file /etc/apache2/sites-enabled/000-default.conf: No such file or directory
Action 'restart' failed.
The Apache error log may have more information.

all I have is:
my-pc sites-available # ls -l
total 12
-rw-r--r-- 1 root root 6437 Jan  7  2014 default-ssl.conf
-rw-r--r-- 1 root root  271 Aug 29 22:12 mysite.conf

A: My guess would be that you deleted /etc/apache2/sites-available/000-default.conf but left the symlink at /etc/apache2/sites-enabled/000-default.conf, which is now a dead link.  Is that the case?

A: I think you have removed 000-default.conf files.But symlink is still available.

So you need to disable it.
sudo a2dissite 000-default.conf


text:
Q: Accessing alfresco document from Window application I set up Alfresco on Linux Server.I want to access the documents and content of Alfresco from my Window Application. How can i access it and can it be OK? And Also which way is the best approach?

A: Alfresco provides developer tools for interacting with an Alfresco repository. You can consult the developer documentation for more information on this.
For use in Java, Alfresco provides the Alfresco Java Foundation API that should be able to help you.

A: Alfresco provides several APIs to access your content. In your case you need a remote API that can access Alfresco from the Windows machine. The Alfresco Java Foundation API is a Java API that can only be used on the Alfresco Repository Machine (same Java VM).
You could either use the REST API or the CMIS standard (which I would suggest).
If you are developing the Client in Java you can use the OpenCMIS client library for example to access Alfresco. There are probably also CMIS clients libraries for other languages.
You should evaluate if CMIS has all the capabilities you need, because since it is a common standard it does not support the complete feature set of Alfresco.


text:
Q: Is systemd.link's handling of auto-negotiation broken? I'm trying to configure a PC Engines box to run an OpenEmbedded build with one or more network interfaces with auto-negotiation turned off, and I seem to be missing something in my .link file. At boot time, I get these messages:
Dec 26 23:20:07 rl-000db948364a systemd[1]: Started udev Kernel Device Manager.
Dec 26 23:20:07 rl-000db948364a systemd-udevd[231]: link_config: autonegotiation is unset or enabled, the speed and duplex are not writable.
Dec 26 23:20:07 rl-000db948364a systemd-udevd[244]: link_config: Cannot set device settings for eth2 : Invalid argument
Dec 26 23:20:07 rl-000db948364a systemd-udevd[244]: Could not set speed or duplex of eth2 to 100 Mbps (full): Invalid argument
Dec 26 23:20:07 rl-000db948364a systemd-udevd[232]: link_config: autonegotiation is unset or enabled, the speed and duplex are not writable.

My .link file for the network interface looks like this:
[Match]
MACAddress=00:0d:b9:48:36:4a

[Link]
AutoNegotiation=false
Duplex=full
BitsPerSecond=100M

I thought perhaps that AutoNegotiation needed some other value, like off or disabled, but those don't seem to change anything, nor does 0. Using something I expect to fail, like vrai, gives me an error message about the illegality of the word when I use udevadm test-builtin.... Running udevadm info... shows that my .link file was used, and I am able to set wake-on-lan to values supported by the interface.
If, after boot-up, I set the duplex and speed with ethtool, it works just fine.
I'm dealing with an Intel Corp. I211 device.
Does anyone have a suggestion as to what else I might try? Thanks!

A: After exhausting all other options, I looked into the systemd-udevd source code, and there is a bug in systemd through at least v236 which prevents it from setting duplex or speed from the contents of .link files. I've submitted a patch to the developers, but it hasn't been accepted yet for the v237 milestone.
This is an esoteric problem that won't affect most people, but if you're building your systemd from source and absolutely, positively want to fix it yourself, the changes are found in the Github pull request.


text:
Q: ListBox expand selected item I have the following code snippet (copy and paste into kaxaml, xamlpad, etc to try it)
that collapses all but the selected item. However, I want to revert back to all visible
when the mouse is not over the ListBox and I just cannot get it to work short of going code behind. I am using the IsMouseOver ListBox property to set selected item properties on the ListBox to attempt to trigger an update but no luck.
Any ideas?

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Grid>
      <ListBox
           Name="lb"
           Width="100"
           Height="100"
           Background="Red"
           SelectionMode="Single">
           <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                     <UniformGrid Columns="1"/>
                </ItemsPanelTemplate>
           </ListBox.ItemsPanel>
           <ListBoxItem Background="AliceBlue">Item 1
           </ListBoxItem>
           <ListBoxItem Background="Aquamarine">Item
           </ListBoxItem>
           <ListBoxItem Background="Azure">Item
           </ListBoxItem>
           <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                     <Setter Property="Visibility" Value="Visible"/>
                     <Style.Triggers>
                          <MultiDataTrigger>
                               <MultiDataTrigger.Conditions>
                                    <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="False"/>
                                    <Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}},Path=SelectedItems.Count}" Value="1"/>
                               </MultiDataTrigger.Conditions>
                               <MultiDataTrigger.EnterActions>
                                    <BeginStoryboard>
                                         <Storyboard Duration="0:0:1">
                                              <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
                                                   <DiscreteObjectKeyFrame KeyTime="0:0:1" Value="{x:Static Visibility.Collapsed}"/>
                                              </ObjectAnimationUsingKeyFrames>
                                              <DoubleAnimation Duration="0:0:1" Storyboard.TargetProperty="Opacity" To="0"/>
                                         </Storyboard>
                                    </BeginStoryboard>
                               </MultiDataTrigger.EnterActions>
                          </MultiDataTrigger>
                          <MultiDataTrigger>
                               <MultiDataTrigger.Conditions>
                                    <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="True"/>
                                    <Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}},Path=SelectedItems.Count}" Value="1"/>
                               </MultiDataTrigger.Conditions>
                               <MultiDataTrigger.EnterActions>
                                    <BeginStoryboard>
                                         <Storyboard Duration="0:0:0">
                                              <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
                                                   <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}"/>
                                              </ObjectAnimationUsingKeyFrames>
                                              <DoubleAnimation Duration="0:0:0" Storyboard.TargetProperty="Opacity" To="1"/>
                                         </Storyboard>
                                    </BeginStoryboard>
                               </MultiDataTrigger.EnterActions>
                          </MultiDataTrigger>
                     </Style.Triggers>
                </Style>
           </ListBox.ItemContainerStyle>
           <ListBox.Style>
                <Style>
                     <Style.Triggers>
                          <Trigger Property="ListBox.IsMouseOver" Value="False">
                               <Setter Property="ListBox.SelectedItem" Value="{x:Null}"/>
                               <Setter Property="ListBoxItem.IsSelected" Value="False"/>
                               <Setter Property="ListBox.SelectedIndex" Value="-1"/>
                          </Trigger>
                          <EventTrigger RoutedEvent="Mouse.MouseLeave">
                               <BeginStoryboard>
                                    <Storyboard>
                                         <Int32Animation Duration="0:0:0" Storyboard.TargetProperty="SelectedIndex" To="-1"/>
                                    </Storyboard>
                               </BeginStoryboard>
                          </EventTrigger>
                     </Style.Triggers>
                </Style>
           </ListBox.Style>
      </ListBox>
 </Grid>
</Page>

A: Move your style to resources and apply it when the mouse is over the ListBox.`
<Page.Resources>
    <Style x:Key="CustomStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="False"/>
                    <Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}},Path=SelectedItems.Count}" Value="1"/>
                </MultiDataTrigger.Conditions>
                <MultiDataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard Duration="0:0:1">
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
                                <DiscreteObjectKeyFrame KeyTime="0:0:1" Value="{x:Static Visibility.Collapsed}"/>
                            </ObjectAnimationUsingKeyFrames>
                            <DoubleAnimation Duration="0:0:1" Storyboard.TargetProperty="Opacity" To="0"/>
                        </Storyboard>
                    </BeginStoryboard>
                </MultiDataTrigger.EnterActions>
                <MultiDataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard Duration="0:0:0">
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}"/>
                            </ObjectAnimationUsingKeyFrames>
                            <DoubleAnimation Duration="0:0:0" Storyboard.TargetProperty="Opacity" To="1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </MultiDataTrigger.ExitActions>
            </MultiDataTrigger>
        </Style.Triggers>
    </Style>
</Page.Resources>

<Grid>
    <ListBox
       Name="lb"
       Width="100"
       Height="100"
       Background="Red"
       SelectionMode="Single">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="1"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBoxItem Background="AliceBlue">Item 1
        </ListBoxItem>
        <ListBoxItem Background="Aquamarine">Item
        </ListBoxItem>
        <ListBoxItem Background="Azure">Item
        </ListBoxItem>
        <ListBox.Style>
            <Style>
                <Style.Triggers>
                    <Trigger Property="ListBox.IsMouseOver" Value="True">
                        <Setter
                            Property="ListBox.ItemContainerStyle"
                            Value="{StaticResource CustomStyle}"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListBox.Style>
    </ListBox>
</Grid>

`
Also note the usage of the MultiDataTrigger.ExitActions, these are the actions to apply when the trigger object becomes inactive.


text:
Q: Parse Facebook comments graph API i have been looking for a way to properly parse the JSON object or associative array of similar facebook feeds in PHP:
https://graph.facebook.com/comments/?ids=http://lovebryan.com/friends/layne/data/upimages/ClevelandForest.jpg
$request_url ="https://graph.facebook.com/comments/?ids=" . $purl;
$requests = file_get_contents($request_url);
$fb_response = json_decode($requests);

How can I implement a foreach function in PHP to extract the id's of each data member?

A: $fb_response = json_decode($json, true);

foreach($fb_response as $key => $value)
{
     // your code....
}


text:
Q: Error generating PWA manifest dynamically I'm trying to generate dynamically the manifest of my PWA in NextJS, but some fields on the manifest are not working.
Here's an example. I have this code in the _app.tsx file:
useEffect( () => {
    const iconUrl = [
      {
          src: '/icon-192x192.png',
          sizes: '192x192',
          type: 'image/png'
      },
      {
          src: '/icon-256x256.png',
          sizes: '256x256',
          type: 'image/png'
      },
      {
          src: '/icon-384x384.png',
          sizes: '384x384',
          type: 'image/png'
      },
      {
          src: '/icon-512x512.png',
          sizes: '512x512',
          type: 'image/png'
      }
  ]
  const manifest = {
    theme_color: '#f69435',
    background_color: '#f69435',
    display: 'standalone',
    scope: `/${restaurantData.slug}`,
    start_url: `/${restaurantData.slug}`,
    name: restaurantData.name,
    short_name: restaurantData.name,
    icons: iconUrl,
  };
    const content = encodeURIComponent(JSON.stringify(manifest));
    const url = 'data:application/manifest+json,'+content;
    const element = document.createElement('link');
    element.setAttribute('rel', 'manifest');
    element.setAttribute('href', url);
    document.querySelector('head')?.appendChild(element);
  }, [])

When I go to Application on the developer tools, I got this error:
Error message from Application in Developer tools
I've tried many things, and I'm not able to solve this issue.
I'll appreciate the help.


text:
Q: NPM still looking for deleted dependency I deleted some module folders that I had previously npm installed into a module. I also manually removed their entries in my module's package.json. Then, npm would still look for those deleted folders so I re-created the folders and npm uninstalled them, which succeeded. Is there another way to "clear" npm's graph?

A: Try running npm cache clean --force and then see if the problem still persists. S If would help if you posted your package.json file so that we could see if any problems exist.


text:
Q: Porque no me aparece el botón de la clase JButton en el Frame? package bienvenidos;
import javax.swing.*;
import java.awt.*;

public class CapturaDatos {

    public static void main(String[] args) {
        PantallaCaptura pantalla1=new PantallaCaptura();
        pantalla1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class PantallaCaptura extends JFrame{

        public PantallaCaptura() {
            setTitle("Pantalla de Captura");
            setBounds(400,200,400,400);
            setVisible(true);
            add(new LaminaCaptura());
        }
}

 class LaminaCaptura extends JPanel{

    public LaminaCaptura(){
     boton1=new JButton("CapturarDato");
     }

     JButton boton1;
 }

A: Necesitas añadir el botón al panel
class LaminaCaptura extends JPanel{

    public LaminaCaptura(){
       this.setLayout(new FlowLayout());
       boton1=new JButton("CapturarDato");
       add(boton1);
    }

     JButton boton1;
 }

Si lo quieres de forma específica tendrás que añadir layouts.
https://docs.oracle.com/javase/tutorial/uiswing/components/panel.html

A: package bienvenidos;
import javax.swing.*;
import java.awt.*;

    public class CapturaDatos {

        public static void main(String[] args) {
            PantallaCaptura pantalla1=new PantallaCaptura();
            pantalla1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }

    class PantallaCaptura extends JFrame{
            public PantallaCaptura() {
            setTitle("Pantalla de Captura");
                setBounds(400,200,400,400);
                setVisible(true);
                add(new LaminaCaptura());
            }
    }

     class LaminaCaptura extends JPanel{

        public LaminaCaptura(){
         boton1=new JButton("CapturarDato");
         add(boton1);
         }

         JButton boton1;
     }


text:
Q: Browser Cache: If we change something force user to get new version, not local cached version We make changes often on our website (which uses caching) and sometimes user don't know to refresh a page in order to get the newest copy of it.
If we do update a page, how can we force the users browser to know that there is a new server version, and to use that rather than their browsers cached page?

A: Either you can set an http header to force reload every n'th second. That's the easy way, but you probably don't want this. The second way is to use a javascript asking the server via ajax if there is an update. If so, force a reload.
About the cache, you can set an expire header on the page.

A: I know the question has been answered, but another way is to set the querystrings at the end of your URL to use a version number:
www.asite.com?version=1.0 //force update
www.asite.com?version=1.1
www.asite.com?version=1.2

The browser should request a new cache each time the version number is changed.


text:
Q: 301 redirect www version to non for only a subdirectory Trying to 301 redirect all urls to non-www only in a specific subdirectory. for example:
https://www.example.com/test

to
https://example.com/test

But not redirect any other subdirectories for example:
https://www.example.com/test1 should keep the www
more examples:
https://www.example.com/test/country/city

to
https://example.com/test/country/city

A: You can use this to redirect your www urls to non-www for a specific directory :
RewriteEngine on

#the directory the rule should apply to
RewriteCond %{REQUEST_URI} ^/DirName/  [NC]
#check if the host  string starts with "www"
RewriteCond %{HTTP_HOST} ^www\. [NC]
#redirect all www urls to non-www
RewriteRule (.*) http://example.com%{REQUEST_URI}  [L,R=301]