text:
Q: spring security and using CustumUserDetails Can anybody help me with spring security?
I have two folder under views 1: allusers 2: superusers
all users have hasRole("ROLE_USER") and superusers have: haseRole("ROLE_ADMIN","ROLE_USER")
I want when a user how has the ROLE_ADMIN after log in be redirect to the right folder i.e supersusers's folder and that one with only ROLE_USER to the allusers's folder.
Don't know how can I do it.
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org  /2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

<http auto-config="true" use-expressions="true">

    <!-- interceptor pages -->
    <intercept-url pattern="/**" access="permitAll" />
    <intercept-url pattern="/index" access="permitAll" />
    <intercept-url pattern="/allusers/**" access="hasRole('ROLE_USER')" />
    <intercept-url pattern="/superusers/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
    <intercept-url pattern="/logout" access="permitAll" />
    <intercept-url pattern="/denied" access="permitAll" />
    <intercept-url pattern="/getAllUsers"  access="hasRole('ROLE_ADMIN')" />
    <access-denied-handler error-page="/403" />

    <form-login login-page="/index" default-target-url="/welcome"
        authentication-failure-url="/loginfailed" />

    <logout logout-success-url="/logout" />

</http>
<authentication-manager>
    <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="
                            select username,password,'true' AS isEnabled from USER where USERNAME=?"
            authorities-by-username-query="
            select u.username ,r.`ROLE_NAME`,u.`PASSWORD` from USER u, USER_ROLE ur,ROLE r where (u.user_id = ur.user_id)
            and (r.role_id=ur.role_id)  and u.username =? " />
    </authentication-provider>
</authentication-manager>

Here is my mvc-dispatcher.xml
    <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.secure.weblayer" />
<mvc:annotation-driven />
<context:annotation-config />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
     <!--   <property name="prefix" value="/WEB-INF/views/allusers/" />-->
     <!--   <property name="prefix" value="/WEB-INF/views/superusers" />-->
    <property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames" value="mymessages"></property>
</bean>
<bean
   class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
   </beans>

As you can see I use sql-query in my spring-security.xml for log in.
I can log in but can not be redirect to any desired pages. But when I in the xml file changethe property to : property name="prefix" value="/WEB-INF/views/allusers"
or  : property name="prefix" value="/WEB-INF/views/superusers"
I can get access to all pages in those folders but not at the same time.

Please any help?

A: You dont wanna touch the InternalResourceViewResolver, as that affects all views.
You dont have your access rights correct, should be like this.
all users is normal users and admin users:
<intercept-url pattern="/allusers/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />

superusers is just admin users
<intercept-url pattern="/superusers/**" access="hasRole('ROLE_ADMIN')" />

Also, remove:
<intercept-url pattern="/**" access="permitAll" />

And then you just want to redirect to right page after login.
So use this for your login controller:
@Controller
public class LoginController {
    @RequestMapping(value="/welcome", method = RequestMethod.GET)
    public String printWelcome(ModelMap model, SecurityContextHolderAwareRequestWrapper request) {
        if(request.isUserInRole("ROLE_ADMIN")) {
            return "redirect:/superusers";
        } else {
            return "redirect:/allusers";
        }
    }
}


text:
Q: Data binding in fetched v-html content I'm fetching a string template (not a Vue template, simple string that has html attributes) from our server which looks like Hi {{ name }} (...) and putting it into:
data: {
  return: {
    template: '', // after template is fetched it goes here
    name: 'John'
  }
}

but instead of Hi John I get Hi {{ name }}. Not sure how to solve it - any easy solutions to that?

A: If the template strings are not Vue templates then you could parse the {{ ... }} placeholders yourself using a RegExp.

new Vue({
  el: '#app',

  data () {
    return {
      firstName: 'John',
      lastName: 'Smith',
      title: 'Mr',
      template: 'Hi {{ title }} {{ firstName }} {{ lastName }}'
    }
  },

  computed: {
    templateOutput () {
      return this.template.replace(/{{\s*([\S]+?)\s*}}/g, (full, property) => {
        return escape(this[property])
      })

      function escape (str) {
        if (str == null) {
          return ''
        }

        return String(str)
          .replace(/&/g, '&')
          .replace(/>/g, '>')
          .replace(/</g, '<')
          .replace(/"/g, '"')
          .replace(/'/g, ''')
      }
    }
  }
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: laravel 4 one to many relationships - iteration I'm trying to improve some code in my app in laravel 4 and trying to implement relationships between models.
I have a table called reservations which has a one to many relationship with items. Items has a one to one relationship with Products. Basically as a reservation the items that are included in the reservation are added to the items table. The specs of the items comes from the products table (type, value etc)
I've set up the relationships in the models as follows:
in the reservations Class:
public function item() {
        return $this->hasMany('Item');
    }

in the items Class:
public function reservation() {
        return $this->belongsTo('Reservation');
    }
public function product() {
        return $this->hasOne('Product');
    }

in the product Class:
public function item() {
        return $this->belongsTo('item');
    }

I'm trying to now query the reservations for a calendar view. I'm retrieving all the reservations in a month using the following:
$events = Reservation::where('play_date','>=',$start->format('Y-m-d'))
            ->where('play_date','<=', $end->format('Y-m-d'))
            ->get();

I'm then trying to iterate through the collection (is it a collection or a result set?) using the following:
$events->each(function($event) { }

I then want to iterate through all the items of the reservation and it's this bit that's confusing me.
$items = $event->item()->get();

which does create an object I can then iterate through this sub collection using another call back but I'm then struggling to get the product information using:
$item->product()->type

I get an error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$type

How can I iterate through the items correctly using laravel relationships? What is the best practice in this and retrieve details relating to the item from the product table
Thank you

A: The main point to do what you want is understand the difference between $event->item and $event->item(). Basically, $event->item is the same as $event->item()->get(). Knowing this, you should be doing something like this
$events = Reservation::where('play_date', '>=', $start->format('Y-m-d'))
                     ->where('play_date', '<=', $end->format('Y-m-d'))
                     ->get();

$events->each(function ($event) {
    $items = $event->item;
    $items->each(function ($item) {
        $type = $item->product->type;
    });
});

You may also want to take a look at Eager Loading your relationships, as to reduce the number of queries ran.


text:
Q: Create expandable  with jquery within expandable  I have found this code to create an expandable/collapsible a while ago while trying to build an expandable Div-Container and it has worked wonders for me so far (unexperienced hobby designer here).
Now I would like to insert an expandable div within one of those. The problem I am facing is that I cannot figure out how to change the function in order so it automatically readjusts the outer height of the first expandable div. I have an example of what it should look like here (If I expand Collapsible 1-3 it should also expand Collapsible 1 so all content is visible):
Collapsible 1

*

*Collapsible 1-1

*Collapsible 1-2

*Collapsible 1-3

The code I use can be found here:
HTML:
<button id="button">Toggle Expand/Collapse</button>

Item

Item

Item

Item

CSS:
#wrapper {
background: #ccc;
overflow: hidden;
transition: height 200ms;
}

JS:
$(function() {
var b = $("#button");
var w = $("#wrapper");
var l = $("#list");

w.height(l.outerHeight(true));

b.click(function() {

 if(w.hasClass('open')) {
   w.removeClass('open');
   w.height(0);
 } else {
  w.addClass('open');
  w.height(l.outerHeight(true));
 }

 });
 });

A: You can use .slideDown and .slideUp instead of calculating height.

$(document).ready(function() {
  $('#button').click(function() {
    $('#wrapper').toggleClass('open').slideToggle(200);
  });
});
#wrapper {
  background: #ccc;
  overflow: hidden;
  /*transition: height 200ms;*/
}

<button id="button">Toggle Expand/Collapse</button>

Item

Item

Item

Item


text:
Q: Reading in data inside a function Here is a function that i am trying to execute, My data directory and base directory have the correct file paths.
loadDIH = function(){
##----
##++++
## Target variable: Days in hospital Year 2
dih.Y2    <- read.csv(file = paste(dataDir, "DaysInHospital_Y2.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")
## Days in hospital Year 3
dih.Y3    <- read.csv(file = paste(dataDir, "DaysInHospital_Y3.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")

   return(list(dih.Y2,dih.Y3))
}

>return(list(dih.Y2,dih.Y3))
Error: object 'dih.Y2' not found

My data directory and base directory have the correct file paths because when i execute the code with out using the function it reads the data eg.
dih.Y2    <- read.csv(file = paste(dataDir, "DaysInHospital_Y2.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")

dih.Y3    <- read.csv(file = paste(dataDir, "DaysInHospital_Y3.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")

>dih.Y2

This returns dih.Y2
Any thought or ideas on how to execute this as a function?
I appreciate any help?

A: Objects created inside a function are visible only within that function. You'll want to use an explicit return statement, like
return(list(dih.Y2,dih.Y3))

Moreover, you'd probably benefit from spending some time reading the R manual section on scope.
There is also the global assignment operator <<-, but it's use is often frowned upon. You should probably stick with the way R wants to be used, and have functions return the values you want explicitly.
In your example, it would look like this:
loadDIH = function(){
##----
##++++
## Target variable: Days in hospital Year 2
dih.Y2    <- read.csv(file = paste(dataDir, "DaysInHospital_Y2.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")
## Days in hospital Year 3
dih.Y3    <- read.csv(file = paste(dataDir, "DaysInHospital_Y3.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")

   return(list(dih.Y2,dih.Y3))
}

Then the command,
foo <- loadDIH(...)

will result in foo being a list containing dih.Y2 and dih.Y3.
This kind of stuff is covered extensively in some of the manuals for beginners.


text:
Q: Session and Cookie save all inputs I have 5 divs like this. That means there can be many inputs are in view. Problem is How to save inputs selections. when refresh page, press back button. I searched about session but my inputs can be many or less not static. that's the problem

        Нэгдүгээр хэсэг

    <?php //dd($questions) ?>
@if(count($questions) > 0)

    <?php $i = 1; ?>
    @foreach ($collections[0] as $question)
        @if ($i > 1)
 @endif

          Асуулт {{ $i++ }}.

{!! nl2br($question->question_text) !!}

          <input type="hidden" name="questions[{{ $question->id }}]"
           value="{{ $question->id }}">
           @foreach($question->options as $option)

               <input type="radio" name="answers[{{ $question->id }}]"
                  value="{{ $option->id }}">{{ $option->option }}
           @endforeach

    @endforeach

@endif

<input type="button" value="Дараагын хуудас" onclick="show_next('account_details','user_details','bar1');">

A: SessionStorage/LocalStorage is client side component, so you can't use it from PHP code. You can save user data in server side storage like APC, cookies or SESSION. I think this is only way to do that.

A: Yes, you can save your inputs in a a session storage, and retrieve whenever you need. This is pretty much just another variable, but it gets stored in the session, so it will hold between page changes.
Just create a variable and save it in session storage, example:
var name= somecode;
sessionStorage.setItem("name", name);

Now when you need whatever you saved in that variable, just use:
sessionStorage.getItem("name");


text:
Q: Insl and outsl gives "Matching constraint does not allow a register" error So here's the code in XV6 source code (x86.h):
static inline void
outsl(int port, void* addr, int cnt)
{
  asm volatile("cld; rep outsl" :
  "=S" (addr), "=c" (cnt) :
  "d" (port), "0" (addr), "1" (cnt) :
  "cc");
}

static inline void
insl(int port, void* addr, int cnt)
{
  asm volatile("cld; rep insl" :
  "=D" (addr), "=c" (cnt) :
  "d" (port), "0" (addr), "1" (cnt) :
  "memory", "cc");
}

It gives this error:
kernel/x86.h:7:3: error: matching constraint does not allow a register [-Werror]
    7 |   "cc");
      |   ^~~~
kernel/x86.h:4:3: error: matching constraint does not allow a register [-Werror]
    4 |   asm volatile("cld; rep outsl" :
      |   ^~~
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
   53 | }
      | ^
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
kernel/sound.c: In function 'read_pci_config':
kernel/sound.c:17:3: error: matching constraint does not allow a register [-Werror]
   17 |   outsl(0xcf8, &tmp, 1);
      |   ^~~~~~~~~~~~~~~~~~~~~
kernel/sound.c:17:3: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:17:3: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
   53 | }
      | ^
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:53:1: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:13:6: error: matching constraint does not allow a register [-Werror]
   13 | uint read_pci_config(uchar bus, uchar slot, uchar func, uchar offset)
      |      ^~~~~~~~~~~~~~~
kernel/sound.c:13:6: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:13:6: error: matching constraint does not allow a register [-Werror]
kernel/sound.c:13:6: error: matching constraint does not allow a register [-Werror]
In file included from kernel/sound.c:10:
kernel/x86.h:4:3: error: matching constraint does not allow a register [-Werror]
    4 |   asm volatile("cld; rep outsl" :
      |   ^~~
kernel/x86.h:4:3: error: output number 0 not directly addressable
kernel/x86.h:4:3: error: matching constraint does not allow a register [-Werror]
kernel/x86.h:4:3: error: asm operand 3 probably doesn't match constraints [-Werror]
cc1: all warnings being treated as errors
make: *** [<builtin>: kernel/sound.o] Error 1

Does anyone had any idea what's the cause of such error?
FYI I'm using the code from older XV6 versions in the latest XV6 version (2021.9). I tried using the original io.h which also has the 2 functions, but it gives the same error.


text:
Q: How do you share state between protocols in Twisted? I have two protocols, one a WebSocket server the other a ZeroMQ pull socket. I want to forward things received my ZMQ to the WebSocket. Is this possible?
class WebSocketProtocol(WebSocketServerProtocol):

    def onMessage(self, msg, binary):
        print "Received: ", msg, binary
        self.sendMessage(msg, binary)

class MyProto(ZmqPullConnection):

    def onPull(self, message):
        print "Recevied: ", message
        # How to I call sendMessage(message) from here?

if __name__ == '__main__':
    zf = ZmqFactory()
    e = ZmqEndpoint("bind", "tcp://127.0.0.1:5500")
    s = MyProto(zf, e)

    factory_ws = WebSocketServerFactory("ws://127.0.0.1:9500/echo", debug = False)
    factory_ws.protocol = WebSocketProtocol
    listenWS(factory_ws)
    reactor.run()

A: Have a look at this example. New WebSocketServerProtocol instances register themselfes on the WebSocketServerFactory. The latter then has a broadcast method to dispatch an event on all currently connected clients.
Given that, all you need is put a reference to the WebSocketServerFactory onto your MyProto instance (s.factory_ws = factory_ws) and then call the broadcast method from your 0MQ proto.


text:
Q: Link Mosquitto with gcc on OSX I am new to Mosquitto and I am tying to write a simple C client connecting to Mosquitto's test server: http://test.mosquitto.org/
Here is the code of the simple C client which is 99.9% of an example found on Mosquitto's site: http://pastie.org/private/orwicqjfjz8g8biurznca
EDIT 1:
I followed the comments and wrote a makefile instead of doing
gcc -o test test.c

The makefile looks like this:
CC = gcc
CFLAGS = -I
DEPS = mosquitto.h

LIBS = -llibmosquitto

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

make: test.c
    $(CC) -m32 -Wall -o $@ $^ $(CFLAGS) $(LIBS)

.PHONY: clean

This is the output i get which seems to be some problem linking mosquitto libs with gcc:
Undefined symbols for architecture i386:
  "_mosquitto_connect", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_connect_callback_set", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_destroy", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_lib_cleanup", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_lib_init", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_log_callback_set", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_loop", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_message_callback_set", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_new", referenced from:
  _main in cc6Blyda.o
  "_mosquitto_subscribe", referenced from:
  _my_connect_callback in cc6Blyda.o
  "_mosquitto_subscribe_callback_set", referenced from:
  _main in cc6Blyda.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
make: *** [make] Error 1

NOTE: I used homebrew to install the mosquitto so the path to the lib is
/usr/local/Cellar/mosquitto/1.1/

Appreciate any help!!
Regards

A: I solved the linking problem by some trial error in my makefile.
This is how the final makefile looks like which does not give any linking problems:
CC = gcc

LIBS = -lmosquitto

%.o: %.c
    $(CC) -c -o $@ $<

make: test.c
    $(CC) -Wall -o test $^ $(LIBS)

.PHONY: clean

Thanks


text:
Q: Click a button 10 times and reload the page I'm trying to make my code click a button and reload the page in Javascript. The button must be clicked 10 times every .5 seconds. When it's been clicked 10 times, I want the code to reload the page. Here's what I've got:
var rolls = 10

var q = 0
setInterval(
  function() {
    document.getElementById("roll").click();
    q += 1
  }, 500);

if (q == rolls) {
  location.reload(true)
}

A: The following solution uses setInterval to click on the button and decreases rolls. If rolls reaches 0, then the page is reloaded. Your mistake was that your code which checked for the value of rolls ran just after the setInterval, earlier than it actually became 0.
var rolls = 10;

setInterval(
  function() {
    if (!(rolls--)) {
        window.location.href = window.location.href;
    }
    document.getElementById("roll").click();
  }, 500);

A: Try to insert the checking into the setInterval method:
var rolls = 10

var q = 0
setInterval(
  function() {
  document.getElementById("roll").click();
  q += 1
    if (q == rolls) {
        location.reload(true);
    }
}, 500);

A: you're doing the check just at the time you define the interval, so
if (q == rolls) {
  location.reload(true)
}

is being called just once at the start.
put it inside the interval function like this:
setInterval(
  function() {
    document.getElementById("roll").click();
    if (++q >= rolls) location.reload(true)
  }, 500);


text:
Q: New to VSCode, Python - some env questions I went through a few articles about how to setup VSCode to work with python for the first time, and I'm very confused.
To me, VSCode seems messy - so many json settings which I manually need to configure...
Anyway, I now have 3 ways of running my python script:

*

*F5, which runs via the terminal

*Run (Ctrl+Shift+D), via Watson

*Run via Code Runner

I don't understand the differences between the different methods of running my script.
Can someone please give me a short intro?
Thanks!

A: Terminal:
Terminal is fast and efficient to use. It also provides detailed information about the errors in your programs. And it is widely used buy a lot of Python programmers.
Watson:
It provides developer tools for more advanced users. You can get more information about that from here. Not recommended for a beginner.
Code Runner:
Code runner is also used to see the the results of the programs but it is read only, and there can be some problems with that. As an example if you are building an application that takes the input from the user in Python, you can't do that via code runner.
So which one is the best?
I would recommend using the Terminal (F5), because it is good for small programs, you get detailed information about your apps, the problems with your apps and some other options too. It is also fast and easy to use for a beginner.

Hope it's clear now.


text:
Q: Python retrieve QComboBox from QTablewidget I am now a month into Python and half a month into QDesigner/Qt.
Within QDesigner, I have a QTableWidget, which I promote to my own InputTable(QTableWidget) class.
class InputTable(QTableWidget):
    def __init__(self, parent=None):
        self.parent = parent
        super(QTableWidget, self).__init__(parent)
...

I inserted some QComboboxes, which allow the user to select the units of the values in the table. This is at the initialization within the InputTable class.
pressureunits = [ "barg","bara", "psig", "psia"]
        pressurecombobox = QComboBox()
        for i in range(len(pressureunits)):
            pressurecombobox.addItem(pressureunits[i])
            self.setCellWidget(2, 0, pressurecombobox)

So far, so good.
Now I want to convert all the inputdata to a parallel table (master table) with values in SI units for further analysis.
units = self.tableInputs.cellWidget(2,0)
if units.currentIndex()==0:   # this means the combobox is at the first entry
    mastertable[0,2] = float(self.tableInputs.item(2,1).text())

This fails, because units is of type QWidget, which has no attribute currentIndex. On some forums I read that the QComboBox is a child of the QWidget and I have played with the children() functions, but helas no solution here. Some people recommend switching to QTableView structure. I spend my day searching how to do this, nothing found yet. Any smart ideas?
Update: After reducing all complexity from my question, I was able to find the solution below.
from PyQt5.QtWidgets import QComboBox, QTableWidget, QTableWidgetItem

Mytable = QTableWidget(3,3)
Mytable.setItem(0, 0, QTableWidgetItem("1"))
print("Now retrieve the data :", Mytable.item(0, 0).text())

pressureunits = [ "barg","bara", "psig", "psia"]
pressurecombobox = QComboBox()
for i in range(len(pressureunits)):
    pressurecombobox.addItem(pressureunits[i])
    Mytable.setCellWidget(2, 0, pressurecombobox)
print("Now retrieve the active (first) entry :", Mytable.cellWidget(2,0).currentText())


text:
Q: Send mail using my own SMTP Server I have windows server 2019 configured in AWS . Installed SMTP server role.
Now , i have a simple mail client which i downloaded from below github link.
https://github.com/CodeCowboyOrg/SimpleSMTPClient.
Image shows that mail sent sucessfully
The sender and receiver mail ID is my personal gmail account. I am not receiving this mail in my gmail inbox.
Any suggestion why i am not receiving mail ?
I think my understanding about smtp work flow is not good.
Please help me to understand.

A: This is a complex subject not conducive to a single StackExchange post. Please do further research before asking a specific question. There is much more to do to have your mail accepted by commercial servers, especially Gmail and even then they are notoriously opaque about their criteria for spam.


text:
Q: Jenkins: ChromeDriver update PATH from shell script and use new version I am looking for a way to update the PATH in Jenkins for running Selenium tests with PyTest.
I need to run the latest version of chromedriver but due to an infrastructure deficiency (our base image is running Debian and the latest available version is 73 and I need to be running at least 83).
There is already a version of chromedriver installed on the image at /usr/bin and I need to be able to point to a different version
The jenkins chromedriver plugin appears that it will just use the latest available version for debian, which doesn't help me at all.
Until I have time to address the systemic issue, I'd like to just install chromedriver and update PATH - because Selenium requires chromedriver on the PATH
It seemed, for ease of use, that https://pypi.org/project/chromedriver-binary/ was a good solution - it installs just fine and the shell script chromedriver-path echoes the location, so I could just update path as the documentation shows: PATH=$PATH:chromedriver-path
This doesn't seem to jive in Jenkins - PATH is not updated
stages {
    stage('build'){
        steps {
            withCredentials([...]) {

                    sh """
                        alias python=python3.8
                        python -m venv --system-site-packages venv # only for jenkins
                        python -u setup.py
                        . venv/bin/activate

                        which chromedriver #/usr/bin/chromedriver
                        chromedriver-path #path/to/python/lib/python3.8/site-packages/chromedriver_binary
                        export PATH=$PATH:`chromedriver-path`

                        which chromedriver #/usr/bin/chromedriver

                    """

                    sh "python -m pytest"
                }

            }
        }
    }

I Have looked at the withEnv() option and environment{} step but I'm not sure how to access that binary and update PATH once chromedriver-binary has been set - because it appears that environment{} would not have access to shell scripts that are installed in the individual steps.
Any tips would be greatly appreciated

A: The issue may actually be in Jenkinsfile declaration.
Try using sh with single quotes '''. Also binaries are searched in directories defined in PATH from left to right, so to override system PATH, you must put your directory on the beginning, not on the end.
If I alter your code snippet:
stages {
    stage('build'){
        steps {
            withCredentials([...]) {

                    sh '''
                        alias python=python3.8
                        python -m venv --system-site-packages venv # only for jenkins
                        python -u setup.py
                        . venv/bin/activate

                        which chromedriver #/usr/bin/chromedriver
                        chromedriver-path #path/to/python/lib/python3.8/site-packages/chromedriver_binary
                        export PATH=$(chromedriver-path):$PATH

                        echo $PATH # just to check the output, your path should be on the beginning
                        which chromedriver # this should now find the proper chromedriver

                    '''

                    sh "python -m pytest"
                }

            }
        }
    }


text:
Q: JS Datepicker - Advance the departure date to after the arrival date I have seen various answers to my issue. However, I am struggling to work with datepicker to figure out which way to trigger my event.
I have two fields. CheckInDate and CheckOutDate. I would like the CheckOutDate to change to after the CheckInDate once the user selects it.
Here is the form code:

        Check in

            <input type="text" class="form-control input datepicker" name="checkInDate" placeholder="Check in">

        Check out

            <input type="text" class="form-control input datepicker" name="checkOutDate" placeholder="Check out">

Does anyone have a piece of Javascript that would trigger the event?


text:
Q: C language Changing For Loop to While loop How to make for loop to while loop
Is it possible to change for loop in array to while loop?

change

for(i = 0; i < 12; ++i) //for loop for selecting only positive
    {
        if(a[i] > 0) printf("%d ", a[i]); //display positive only using if statement
    }

to

int i = 0, a[12];
    while(i < 12)
    {
        if(a[i] > 0)
        {
            printf("%d ", a[i]);
        }
        i++;
    }

but it doesn't display the positive same as the negative if changed..

A: int i;
for(i=0; i < count; i++)
{
    // Work item here
}

is functionally equivalent to
int i=0;
while (i < count)
{
    // Work item here
    i++;
}


text:
Q: Vertically align span:after relative to text I made a menu with links that have "list bullets", reacting to hover, like this.
Each item is wrapped by a span, and use :after to create the bullets.
The bullets are vertically aligned to the bottom of the text, and I want them to be centered.
However, trying to center it by using vertical-align: middle; (and any other means I could manage to find) results in this this (inspecting it shows the text is properly centered on the container) and I can't seem to find any way to get it properly centered.
Here is the fiddle.

A: Can you try if this code does what you need:
%linkBase {
  $fontSize: 40px;
  line-height:40px;
  font-size: $fontSize;
  position:relative;
  &::after {
    $bulletHeight: $fontSize * 0.8;

    content: '';

    display: inline-block;

    width: 2px;
    height: 40px;

    background-color: black;
    top:50%;
    position:absolute;
    margin-top:-20px;
  }
}

.link {
  @extend %linkBase;
}

.linkCentered {
  @extend %linkBase;
}

The idea is that you set the original link to be relative, then set the "after"element to be absolutely positioned. Then you set the "top" of that element to 50%, which pushes it half way down, then you pull it back up with a margin-top of half its height.
This is a common method of centering items.


text:
Q: WebClient.DownloadString result is not match with Browser result The following code:
        WebClient WC = new WebClient();
        WC.Encoding = Encoding.UTF8;
        string Url = "http://www.tsetmc.com/tsev2/data/instinfodata.aspx?i=59266699437480384&c=64";
        return WC.DownloadString(Url);

code returns:
�Q�T�MP�J�A|�^D����~���C�"�����l� ��;I&3=j=�iG�H9Ȓ�J�^� �j��T�Q=HH�'Qm�������1�hF�4�*�������{�x�\o?

when I visit that URL in any web browser, I get:
12:29:45,A ,3540,3567,3600,3621,3690,3515,140,238204,849582597,1,20140914,122945;;1@2825@3523@3583@1700@1,1@2000@3522@3600@8700@2,1@500@3511@3640@2500@1,;19774,99736,1

is there any way to get right string?
also, i use this online Decoder, but i dont get right anwser:
Universal Online Decoder

A: This should work:
    WebClient WC = new WebClient();
   // WC.Encoding = Encoding.UTF8;
    string Url = "http://www.tsetmc.com/tsev2/data/instinfodata.aspx?i=59266699437480384&c=64";
    return Encoding.UTF8.GetString(WC.DownloadString(Url));

A: use Uri  Object as argument in DownloadString method:
var url =String.Format("http://www.tsetmc.com/tsev/data/instinfodata.aspx?i=59266699437480384&c=64");
var WC = new WebClient { Encoding = Encoding.UTF8 };
return WC.DownloadString(new Uri(url));


text:
Q: php/mysql database redesign and migration: changing databases to tables I wrongly designed my application to have one database to each user. each user had 3 similar tables. I now want to have one database and 3 tables only; where i will use the database name in the old databases as a reference in the new system. There was another database called "users" in the old database that stored the database names. I'm done with the schema design of the new database and now left with the migration.

The trick here is that I have 3 db connections. I first connect to the users database and userinfo table, pick up the database_name in a loop, use it to connect each old db and further connect to personal, accounts and games table.
After picking up the tables, i will like to populate/join it with the new Database (DATA_ONE) and the tables whiles i append the old database_name to the new tables. Any help on this or is there a better way to do this? Thanks much
<?php

$dbhost = "localhost";
$dbname = "users";
$dbuser = "root";
$dbpass = "*****";

    $conn1 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE) or die("MySQL Error: " .  mysql_error());
    $conn2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE) or die("MySQL Error: " . mysql_error());
    $conn3 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE) or die("MySQL Error: " . mysql_error());

    mysql_select_db($dbname,$conn1) or die("MySQL Error: " . mysql_error());

$query  = "SELECT database_name FROM userinfo";
$result1 = mysql_query($query,$conn1);
 while($row = mysql_fetch_array($result1, MYSQL_ASSOC))
    {
 $database_name =$row['database_name'];
 $conn2 = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
 $db = mysql_select_db($database_name ,$conn2) ;
 // now, pick personal, accounts, games tables of user and populate new database and  tables.
// this is where i need help.
  }

 ?>

A: Why do you think you need 3 seperate database connections with the same credentials? In any mysql query you can reference tables from any database on the same instance by prefixing the table name with the database name (and a . in between). I'd suggest not using 'database_name' as an attribute name:
$databases=get_mysql('SELECT DISTINCT database FROM users.userinfo ORDER BY database');
$count_of_users=count($databases);
foreach ($databases as $user_offset=>$user) {
   $uqry="INSERT INTO data_one.personal
     (user, id, address, password)
     SELECT '$user'
     , (id*$count_of_users*$user_offset)
     , address
     , password
     FROM ${user}.personal";
    ...

(assuming that 'id' is an autoincrement value which may be referenced elsewhere).


text:
Q: How can i add context menu for each item on listView1 and treeView1 when doing mouse right click on item? The items in the listView1 are files so i want that the menu for each file when i will do on the file right click with the mouse will show different options(properties) then if i'm doing right clikc with the mouse on treeView1 item since the items on the treeView1 are directories.
How can i make that on right click on specific item when the mouse cursor is over an item it will show a menu with options for this item ?
The listView! MouseUp event:
private void listView1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            if (listView1.FocusedItem.Bounds.Contains(e.Location) == true)
            {
                contextMenuStrip1.Show(Cursor.Position);
            }
        }
    }

The treeView1 MouseUp event:
    private void treeView1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            // Select the clicked node
            treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);

            if (treeView1.SelectedNode != null)
            {
                myContextMenuStrip.Show(treeView1, e.Location);
            }
        }
    }

And a method i did but not sure if need to use it:
    private MenuItem AddMenuItem(ContextMenu cm, string text, EventHandler handler, object context)
    {
        MenuItem item = new MenuItem(text, handler);
        item.Tag = context;
        cm.MenuItems.Add(item);
        return item;
    }

A: You can differentiate between the file and directory node by giving them specific name  using TreeNode.Name property. In the COntextMenuStrip.Opening event, you can then enable or disable the menu items based on the node name.
TreeNode tn = treeView1.GetNodeAt( e.X, e.Y );

if( tn != null )
{
  if( tn.Name == "FileName") {

  }
}


text:
Q: Does ExecuteQuery have a cache/timeout/etc? I wasn't sure how to phrase the title, forgive me. I'm running into an issue with the CSOM (SharePoint 2010, but likely in 2013 as well), where my initial ExecuteQuery() statement takes upwards of 20 seconds, and successive requests take less than a second. If a minute or two lapses between requests, the first ExecuteQuery() request after the lapse will take another 20+ seconds. See below for my sample code and data results.
void Main()
{
    var listId = new Guid("60558323-bd04-45b7-946f-b70709e6a001");
    var listItemId = 15629;
    for (int i = 0; i < 25; i++)
    {
        Debug.WriteLine("Waiting " + i*10 + "s...");
        Thread.Sleep(i*10*1000);
        var sw = new Stopwatch();
        sw.Start();
        var listItemUrl = GetServerRelativeListItemUrl(listId, listItemId);
        sw.Stop();
        Debug.WriteLine("Request took " + sw.ElapsedMilliseconds.ToString() + " ms.");
    }
}

public string GetServerRelativeListItemUrl(Guid listId, int listItemId)
{
  using (var clientContext = this.GetClientContext())
  {
      var web = clientContext.Web;
      clientContext.Load(web);

      var list = web.Lists.GetById(listId);
      clientContext.Load(list);

      var listItem = list.GetItemById(listItemId);
      clientContext.Load(listItem);
      clientContext.Load(listItem.File);
      clientContext.ExecuteQuery();

      var listItemUrl = listItem.File.ServerRelativeUrl;
      return listItemUrl;
  }
}

protected ClientContext GetClientContext()
{
    var clientContext = new ClientContext("http://{url redacted}");
    clientContext.Credentials = CredentialCache.DefaultCredentials;
    return clientContext;
}

And my output:

    Waiting 0s...
    Request took 693 ms.
    Waiting 10s...
    Request took 37 ms.
    Waiting 20s...
    Request took 390 ms.
    Waiting 30s...
    Request took 39 ms.
    Waiting 40s...
    Request took 35 ms.
    Waiting 50s...
    Request took 357 ms.
    Waiting 60s...
    Request took 39 ms.
    Waiting 70s...
    Request took 350 ms.
    Waiting 80s...
    Request took 343 ms.
    Waiting 90s...
    Request took 340 ms.
    Waiting 100s...
    Request took 347 ms.
    Waiting 110s...
    Request took 688 ms.
    Waiting 120s...
    Request took 690 ms.
    Waiting 130s...
    Request took 689 ms.
    Waiting 140s...
    Request took 24592 ms.
    Waiting 150s...
    Request took 21804 ms.
    Waiting 160s...
    Request took 21765 ms.
    Waiting 170s...
    Request took 21784 ms.
    Waiting 180s...
    Request took 21766 ms.
    Waiting 190s...
    Request took 23854 ms.
    Waiting 200s...
    Request took 21772 ms.
    Waiting 210s...
    Request took 21763 ms.
    Waiting 220s...
    Request took 21979 ms.
    Waiting 230s...
    Request took 24496 ms.

Note that the first request doesn't take the full 20+ seconds because I had run an ExecuteQuery immediately prior to that. Had it been first run, it would've taken the full time.
Is there some kind of internal cache or timeout in the SharePoint Client Object Model that would be causing this delay when there are no requests for 140ish+ seconds? I can't find any documentation pointing to this, but I can definitely see it in action.

A: I know in the JavaScript Client Object Model executeQueryAsync is performed using an XmlHttpRequest, the results of which are cached by default. I would assume the managed client object model requests data using the same method 'under the covers'
As for how long the cached request is valid, it appears to be dependent upon the user's browser configuration.
If you inspect an executeQuery response (in Fiddler, for example) you'll see that no 'cache lifetime' information is specified in the response. If you look at the cache tab in Fiddler, it will tell you this:

This response does not specify explicit HTTP Cache Lifetime information and does not specify a Last-Modified date. Heuristic expiration is typically based on Last-Modified date. Lacking Last-Modified, this response may be revalidated on every use or once per browsing session, depending on the browser configuration.

Which complies with the W3 HTTP 1.1 caching specification.
You'll also notice that the executeQuery responses will not contain a last modified time or etag -- which are other common methods of telling a browser when it should request new information.
Each browser behaves differently in regard to what they decide to cache -- most allow the user to provide some configuration on what happens when no server values are present: For example, IE allows you to specify 'Every time I visit the web page', 'Every time I start Internet Explorer', 'Automatic', or 'Never' for when it caches http responses and modifies its behavior according to the user's specification. 'Automatic' causes IE to use an algorithm to determine how often it should refresh content (based on how often it thinks that the content changes). This example information applies specifically to IE9, but as far as I know works similarly across all versions later than 6.0.
So in summary, I'd like to tell you 'the default cache timeout is xx seconds' but the answer really is that it depends...

A: Don't know if it helps, but ClientContext object has a timeout property
clientContext.RequestTimeout = Timeout.Infinite;

However, you'll be tight to the timeout in the Webserver (IIS). No idea about Cache, but John-o reply seems very good to me.


text:
Q: Cannot find 'user_signed_in' [ Devise ] Rails version: 4.2.6, Ruby: 2.3.1
I use:
before_filter :authenticate_user!, except: [:index, :show]in my controller. I want to hide two buttons in my view:
    <% if user_signed_in? %>

          <%= link_to 'Edit', edit_project_path(@project) %>
          <%= link_to 'Delete', project_path(@project), method: :delete, data: { confirm: 'Are you sure?' } %>

      <% end %>

But I receive an error: "Cannot find 'user_signed_in" It seems like helper methods don't work. I tried to use any other Devise methods, but the results are the same...
My routes.rb:
    Rails.application.routes.draw do
      devise_for :users
      resources :projects
      resources :contacts, only: [:new, :create]
      get 'welcome/index'
      root 'welcome#index'

      get '*path' => redirect('/')
    end

user.rb
    class User < ActiveRecord::Base
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable
    end

How can I fix it?
Thanks.

A: Seems like an odd error. The code appears to be correct as far as I can tell. I would ensure that you have installed Devise properly by running rails generate devise:install, run any pending migrations and then restart your rails server. The Devise Wiki indicates there can be strange errors like this if implemented and not restarted afterwards, so I would try that if you haven't.

A: You can use
<% if current_user.present? -%>

      <%= link_to 'Edit', edit_project_path(@project) %>
      <%= link_to 'Delete', project_path(@project), method: :delete, data: { confirm: 'Are you sure?' } %>

<% end-%>

OR include this in application controller
include Devise::Controllers::Helpers


text:
Q: import a dbf file in oracle I have snapshots of two oracle database tablespaces in amazon ec2.
Currently we are able to start a database against one of the tablespaces. Is there any way to import the second tablespace into the oracle with a separate user.
We tried creating a new tablespace pointing at the same dbf file and associate it to a new user but the user does not have any access to any objects. The dbf contents are not loaded into the database.
Any help ?
Thanks.

A: You might be able to get there using transportable tablespace.  That said, is there a reason you cannot simply create a new tablespace and then copy the data to the new tablespace?  You could do that either via data pump or SQL.
I am assuming you are more interested in duplicating the data held in that tablespace versus the tablespace itself.


text:
Q: How to properly use findBySomeOtherId not findById in Spring data jpa? I am working on a Spring boot project with spring data jpa(MYSQL)
When I hit this end point http://localhost:8080/admin/interviews/101
I get this error
{
    "timestamp": "2019-10-11T13:45:37.111+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]",

    "trace": "org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [101] did not match expected type [com.yash.arci.model.Interviews (n/a)]\r\n\tat org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible

This is interviewStatus class
@Entity
@Table(name ="interview_status" )
public class InterviewStatus implements Serializable {

private static final long serialVersionUID = -6353284727527331855L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name ="interviewId",insertable = false, updatable = false)
private Interviews interviewId;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name ="statusId",insertable = false, updatable = false)
private Status statusId;
..........
}

@Repository
public interface InterviewStatusRepository extends
JpaRepository<InterviewStatus, Integer> {

InterviewStatus findByInterviewId(Integer interviewId);
}

I want the record on the basis of interviewId. I can already get on the basis of primary key but I want it on the basis of Interview Id, I have interviewId column in interviewStatus table.

A: Please use this InterviewStatus findByInterviewId(Interviews interviewId); where interviewId is gotten by running Interviews findById(Long id).
Due to the datatype conflict, it is ok that you pass in as parameter the expected datatype. so it is expecting Interviews not Integer, but you have integer. in this case, you get Interviews using the integer then pass the gotten Interviews as parameter.


text:
Q: ethers Get logs at specific blocks I'm trying to get logs on ethers however,  right now I'm chunking out the blocks based on the max blocks my provider allows (3500).  However this is inefficient and slow,
(Note: yes I know the graph probably would be better)
let fromBlock = parseInt(filter.fromBlock as any) ?? 0
let toBlock = parseInt((filter.toBlock ?? blockNumber) as any)
let blockSpan = toBlock - fromBlock;
const numberOfChunks = Math.ceil(blockSpan / MAX_BLOCKS_PER_LOG);

var logPromises = Array.apply(0, Array(numberOfChunks)).map((_,i) => {
  const fb = fromBlock + (i * MAX_BLOCKS_PER_LOG)
  //Logs filter is inclusive so we need to subtract 1
  const tb = Math.min(toBlock, fb + MAX_BLOCKS_PER_LOG - 1)
  return provider.getLogs({
    ...filter,
    fromBlock: fb,
    toBlock: tb,
  })
});
//...

I would like to lets say I would like to getLogs as block [315536, 355536, 392301], I know I can make requests to get logs for each individual block, however I would like to make a single query, so I don't have to make that many additional requests to the rpc provider.
Is this possible?


text:
Q: is there any way of making this program more efficient? I want the program to be more efficient, i was thinking to use a 'for loop' but i dont know how to implement it in my code and also the writing to file part is really long i want to make it shorter
    import random

    def character_attributes():
        initial_value = 10
        character1_strength = initial_value + (random.randint(1,12) // random.randint(1,4))
        character1_skill = initial_value + (random.randint(1,12) // random.randint(1,4))
        character2_strength = initial_value + (random.randint(1,12) // random.randint(1,4))
        character2_skill = initial_value + (random.randint(1,12) // random.randint(1,4))

        print("Character 1 now has a strength attribute of {0}".format(character1_strength))
        print("Character 1 now has a skill attribute of {0}".format(character1_skill))
        print("Character 2 now has a strength attribute of {0}".format(character2_strength))
        print("Character 2 now has a skill attribute of {0}".format (character2_skill))

        myfile = open('character_attribute_data.txt', 'w')
        myfile.writelines('Character 1 has a strength attribute of : ')
        myfile.writelines(str(character1_strength))
        myfile.writelines('\n')
        myfile.writelines('Character 1 has a skill attribute of: ')
        myfile.writelines(str(character1_skill))
        myfile.writelines('\n')
        myfile.writelines('Character 2 has a strength attribute of : ')
        myfile.writelines(str(character2_strength))
        myfile.writelines('\n')
        myfile.writelines('Character 2 has a strength attribute of : ')
        myfile.writelines(str(character2_skill))
        myfile.close()

A: I don't think that you can get much more efficient in the sense of higher speed. You are using python functions for all the string manipulations and you will hardly get any better in python.
But your code is not that efficient concerning development speed. Imagine you want to change 'Character' by 'Person' then you have to change 8 lines of code. The answer of unutbu for example gives you a hint for a much better solution and even this could be improved e.g by introducing a class for characters as pointed out by moooeeeep. Even if you now think this is pure cosmetics, it will on the long run helps you to improve performance as you will be able to make changes (e.g. an optimisation you found) in contrast to the current code which is not maintainable.
Another point  is, I can hardly belief that you really get into performance problems with this code. It does nothing than writing some few lines into a single file. Be very careful to not optimize things you don't need to (premature optimization). Only if you get into performance problems, then analyze the bottlenecks and try to improve the worst.
EDIT:
Sorry, i meant moooeeeep comment on the question:
This is a prototype extending the example from unutbu with a class holding the attributes information:
import random

class Character(object):
    '''
    This class holds all the information concerning a character, it's attributes,
    the character number, ...
    '''
    def __init__(self, character_number, initial_value):
        '''
        Initialize a new character object with character_number and initial_value
        '''
        self.strength = initial_value + (random.randint(1,12) // random.randint(1,4))
        self.skill = initial_value + (random.randint(1,12) // random.randint(1,4))
        self.character_number = character_number

    def get_attributes_dict(self):
        '''
        return a dictionary with the attributes names and their values for this character
        '''
        return {'strength': self.strength,
                'skill': self.skill
                }

def writeout_character_attributes(characters_list):
    '''
    this function writes a complete list of character into a file
    '''
    #The 'with' statement is used here, because it automatically closes the
    #file at the end of this block, so you cannot forget it
    with open('character_attribute_data.txt', 'w') as myfile:
        #iterate over the character in the list
        for character in characters_list:
            #get all the attributes for the current character
            attributes = character.get_attributes_dict()
            #iterate over the attributes names and values,
            #defined in the character class
            for attribute_name, val in attributes.items():
                msg = "Character {i} now has a {attribute_name} attribute of {val}".format(
                    i= character.character_number, attribute_name=attribute_name, val=val)
                print(msg)
                myfile.write(msg+'\n')

def get_list_of_characters(initial_value):
    list_of_characters = []
    # we want two characters with numbers 1 and 2
    for i in range(1, 3):
        #create a new character
        character = Character(i, initial_value)
        #add this character to the list of characters
        list_of_characters.append(character)
    return list_of_characters

if __name__ == '__main__':
    list_of_characters =  get_list_of_characters(10)
    writeout_character_attributes(list_of_characters)

It's maybe not less lines of code, but it is much easier for example to add more attributes or add komplex logic to the Character class

A: This doesn't make the code more efficient, but it does make it shorter:
import random

def random_val(initial_value):
    return  initial_value + (random.randint(1,12) // random.randint(1,4))

def character_attributes():
    initial_value = 10
    with open('character_attribute_data.txt', 'w') as myfile:
        for i in range(1, 3):
            attributes = {
                'strength': random_val(initial_value)
                'skill': random_val(initial_value)}
            for key, val in attributes.items():
                msg = "Character {i} now has a {key} attribute of {val}".format(
                    i=i, key=key, val=val)
                print(msg)
                myfile.write(msg+'\n')


text:
Q: Variable length Lookbehinds RegEx don't works in Python I want extract the text between ':' and '|' characters, but in second and third data there are a space after the ':'
The intput:
Referencia:22726| Referencia Cliente Ak: 233726 | Referencia histórica: 256726 | Suelo | AGOLADA (Pontevedra) -  CARPAZO O PE#A LONJA [EXTRACT]
Referencia:39766| Referencia Cliente Ak: 39767 | Referencia histórica: 39768 | Garaje | MOJACAR (Almería) -  URB.VILLA MIRADOR DEL MAR - MOD. # [EXTRACT]
Referencia:397A5| Referencia Cliente Ak: 397B5 | Referencia histórica: 397C5 | Garaje | MOJACAR (Almería) -  VILLA MIRADOR DEL MAR-MODULO #-PLAZA 4 [EXTRACT]
Referencia:AA39803| Referencia Cliente Ak: P_39803 | Referencia histórica: 200_39803 | Garaje | MOJACAR (Almería) -  VILLA MIRADOR DEL MAR - MODULO [EXTRACT]

Output desired:
22776
233726
256726
39766
39767
39768
397A5
397B5
397C5
AA39803
P_39803
200_39803

My first pattern: (?<=:)(\w{5,12})
This matches only the first column.
My second pattern: (?<=:\s)(\w{5,12})
This matches the second and third columns
So I believed that my third pattern was the correct one: (?<=:\s?)(\w{5,12})  That pattern don't works.

A: a lookbehind can't be variable length in python. A way to solve this:
(?:(?<=:\s)|(?<=:))(\w{5,12})

But since you use a capturing group, a lookbehind is useless:
:\s?(\w{5,12})

A: Remove the ? character in the Lookbehind move the \s to the matches
(?<=:)(\s?\w{5,12})


text:
Q: Display user inputs in textarea and format as array in database PHP I've created a custom options page for my WordPress theme and have a textarea for users to add options that will be appended to an array in another file. User input is successfully added to the appropriate location in the database, but it is being stored as a single string. I would like for the user to be able to enter one option on each line and have the inputs saved as an array with each line being saved as an element in the array.
for example:
Textarea user input:
'my option1'
'my option2'
'my option3'

is stored as:
a:1:{s:24:"my_textarea_field_0";s:34:"my option1
my option2
my option3";}

I would like for it to be stored as an array: {"my option1", "my option2", "my option3"}
Also, the text entered into the textarea is saved to the database but is not displayed in the textarea after the submit button is pressed. I would like for the user's input the be added to the database as an array and continue to be displayed in the textarea after it has been submitted.
Here is the relevant code:
function my_textarea_field_0_render() {
        $this->$options = get_option('my_settings');
        ?>

            Lorem ipsum dolor sit amet.

        <textarea cols='145' rows='8' name='my_settings[my_textarea_field_0]'><?php echo $options['my_textarea_field_0'];?></textarea>

        <?php
        add_option('my_settings', '$options');
}

I've spent a while searching for solutions and tinkering with the code, but I haven't been able to figure it out.

A: *

*To make array from value of textarea, use explode function. Maybe this sample code is useful for you.

$arrTextarea = explode("\n", str_replace("\r", "", $valTextarea));

*You should use only php code in function.

function my_textarea_field_0_render() {
    $this->$options = get_option('my_settings');
    $html = `

            Lorem ipsum dolor sit amet.

            <textarea cols='145' rows='8' name='my_settings[my_textarea_field_0]'>` .
                $options['my_textarea_field_0'] .
            `</textarea>

`;
    add_option('my_settings', '$options'); // I didn't understand what is $options.
}


text:
Q: Tangent to two circles with parametric coordinates (2+2cos θ , 2 sin θ)? I was wondering if someone could help solve this question,
Show that the point with coordinate$ ( 2 + 2cos (θ) , 2 sin (θ))$ lie on the circle
$x^2 + y^2 = 4x$ and obtain the equation of the tangent to the circle at this point.
The tangent at the points A and B on this circle touch the circle $x^2+y^2=1$ at the points C and D. Find the coordinate of the points of intersection of these tangents, and obtain the equation of the circle through the points A B C D.
the answers are:
$x cos θ + y sin θ = 2 + 2 cos θ $
(-2,0)
$x^2+y^2=2x+2$
I can get the equation for the tangent quite easily but can't get the rest, I run into some really messy algebra, by inserting x,in the equation of the tangent, into the formula for the circle, to find the points of intersection. The algebra is horrid and leads to no viable answer.
Thanks for any help.

A: $ x^2+y^2=4x $ and $ (x-2)^2+y^2=2^2 $ represent the same circle! ( being tangent to y-axis at the origin).

A: You can avoid the messy algebra via another method. The parametric equation for the smaller circle is x=cosθ, y=sinθ and you can use this as the coordinates on the smaller circle. If you sketch the graph for both circles and draw the tangent line that touches both circles at A on the bigger circle and C on the smaller circle you will notice the parameter or angle θ subtended for point A on the bigger circle and point C on the smaller circle are the same because the line from center of the circle to the point A and C respectively are perpendicular to the tangent line.
enter image description here
The gradient of the tangent line is given by the derivative of the given point, m = -cosθ/sinθ, which is the same if you work out the gradient between points A and C, which is 2sinθ-sinθ/2+2cosθ-cosθ=-cosθ/sinθ. Solving this equation to get the values of θ you can proceed to get the equation of the other tangent and obtain the intersection point...


text:
Q: How to mazimize custom claims storage in Firebase? I'm currently using custom claims to store project-based permissions in my firebase app.
However, I have quickly hit the 1000b limit due to lots of projects. The nature of the app means a user will be creating hundreds, if not thousands of projects.
Does anyone have any idea how to get around this size limit without resorting to storing permissions in rtdb (this would mean permissions aren't accessible throughout the Google ecosystem e.g storage).
I found this answer which implied I can somehow store single byte keys. Whilst my values are already a single character, my keys are UUIDs. How would I go about achieving condensing these keys? - somehow map a single byte to a UUID? I'm currently using claims on the client, cloud functions, and in db rules.
An alternative I was contemplating was to use custom JWT tokens as, as far as I can tell, these might not have the same size limit for claims.
Any help would be appreciated!

A: The custom claims are sent from the client to the server with every request. I'd seriously reconsider trying to add more than the default limit of ~1K to each request, and in fact would typically look for another approach well before that.
Instead of storing individual project IDs, consider if there is a way to turn those into a more limited set of roles. This may be a lossy operation, where you lose some nuances of the existing model. For those differences, you can consider accepting them, or them encoding the exceptions into the token again as (a much smaller set of) custom claims.
If neither of these is feasible, the idiomatic approach is to store the ACL into a secondary system (such as Realtime Database you mention) and look it up there. You can't do such a lookup from within the Storage security rules though (as you mention), so you will have to wrap (read) access to Storage in a custom API. In the case of write operations, you can consider allowing them to a more broad set of users, and having a Cloud Function (or periodic process) perform a cleanup of uploads by rogue users.


text:
Q: Is there a point completing all of the available memories before assassinating your target? Is there any point in collecting all memories before going to kill main victim? Completing 2 memories is sufficient. I completed everything in the poor district in Damascus and Acre, and I just started with Jerusalem and the missions are always identical. Only the informant challenges are different.
I really like this game, but if everything will be same till end of the game it's kind of disapointing.

A: As far as I can recall, there isn't any advantage to completing all pre-assassination requirements, other than a sense of completion... The multiple option for approaching an assassination was present so that users can opt to complete their preferred types.
Your disappointment was shared by many critics on the game's release and the repetitiveness was a strong critical point at the time. You should know that the later games improved on the issue by providing better variety in missions.
Edit: There is one advantage to complete all available pre-assassination missions - you can get more heath blocks earlier, but once you reach the maximum amount of health blocks, there's not point doing more than the required amount of missions.


text:
Q: What is a design matrix? How do I build a design matrix for Rasch analysis? I am trying to do an LRSM Rasch analysis of 72-item data. This data has 67 binary items and 5 ternary items. I need to create a "design matrix" in order to analyze this data. I do not really know what a design matrix is, nor do I know how to create one for my data. Could someone please give me some clues on getting started?

A: Design matrix groups all your variables together, typically for regressions. If a variable is categorical, it'll be coded.
You can use model.matrix in R to construct one. However, you shouldn't need to do it yourself because whatever analysis you'll be using should automatically do it for you.


text:
Q: The response body is a byte stream. See the service documentation for allowed content types When I used REST to call my WCF service it skips the method being called with the following error:

The response body is a byte stream.
  See the service documentation for
  allowed content types.

I am dealing with placing objects in memory and then trying to serialize them as a JSON string. To do this, I have an interface to my service contract:
 [ServiceContract]
    public interface IDashboardService
    {

        [WebGet(UriTemplate = "dashboard/group/id/{id}", ResponseFormat=WebMessageFormat.Json)]
        [OperationContract]
        Stream GetGroupById(string id);

    }

And in my service contract overrides the method that is being skipped:
public class Dashboard : GroupBase, Contracts.IDashboardService
{
        public Dashboard() : base()
        {

            if (!ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated)
                throw new WebException("Unauthorized: Class: Dashboard, Method: Dashboard()",
                    System.Net.HttpStatusCode.Forbidden);

        }

        public override System.IO.Stream GetGroupById(string id)
        {
            return base.GetGroupById(id);
        }

}

Here is the base method:
 public virtual Stream GetGroupById(string id)
        {
            byte[] bytes = null;

            var groupId = System.Convert.ToInt32(id);
            var serializer = new JavaScriptSerializer();

            switch (groupId)
            {
                case 0: // regions
                    var regions = GroupRepository.GetAllRegions();
                        bytes = Encoding.UTF8.GetBytes(serializer.Serialize(regions));
                    break;
                case 1: // customers
                    var customers = CustomerRepository.GetAllCustomers();
                        bytes = Encoding.UTF8.GetBytes(serializer.Serialize(customers));
                    break;
            }

            return new MemoryStream(bytes);

        }

Any idea how I can get this working? Thanks.

A: You can't return a stream and then tell WCF to format it as JSON.  Just remove the MessageFormat attribute and set the Content Type header manually to application/Json

A: I had to put this line in before returning the memory stream to get it to format as JSON:
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";


text:
Q: Using TouchImageView in RecyclerView attached with PageSnapHelper? My app is doing a gallery which uses TouchImageView on RecyclerView.
I was trying to use this class to display multiple fullscreen images in a RecyclerView attached with PageSnapHelper
This works fine, but the zooming is very awkward to use .If I try to pinch zoom , the image moving left and right but not zooming. Only double Tap works.
I think there is a conflict with the swiping and scrolling of the RecyclerView attached with PageSnapHelper .
How can I make the TouchImageView touch events override the PageSnapHelper events when pinch zoomed byt swiping also works when swiped?
To be simple , I want the same behavior of Chat Apps(Whatsapp and telegram) Image Slider which supports both swiping and pinch zooming
Note , I searched the stackoverflow but there are only solutions for ViewPagers but no recyclerview

A: Im not exactly sure what you are asking here, but if I got it right, the problem is you can't pinch zoom because the RecyclerView is recognising your pinch action as a swipe.
If you wanted, you could always disallow the RecyclerView from intercepting the touch event (and handle the event yourself) by calling:
view.parent.requestDisallowInterceptTouchEvent(true)

inside the onTouch method of the PrivateOnTouchListener.
If you want a simpler solution, you could also check if the current view is zoomed or if at least 2 fingers are touching the view. If yes, disallow the parent to intercept the touch event. The inside the PrivateOnTouchListener code would then look like this:
     if (isZoomed || event.pointerCount >= 2) {
        v.parent.requestDisallowInterceptTouchEvent(true)
     }

The parent will now only be allowed to intercept the touch event if the view isn't zoomed and if only one finger is touching the view.


text:
Q: How to install ExactImage on Fedora 37 I'd like to use ExactImage on Fedora 37. As far as I can see, it is neither in the main repository nor in rpmfusion, nor can I find any third-party package.
I tried compiling from source but it appears to be an extremely difficult case. For one thing, the latest release does not compile as-is, but at least this was fixable with Ubuntu/Debian patches.
However, I'm still having trouble building/installing AGG. I somehow managed to with CMake, but something must be wrong since I'm getting a linking error with ExactImage.
Has anyone else tried this and can provide steps, or at least a hint how to properly build AGG? Also I'm confused which AGG sources I should use?

A: In this case, I suggest you to use alien to convert deb to rpm package.
sudo dnf install alien
sudo alien --to-rpm exactimage_1.0.2-8+b3_amd64.deb

Now you have an rpm package. Next step is to resolve the dependencies, which might be time-consuming, I know.
sudo rpm -i exactimage_1.0.2-8+b3_amd64.rpm

In my case the following deps were required:
lilmbase25-common
libIex-2_5.so.25()(64bit)
libIlmImf-2_5.so.25()(64bit)
libagg.so.2()(64bit)
These are the apps that rpm installed:
/usr/bin/bardecode
/usr/bin/e2mtiff
/usr/bin/econvert
/usr/bin/edentify
/usr/bin/empty-page
/usr/bin/hocr2pdf
/usr/bin/optimize2bw

A: I managed to build from source after all, although it might not be the proper way. Here are some key steps:

*

*Download the following packages from Ubuntu:

*

*AGG: orig patches

*ExactImage: orig patches

*Extract the archives in two isolated folders (agg, exactimage)

*Apply patches for both projects. Assuming you are in the respective source trees: cat ../debian/patches/series | while read PATCHFILE; do echo "../debian/patches/$PATCHFILE"; git apply "../debian/patches/$PATCHFILE"; done

*Install the dependencies of AGG and ExactImage from Fedora repository (including the corresponding -devel packages of course)

*Build/install AGG using automake (do not use CMake, it doesn't yield correct results!)

*

*bash autogen.sh

*Manually fix the generated configure script, there's a syntax error. (Or perhaps better, fix the configure.ac source file, lines 104-107, before running autogen.sh)

*./configure --disable-gpc --disable-examples --enable-freetype --enable-ctrl --enable-platform --with-pic, make -j4, sudo make install (reason for --disable flags: GPC was removed by Debian for licensing reasons, examples don't compile)

*Build/install ExactImage

*

*Manually fix image/Makefile (rename -laggfontfreetype_pic to -laggfontfreetype)

*PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ./configure --without-jasper --without-evas, make -j4, sudo make install (warning: no uninstall command provided!) (reason for --without flags: ExactImage's Jasper code is outdated/incompatible with Fedora's Jasper package; not sure what was wrong with evas)

*ExactImage doesn't look in /usr/local/lib for some reason, hence create symbolic links for AGG to /usr/lib64: for LIBFILE in /usr/local/lib/libagg*; do sudo ln -s "$LIBFILE" /usr/lib64/$(basename "$LIBFILE"); done (warning: likely not an elegant solution)

Frankly, I'm a bit annoyed I couldn't find sources working out of the box. This was probably the most chaotic and time-taking build process I ever had, especially as it needed many tries to get right. But at least I can use ExactImage now.
Next thing I'll do is file a packaging request for ExactImage at Fedora or RPMFusion.


text:
Q: How to search through both zipped and unzipped folders for a specific line I'm trying to implement a Python script that takes a folder from the user (can be zipped or unzipped), and search through all the files in the folder to output the specific lines that my regular expression matches. My code below works for regular unzipped folders, but I can't figure out how to do the same with zipped folders that are inputted to function. Below are my code, thanks in advance!
def myFunction(folder_name):

path = folder_name

for (path, subdirs, files) in os.walk(path):
    files = [f for f in os.listdir(path) if f.endswith('.txt') or f.endswith('.log') or f.endswith('-release') or f.endswith('.out') or f.endswith('messages') or f.endswith('.zip')] # Specify here the format of files you hope to search from (ex: ".txt" or ".log")
    files.sort() # file is sorted list

    files = [os.path.join(path, name) for name in files] # Joins the path and the name, so the files can be opened and scanned by the open() function

    # The following for loop searches all files with the selected format
    for filename in files:

            #print('start parsing... ' + str(datetime.datetime.now()))
            matched_line = []
            try:
                 with open(filename, 'r', encoding = 'utf-8') as f:
                        f = f.readlines()
            except:
                 with open(filename, 'r') as f:
                        f = f.readlines()

            # print('Finished parsing... ' + str(datetime.datetime.now()))

             for line in f:
                #0strip out \x00 from read content, in case it's encoded differently
                line = line.replace('\x00', '')

                RE2 = r'^Version: \d.+\d.+\d.\w\d.+'
                RE3 = r'^.+version.(\d+.\d+.\d+.\d+)'
                pattern2 = re.compile('('+RE2+'|'+RE3+')', re.IGNORECASE)
                for match2 in pattern2.finditer(line):
                    matched_line.append(line)
                    print(line)

#Calling the function to use it

myFunction(r"SampleZippedFolder.zip")

The try and except block of my code was my attempt to open the zipped folder and read it. I'm still not very clear with how to open the zipped folder or how it works. Please let me know how I can modify my code to make it work, much appreciated!

A: One possibility is first determine what object type folder_name is using zipfile and os.isdir() and whichever one succeeds, get the list of files and proceed. Maybe something like this:
import zipfile, os, re

def myFunction(folder_name):

    files = None # nothing yet

    path = folder_name

    if zipfile.is_zipfile(path):
        print('ZipFile: {}'.format(path))
        f = zipfile.ZipFile(path)
        files = f.namelist()
        # for name in f.namelist(): # debugging
            # print('file: {}'.format(name))

    elif os.path.isdir(path):
        print('Folder: {}'.format(path))
        files = os.listdir(path)
        # for name in os.listdir(path): # debugging
        #     print('file: {}'.format(name))

    # should now have a list of files
    # proceed processing the files
    for filename in files:
        ...


text:
Q: Проблемы с переадресацией с http на https Переадресация работает только с корня сайта.
httpd.conf
<VirtualHost *:80>
    DocumentRoot /var/www/html/example.com
    ServerName example.com
    Redirect ^/?(.*) https://example.com

</VirtualHost>

<VirtualHost *:443>
    DocumentRoot /var/www/html/example.com
    ServerName example.com

    SSLEngine on

    # SSLRequireSSL
    # SSLVerifyClient require

    SSLCACertificateFile /usr/local/ssl/crt/comodo.crt

    #ServerAlias www.example.com
    <Directory "/var/www/html/example.com">
        allow from all
        Options None
        Require all granted
    </Directory>

    ErrorLog /var/www/html/example.com/error.log

    php_admin_flag register_globals 1
    php_admin_value max_execution_time 60
    php_admin_value upload_max_filesize 10M
    Include /etc/letsencrypt/options-ssl-apache.conf
    ServerAlias www.example.com
    SSLCertificateFile /etc/letsencrypt/live/example.com-0001/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com-0001/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com-0001/chain.pem
</VirtualHost>

.htaccess
ErrorDocument 403 /403
# Disable magic quotes
php_flag magic_quotes_gpc 0
php_flag magic_quotes_runtime 0

# Turn on URL rewriting
RewriteEngine On

Options -Indexes
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# Installation directory
RewriteBase /

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php?q=$0

AddDefaultCharset UTF-8
<Files config.php>
deny from all
</Files>
<Files M*.php>
deny from all
</Files>
<Files C*.php>
deny from all
</Files>
<Files v*.php>
deny from all
</Files>
AddType application/octet-stream .txt
AddType application/octet-stream .exe
AddType application/octet-stream .npk
AddType application/octet-stream .rsc
AddType application/octet-stream .xls
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}


text:
Q: gpg --gen-key hangs at gaining enough entropy on centos 6 Trying to generate a key for a server.
gpg --gen-key

We need to generate a lot of random bytes. It is a good idea to perform
  some other action (type on the keyboard, move the mouse, utilize the
  disks) during the prime generation; this gives the random number
  generator a better chance to gain enough entropy.

and it just hangs there.
There is another error:

can't connect to `/root/.gnupg/S.gpg-agent': No such file or directory

which seems to go away after:

gpg-agent --daemon
  GPG_AGENT_INFO=/tmp/gpg-4c5hyT/S.gpg-agent:1397:1; export GPG_AGENT_INFO;

#GPG_AGENT_INFO=/tmp/gpg-4c5hyT/S.gpg-agent:1397:1; export GPG_AGENT_INFO;
gpg --gen-key
...

but again, it hangs at "...gain enough entropy".
There are no "++++++++++++++++++++++++++++++++++++++++++"'s which from forum posts looks like should be expected as the key is generated.
I have tried reinstalling the package, but seemingly everything depends on gpg.
I've read other people having problems with this on centos 6 too (whereas centos 5 works fine).
There is nothing remarkable in /var/log/*.
Any ideas on where to go from here?
Thanks.

A: Twist on other responses but at least one liner and not root.
((find / | xargs file) &> /dev/null &); gpg2 --gen-key --batch --passphrase-file output-key.txt key-gen-options.txt

Key-gen-options contains
Key-Type: 1
Key-Length: 2048
Subkey-Type: 1
Subkey-Length: 2048
Name-Real: myuser
Name-Email: myuser@email.com
Expire-Date: 0

Output-key.txt contains my super secret key.

A: When the gpg --gen-key command hangs like this, log in to another shell and perform the following command:
dd if=/dev/sda of=/dev/zero

(This command basically reads from your hard drive and discards the output, because writing to /dev/zero will do nothing.)
After a few seconds / minutes, the key generation command should complete.

A: EXTRAOPTIONS="-r /dev/urandom" worked for me instead of EXTRAOPTIONS="-r /dev/random"

A: I've tried all the solutions, and found that haveged works the best even when others don't work (especially on a headless server that doesn't have much user input or activity).
yum install haveged
apt install haveged
It starts the haveged daemon service that will keep /dev/random full of entropy. --key-gen should complete in less than a minute.
You can verify by running cat /dev/random. Normally, it will quickly run out of entropy and pause. That's why the --key-gen hangs. But after installing haveged, cat /dev/random should provide output continuously.

A: For a more reliable solution you could install random number generator related utilities, which will make sure that you always have enough random bytes.
yum install rng-tools

and then edit /etc/sysconfig/rngd and add EXTRAOPTIONS="-r /dev/random"
Start the service
 service rngd start

Voila and you live happily ever after :)

A: How I did it:

*

*pacman -S community/rng-tools

*vim /etc/conf.d/rngd to add RNGD_OPTS="-r /dev/urandom"

*systemctl enable --now rngd

*gpg-agent --daemon

*gpg --full-gen-key

Worked even when $GNUPGHOME is set to point to a custom directory.

A: https://gist.github.com/franciscocpg/1575d286548034113884c3185ca88681
Open a ssh session

sudo apt-get install rng-tools

In another SSH window open

gpg --gen--key

Go back to your first SSH session and run

sudo rngd -r /dev/urandom

Let this run till gpg generates your keys!
Then you can kill rngd

sudo kill -9 $(pidof rngd)

A: Both comments given before are perfectly fine. But here is just my 2 cents.
The problem with RHEL/centos 6 and entropy is that they are tickless kernels. So, by themselves, these kernels don't generate enough entropy. You have to get some keyboard attached or even some mouse movement or use dd as mentioned.
rngd daemon is awesome and most commercial entities use it.
However, the best approach I have seen is use of dedicated TPM device. They are small hardware which are quite expensive. You put them and rngd utilizes random true entropy from the hardware source. As far as I know, Fujitsu has some good TPM device.
Yeah, these three methods pretty much cover the entropy part.

A: Switching to gpg2 worked for me.
None of the other solutions did, because of permissions issues.


text:
Q: pass parameter to another component - null Follow the excerpt that I send and the other that I receive the parameter. but it's coming null
Usuario usuario = Usuario();
        usuario.email = email;
        usuario.senha = senha;

        //cadastrar ou logar
        if( _cadastrar ){
          print(usuario);
          Navigator.of(context).pushNamed('/termos-aceite', arguments: usuario.email);
        }else{
          //Logar
          _logarUsuario(usuario);
        }

// second screen
     Widget build(BuildContext context) {
    setState(() {
      args = ModalRoute.of(context).settings.arguments;
    });
    print('args');
    print(args); //value is null

A: you need to send a map not a property
Usuario usuario = Usuario();
    usuario.email = email;
    usuario.senha = senha;

    //cadastrar ou logar
    if( _cadastrar ){
      print(usuario);
      Navigator.of(context).pushNamed('/termos-aceite', arguments: {"email":usuario.email});
    }else{
      //Logar
      _logarUsuario(usuario);
    }

when you try to get the values cast the arguments as Map of String Object like this and and use the property key you to get the data
     setState(() {
  args = ModalRoute.of(context).settings.arguments as Map<String, Object>;

});
print('args');
print(args["email"]); //value is email's value

A: There is a better and generic approach to do that, and I would suggest you to do that.
So we can do this via using the Constructor method, which accepts some variable with values, in your case this is the page, i.e., /termos-aceite. Now taking the Page name as Termos for this /termos-aceite. Let us see how this works.
class Termos extends StatelessWidget {
  // Declare a field that holds the Todo.
  final dynamic email;

  // In the constructor, require a Todo.
  DetailScreen({Key key, @required this.email}) : super(key: key);

  //To use that, you can simply do
  print(args);
  setState(() {
    args = this.email;
  });
}

And In order to pass it to the page, in this case to Termos, we do this using your code only
Usuario usuario = Usuario();
usuario.email = email;
usuario.senha = senha;

//cadastrar ou logar
if( _cadastrar ){
   print(usuario);
   // Read about MaterialPageRoute() here
   // https://api.flutter.dev/flutter/material/MaterialPageRoute-class.html
   Navigator.push(context, MaterialPageRoute(
     builder: (context) => Termos(email: email)
   ));
}else{
  //Logar
  _logarUsuario(usuario);
}

I hope you will get it what you want. Also, please keep googling these things about flutter. It is cool, and you will find great things there in the documentation itself. I am anyway listing down some of the links for you, hope that would be a learning experience for you. Keep learning

*

*Flutter Dev Docs

*Naivgate With Argument

*Passing data to a new screen


text:
Q: How to keep Virtualbox from being uninstalled by kernel update in yum I use fedora, and installed virtualbox-ose from rpmfusion. It seems that the virtualbox-ose is compiled against certain kernel versions. If I update kernel with yum update, virtualbox-ose will be removed if older kernel is replaced by newer one.
Is there any good idea about that? How to keep my virtualbox from being uninstalled in this way, while I want to keep my system update-to-date as more as possible?

A: RPMFusion provides two types of kernel module packages:  kmods and akmods.  kmod packages contain binary kernel modules built for a specific version of the Linux kernel.  akmod packages contain the source code of kernel modules, and bring in via dependencies the tools needed to compile them.  If you have an akmod package installed, and you update the kernel, the akmod package will automatically build modules for the new kernel.
To switch to the akmod version, just run yum install akmod-VirtualBox-OSE.
That being said, just yesterday I switched to using the official YUM repository for VirtualBox from Oracle, because RPMFusion is two versions behind and I was experiencing a bug that was fixed in a newer version.  That also includes a dkms package for building the kernel modules automatically on kernel update.  (dkms is Debian's analog to akmod, but works fine on Fedora.)  You could also switch to that if you'd like.
To remove the RPMFusion version, add Oracle's repository, and install VirtualBox, run the following commands (as root):
yum remove VirtualBox-OSE
wget http://download.virtualbox.org/virtualbox/rpm/fedora/virtualbox.repo > /etc/yum.repos.d/virtualbox.repo
yum install VirtualBox-4.0 dkms
service vboxdrv setup

A: Either exclude the kernel from the update, or wait until RPMFusion has released an updated package.


text:
Q: How to set Claimtypes.NameIdentifier as a UserId value to multiple rows in other DB Table for new user When new, authenticated user logs in, i want to set his UserId from AspNetUsers table to my Tasks table as a UserId to each Task row. In my Tasks table is a set of six task rows as TaskId, UserId, TaskDescription, Count. In frontend each task has a button for to increment count how many times the user has accomplished each task. In my TaskController method following code sets the UserId as expected, but only to the last row of tasks.I have tried "foreach" loop but obviously I am doing something wrong.
private string GetCurrentUserId()
{
   return HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
}

private string GetUserId()
{
   return User.FindFirst(ClaimTypes.NameIdentifier).Value;
{

[HttpGet]
public ActionResult<IEnumerable<Tasks>> GetTasks()
{
   var tasks = _context.Tasks
       .Where(u => u.UserId == GetCurrentUserId())
       .ToList();

   if (tasks.IsNullOrEmpty())
   {
       Tasks tasks1 = new Tasks
       {
          UserId = GetUserId()   //this sets the UserId but only to the last task on the list, which
                                 //frontend also shows only.I want to show the whole set of
                                 //CurrentUsers tasks. Foreach loop gives me nulls, but I am a
                                 //student and maybe not doing it right.
       };

       _context.Add(tasks);
       _context.SaveChanges();
   }
     return tasks.ToList();
}


text:
Q: How to identify if a JSON Object is nested or not I am getting a JSON object on javascript page from a JSP page through an ajax call. I want to find out if it is a nested JSON object or not.
For example:
A simple JSON Object looks like this:
{
    "time":"2015-04-23T06:23:48.173+0000",
    "timeZone":"IST"
}

and a nested JSON Object looks like this:
{
    data" : {
        "attributes" : {
            "key1":"abc",
            "key2":"xyz"
        }
    }
}

So I want to differentiate between the two as I want to work with them differently
Thanks in advance...

A: Assuming you parsed the JSON, iterate over the properties of the object and check whether any property value is an object or not:
var isNested = Object.keys(obj).some(function(key) {
    return obj[key] && typeof obj[key] === 'object';
});

A: In javascript objects, are contained inside the curly brackets { }. A nested object is where the value of a key is another object.
In your example, the "attributes" object holds key1 and key2. Which is then nested inside the "data" object as its value.
JSON is mostly the same as regular javascript objects with a few restrictions and syntax.

A: You can use the following function, which checks for any object defined after the first level:
function check_if_nested(obj) {
    check_nest=[]
    obj.map(function(e,i) {$.each(e, function(v){
      if(typeof(obj[0][v])=='object') {check_nest.push('nested')} else {check_nest.push('not nested')}
    })})
    if(check_nest.includes('nested')) {return(true)} else {return(false)}
    }

Usage:
Not nested example:
obj_1 = [{
    one: "apples",
    two: "oranges"
}]

..usage:
check_if_nested(obj_1)

false
Nested example:
obj_2 = [{
    one: "apples",
    two: "oranges",
    children: [{
        three: "bananas",
        four: "jicamas"
    }]
}]

..usage:
check_if_nested(obj_2)

true


text:
Q: How to assign mysql result to variable (in C) I can't assign the result of query to variable (the program is written in C). Here is what I do
char buffer[100];

while ((row = mysql_fetch_row(res)) != NULL) {
   buffer = row[0];
}

A get this error during compile process
error: incompatible types in assignment

What is wrong here ?

A: Assuming it's a string? C doesn't have strings it has arrays of characters. So you have copy the characters from one array to another.
so use a copy function like
strncpy(buffer, row[0], 100);


text:
Q: Place button in one2many field tree view I want to add button in one2many tree view line. I have placed button in tree view and these button shows successfully.
But when i click on button, it display form define against one2many field instead of function call.
Need guidance how to call function/form on button click.
                    <page name="component_line_id" string="Component Lines">
                        <field name="component_line_id">
                            <tree>
                                <field name="purchase_order_id" required="1"/>
                                <field name="description"/>
                                <field name="payable_amount"/>
                                <field name="file_name" string="Attachment"/>
                                <button string="Create Bill" name="create_bill" type="object" class="oe_highlight" icon="fa-icon_you_like"/>
                                <button string="View Bill" name="view_bill" type="object" class="oe_highlight" icon="fa-icon_you_like"/>
                            </tree>
                            <form string="Component Lines">
                                <group>
                                    <group>
                                       <field name="purchase_order_id"/>
                                       <field name="description"/>
                                        <field name="payable_amount"/>
                                    </group>
                                    <group>
                                        <field name="attachment_file" filename="file_name"/>
                                        <field name="file_name" invisible="1"/>
                                    </group>
                                </group>
                            </form>
                        </field>
                    </page>

A: I think you need to save the record first to be able to run the button. Are you sure it was not on edit mode?


text:
Q: How to get RFC1123 Date format for current date time using XSLT 2.0 I am trying to retrieve current date time in RFC1123 date format in XSLT.
has anybody tried this using XSL2.0?
I have seen code for converting various date times based on zone in XSLT2.0 and to format in specific date time format such yyyy/mm/dd or YYYY:MM:DDTHH:MM:SS.0Z, but couldnt find a way to format it to show like this
Tue, 09 Jul 2019 20:34:29 GMT
concat(date:add('1970-01-01T00:00:00',concat('PT',floor(dp:time-value() div 1000),'S')),':',dp:time-value() mod 1000)
This returns in GMT format like this 2019-07-09T21:01:26:547
How to format it for - Tue, 09 Jul 2019 20:34:29 GMT using XSLT2.0?

A: Use current-dateTime() to get the current date and time and then use format-dateTime to format it as needed, see the spec https://www.w3.org/TR/xslt20/#function-format-dateTime on details: a picture string
'[FNn,*-3], [D01] [MNn] [H01]:[m01]:[s01] [z]'

on my machine in German summer time gives
format-dateTime(current-dateTime(), '[FNn,*-3], [D01] [MNn] [H01]:[m01]:[s01] [z]')

as
Wed, 10 July 12:01:13 GMT+02:00

This is meant as an example on the use of format-dateTime, I haven't checked the exact details of the RFC you cited to try to implement the exact requirements.

A: Thanks for quick reply, your solution worked using Altova XML Spy, but unfortunately it didnt worked for me in Datapower using XSLT2.0, Not sure what was wrong, may be some issue with DP firmware version.
just for other users to make this post more helpful. I tried below 2 options which didnt work for me, but might be useful for others.
using XSLT
<xsl:value-of select="java:java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneOffset.UTC))"></xsl:value-of>

<xsl:value-of select="format-dateTime(current-dateTime(), '[FNn,*-3], [D01] [MNn] [H01]:[m01]:[s01] [z]')"/>

So I used Gateway script to get same date format which I was looking for and stored in context variable using below
var dateNeeded = new Date()).toUTCString(); //Thu, 11 Jul 2019 21:08:12 GMT


text:
Q: Unable to use _bulk API on Elasticsearch on Windows I am new to windows . I was working my entire on linux. Can somebody help me here for _bulk api indexing
C:\ELK\master-1\elasticsearch\sample_data>curl -k -H 'Content-Type: application/x-ndjson' -X POST 'https://localhost:9200/bank/_bluk?pretty' -d @accounts.json
curl: (6) Could not resolve host: application
curl: (3) URL using bad/illegal format or missing URL

A: I see you typed "_bluk" instad of "_bulk" , also you must use the --data-binary flag instead of d:
curl -s -H "Content-Type: application/x-ndjson" -XPOST localhost:9200/_bulk --data-binary "@accounts.json"
docs: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html#bulk-curl


text:
Q: C passing in cat return value I want to know how to pass a value into a program like:
cat somefile | myprog
somefile:
hello
$cat somefile | myprog
>hello
this is what I tried.
int main(int argc, char **argv) {
  printf("%s", argv[1]);
  return 0;
}

I doubt it's complicated but I Just don't know how.
P.S my keyboard is boarderline broken if some chars are a little off.

A: If you want your example cat foo | bar to work, you need to read data from standard input, e.g.:
#include <stdio.h>

int main()
{
  int ch;
  while ( (ch = getchar()) != EOF )
    putchar(ch);
}

This program just echoes everything coming form standard input to standard output, so
$ cat somefile | myprog

will then print hello.  You don't have to parse anything from argv, because the surrounding shell will already have parsed that for you and discerned between stuff like program arguments and pipes.

A: You just have to read from the standard input of your program.
Try reading a line using cin or scanf.
For example for reading a single line and printing it out using cin:
#include <iostream>

int main()
{
   std::string s;
   std::getline(std::cin, s);
   std::cout << s << std::endl;

   return 0;
}

A: Here's a few options of what you might want here:

*

*You want to pass the filename 'somefile' to your program.
$ myprog somefile
argv is the parameter array - so you can access 'somefile' at argv[1]

*somefile contains a list of parameters like "hello world"
$ cat somefile | xargs myprog
Now 'hello' and 'world' will be at argv[1] and argv[2] respectively. It's analogous to invoking your program as myprog hello world.

*You want to read the contents of the pipe (the file contents) inside your file.
As others have said, you're just reading from stdin. Pipe effectively attaches the     stdout of the previous command to the stdin of the following command.