text:
Q: How should btime be specified? I have read that Unix systems has not specified btime or generally like POSIX, there is no specification about btime. There is a mention about btime.
Therefore the question, how should btime be specified or does it not matter and btime can be set whatever the user wants? Should btime be specified? If so, there are already proposals to add it to POSIX or the successor to POSIX. It would be good if someone can tell me where I can send a proposal.

A: I'm assuming that by "btime", you mean "birth time", or "file creation time". You're right, POSIX doesn't specify that currently, and there is no mention of "btime" in the standard, even in the current 202x draft. It does mention "file creation time", once, in relation to pax.
As mentioned in roaima's answer, the standard does allow additional fields to be added to struct stat. Some platforms have eschewed that however; on Linux for example the file creation time is available in struct statx, which is returned by the statx function. Adding fields to struct stat itself would create a risk of conflict with future issues of the standard.
If you want to change that, you'll need to get involved with the Austin Group, which is in charge of updating POSIX. You should plan on dedicating quite a lot of time to familiarise yourself with its way of working, and to participate passively before suggesting changes. You could start by looking at how the standard currently defines the existing timestamps, and where they are mentioned (including every single function which results in updating them).
Note that to a large extent, POSIX isn't the right venue to drive change; it tends to document features and normalise them once they are supported somewhere and have proven themselves useful.

A: POSIX does not define btime. However, it does allow for additional fields in the stat structure, "which shall include at least the following members", so I see no reason why non-POSIX implementations cannot include btime and still remain POSIX compliant.
...
struct timespec st_atim    Last data access timestamp.
struct timespec st_mtim    Last data modification timestamp.
struct timespec st_ctim    Last file status change timestamp.
...


text:
Q: Why would SQL queries that use reserved words suddenly start causing problems? In the past couple of days we have experienced issues with 3 different  applications that have been running fine for several years. Errors #1 and #2 were caused by reserved words in SQL queries. I am fairly certain that is also the cause of Error #3, but I cannot be sure as I don't have the source code. The databases for the three applications are all on the same instance of SQL Server. We are running SQL Server 2008 with no updates, and the last Windows update was in 2016. What could have caused these errors to suddenly start occurring?
Error details:

*

*We have a Web Forms site that has been used daily (and not updated) for the past 6 years. Two days ago it suddenly started throwing a SQL timeout exception on one of its pages. In SSMS I tested the raw queries being used and they all ran in under 2 seconds. However I noticed that two of them used the reserved words "Status" and "Date" without square brackets. I added square brackets around the reserved words and re-uploaded the site, and that fixed the error.

*Today users reported an issue with a report in an old MS Access Data Project. I tested the report myself and got a query timeout. The data source for the report is a table-valued function, which when I executed directly in SSMS completed in a matter of seconds. I examined the function body and saw that it used the reserved words "Priority" and "Timestamp". I added square brackets, altered the function, and voila, the report now opens with no errors.

*We have an .asmx web service that has been used daily for the past 6 years. One of the methods is supposed to query a table and return a list of user logins and passwords. Yesterday it started returning an empty response object. I don't have the source code for the web service so I can't see the text of the query. However I can see that the table has columns named with the reserved words "User_ID" and "Password", and based on the pattern for errors #1 and #2 I would bet that that's the problem.

These queries have been running for years without problems. Why would they suddenly start causing problems? Is there perhaps a configuration in SQL Server that has been changed?

A: You're not getting an error from the queries themselves - you're just seeing them take a long time to run. So you're not facing a problem where it has a problem with "date"'a being a reserved word.
What you're more likely to be seeing is a series of bad plans, possibly caused by some statistics getting updated at a bad time or something similar. The fact that you can tweak the queries a little and see performance improve makes me think that you could solve this by identifying and clearing out the bad plans, because you've been able to get good plans very easily. Query select * from sys.dm_exec_plan_cache c cross apply sys.dm_exec_sql_text(c.sql_handle) t or something like that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel problem passing variables from controller to mailer I am having trouble passing variables from the controller to the mail fucntion I have tried to search it up on google but didn't find anything that works my goal is to get the variable from the form to the welcomemail.blade the current issue is that the variable doesnt get to my wlcomemail.php from the controller. the mailing part itself does work.
Controller code:
$email_data = array(
            'first_name'=>'John',
            'last_name'=>'Doe',
            'email'=>'john@doe.com',
            'password'=>'temp',
        );

        //Customer::create($data);
        Mail::to($email_data['email'])->send(new welcomemail($email_data));

welcomemail.php code:

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class welcomemail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */

    public $email_data;
    public $example;

    public function __construct()
    {
        $this->email_data = $email_data;
        $this->example = 'example';
    }

    public function build()
    {
        return $this->markdown('emails.welcomemail');
    }
}

blade code:
# Introduction

Welcome.
{{$email_data['first_name']}}
{{$example}}
@endcomponent

A: change this:
public function __construct()
{
    $this->email_data = $email_data;
    $this->example = 'example';
}

to:
public function __construct($email_data)
{
    $this->email_data = $email_data;
    $this->example = 'example';
}

now you have it in your mail class
it should work


text:
Q: What is the best practice for a Relation between Accounts with two roles? I'm trying to get the best relation between the two roles that one account can have, which are "User" and "Company". I'm deciding between these:
If someone is going to register, he/she needs to choose between what role is going to use, then fill the rest of the fields. For example, If I register as a User, the field "companyId" is going to be empty, and I don't want that...

The same here, If I register as a company, I need to fill the required fields and that's it, but the field "userId" is empty, in case if I receive any feedback or I put my project.

So what is the best practice for doing this? You can read the complete "fields" that a User or Company needs to fill.

A: The first one raises some questions, for sure.

*

*Why would account be modeled as a child of feedback and project ?

*Similarly, why would both user and company be child entities of account?

I think those relationships are backwards: Instead of "Accounts have users" make it "Users have accounts". Apply the same to Account --> Feedback and Account --> Project: Feedback is given on Accounts, and Projects are tied to Accounts. This is close to what you've done in the second diagram, but there are some questions there too:

*

*What to do with Company? Is a Company really a separate entity from User? Or is there a relationship between them?

*Where does Account fit into the second diagram?

I would suggest something like this (the fields need to be updated with the correct keys, but the relationships are the important part):

This allows both a User and a Company to have an Account. It also allows User's to be assigned to a Company. Account's belong to either a User or a Company, and both Project and Feedback are defined in terms of an Account.
Also think in terms of the cardinality of each of these relationships:

*

*can a user be associated with more than 1 company? Must all users be assigned to a company?

*Can a company have no users?

*Does an account have exactly 1 owner? Can it be owned by both a User and a Company at the same time? Can it have no owner at all?

And some more general questions to consider:

*

*Does a project exist independently of an account (this might be phrased as "is Project a weak or a strong entity?")?

*Does feedback really apply to an account? Or is feedback actually a property of a User/Company?


text:
Q: Can I feed intermediate result back into the CNN and get my final result? (update) I am new to machine learning.
I got the intermediate result of layer 31 of my CNN using the following code:
conv2d = Model(inputs = self.model_ori.input, outputs= self.model_ori.layers[31].output)
intermediateResult = conv2d.predict(img)

I am trying to load this intermediate result back into the neural network.
Can this be done?
I tried doing the following:
newmodel = keras.Sequential(self.model_ori.layers[32:])
newmodel = newmodel.build(intermediateResult.shape)

I did the above but I got the following error:
A merge layer should be called on a list of inputs. Received: inputs=Tensor("up_sampling2d_2/resize/ResizeNearestNeighbor:0", shape=(1, 26, 26, 128), dtype=float32) (not a list of tensors)

Here is my model summary:
Model: "model"
__________________________________________________________________________________________________
 Layer (type)                   Output Shape         Param #     Connected to
==================================================================================================
 input_1 (InputLayer)           [(None, None, None,  0           []
                                 3)]

 conv2d (Conv2D)                (None, None, None,   432         ['input_1[0][0]']
                                16)

 batch_normalization (BatchNorm  (None, None, None,   64         ['conv2d[0][0]']
 alization)                     16)

 leaky_re_lu (LeakyReLU)        (None, None, None,   0           ['batch_normalization[0][0]']
                                16)

 max_pooling2d (MaxPooling2D)   (None, None, None,   0           ['leaky_re_lu[0][0]']
                                16)

 conv2d_1 (Conv2D)              (None, None, None,   4608        ['max_pooling2d[0][0]']
                                32)

 batch_normalization_1 (BatchNo  (None, None, None,   128        ['conv2d_1[0][0]']
 rmalization)                   32)

 leaky_re_lu_1 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_1[0][0]']
                                32)

 max_pooling2d_1 (MaxPooling2D)  (None, None, None,   0          ['leaky_re_lu_1[0][0]']
                                32)

 conv2d_2 (Conv2D)              (None, None, None,   18432       ['max_pooling2d_1[0][0]']
                                64)

 batch_normalization_2 (BatchNo  (None, None, None,   256        ['conv2d_2[0][0]']
 rmalization)                   64)

 leaky_re_lu_2 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_2[0][0]']
                                64)

 max_pooling2d_2 (MaxPooling2D)  (None, None, None,   0          ['leaky_re_lu_2[0][0]']
                                64)

 conv2d_3 (Conv2D)              (None, None, None,   73728       ['max_pooling2d_2[0][0]']
                                128)

 batch_normalization_3 (BatchNo  (None, None, None,   512        ['conv2d_3[0][0]']
 rmalization)                   128)

 leaky_re_lu_3 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_3[0][0]']
                                128)

 max_pooling2d_3 (MaxPooling2D)  (None, None, None,   0          ['leaky_re_lu_3[0][0]']
                                128)

 conv2d_4 (Conv2D)              (None, None, None,   294912      ['max_pooling2d_3[0][0]']
                                256)

 batch_normalization_4 (BatchNo  (None, None, None,   1024       ['conv2d_4[0][0]']
 rmalization)                   256)

 leaky_re_lu_4 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_4[0][0]']
                                256)

 max_pooling2d_4 (MaxPooling2D)  (None, None, None,   0          ['leaky_re_lu_4[0][0]']
                                256)

 conv2d_5 (Conv2D)              (None, None, None,   1179648     ['max_pooling2d_4[0][0]']
                                512)

 batch_normalization_5 (BatchNo  (None, None, None,   2048       ['conv2d_5[0][0]']
 rmalization)                   512)

 leaky_re_lu_5 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_5[0][0]']
                                512)

 max_pooling2d_5 (MaxPooling2D)  (None, None, None,   0          ['leaky_re_lu_5[0][0]']
                                512)

 conv2d_6 (Conv2D)              (None, None, None,   4718592     ['max_pooling2d_5[0][0]']
                                1024)

 batch_normalization_6 (BatchNo  (None, None, None,   4096       ['conv2d_6[0][0]']
 rmalization)                   1024)

 leaky_re_lu_6 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_6[0][0]']
                                1024)

 conv2d_7 (Conv2D)              (None, None, None,   262144      ['leaky_re_lu_6[0][0]']
                                256)

 batch_normalization_7 (BatchNo  (None, None, None,   1024       ['conv2d_7[0][0]']
 rmalization)                   256)

 leaky_re_lu_7 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_7[0][0]']
                                256)

 conv2d_10 (Conv2D)             (None, None, None,   32768       ['leaky_re_lu_7[0][0]']
                                128)

 batch_normalization_9 (BatchNo  (None, None, None,   512        ['conv2d_10[0][0]']
 rmalization)                   128)

 leaky_re_lu_9 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_9[0][0]']
                                128)

 up_sampling2d (UpSampling2D)   (None, None, None,   0           ['leaky_re_lu_9[0][0]']
                                128)

 concatenate (Concatenate)      (None, None, None,   0           ['up_sampling2d[0][0]',
                                384)                              'leaky_re_lu_4[0][0]']

 conv2d_8 (Conv2D)              (None, None, None,   1179648     ['leaky_re_lu_7[0][0]']
                                512)

 conv2d_11 (Conv2D)             (None, None, None,   884736      ['concatenate[0][0]']
                                256)

 batch_normalization_8 (BatchNo  (None, None, None,   2048       ['conv2d_8[0][0]']
 rmalization)                   512)

 batch_normalization_10 (BatchN  (None, None, None,   1024       ['conv2d_11[0][0]']
 ormalization)                  256)

 leaky_re_lu_8 (LeakyReLU)      (None, None, None,   0           ['batch_normalization_8[0][0]']
                                512)

 leaky_re_lu_10 (LeakyReLU)     (None, None, None,   0           ['batch_normalization_10[0][0]']
                                256)

 conv2d_9 (Conv2D)              (None, None, None,   130815      ['leaky_re_lu_8[0][0]']
                                255)

 conv2d_12 (Conv2D)             (None, None, None,   65535       ['leaky_re_lu_10[0][0]']
                                255)

==================================================================================================
Total params: 8,858,734
Trainable params: 8,852,366
Non-trainable params: 6,368
__________________________________________________________________________________________________
None

Can someone kindly help me out?
Sincerely,
Lolcocks.

A: It is easy, you can do it by layer.get_weights or set_weights during your running task or the callback function.
It must be same type criteria, model sequences, layer, matrix, or configuration.`
[ Sample 1 ]:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Model Initialize
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
model = tf.keras.models.Sequential([
        tf.keras.layers.InputLayer(input_shape=( 32, 32, 3 )),
        tf.keras.layers.Normalization(mean=3., variance=2.),
        tf.keras.layers.Normalization(mean=4., variance=6.),
        tf.keras.layers.Conv2DTranspose(2, 3, activation='relu', padding="same", name="Conv2DTranspose_01"),
        tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='valid'),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(4 * 256),
        tf.keras.layers.Reshape((4 * 256, 1)),

        tf.keras.layers.LSTM(128, return_sequences=True, return_state=False),
        tf.keras.layers.LSTM(128, name='LSTM256'),
        tf.keras.layers.Dropout(0.2),
])

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(64, activation='relu', name='dense64'))
model.add(tf.keras.layers.Dense(7))
model.summary()

Conv2DTranspose_01 = model.get_layer( name="Conv2DTranspose_01" )
weights_01 = Conv2DTranspose_01.get_weights()[0]
weights_02 = Conv2DTranspose_01.get_weights()[1]

Conv2DTranspose_01.set_weights([weights_01, weights_02])
weights_01 = Conv2DTranspose_02.get_weights()[0]
weights_02 = Conv2DTranspose_02.get_weights()[1]

[ Output ]:
[[[[ 0.12476468 -0.35062584  0.03172061]
   [ 0.24610531  0.17492849  0.21293753]]

  [[-0.0718551   0.12790853  0.15102917]
   [-0.02433318 -0.08994108 -0.30636993]]
...

[ Callback Fn ]:
class custom_callback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        print('weights: ' + str(self.model.get_weights()))
        Conv2DTranspose_01 = model.get_layer( name="Conv2DTranspose_01" )
        weights_01 = Conv2DTranspose_01.get_weights()[0]
        weights_02 = Conv2DTranspose_01.get_weights()[1]

Conv2DTranspose_01.set_weights([weights_01, weights_02])

custom_callback = custom_callback()

history = model.fit(x_train, y_train, epochs=3000, batch_size=5 ,validation_data=(x_test, y_test), callbacks=[custom_callback])


text: Q: sharing files with script I want to be able to write a script to share files within Google Drive folders using addfile.  However I'm running into issues getting to the correct folder for the from and to.  Example.  Share file1 in   drive/level1/master with drive/level1/foldera.  I have many files to share and copying/sharing them manually is time consuming.


text:
Q: Container height not expanding to fit content resulting in overflow I tried to work with flexboxes but am having trouble with it.
This is how it should look:

As soon as the display is too small, the content either overflows the nested flexbox or (while I tried to fix it myself) the nested flexbox overflows the main flexbox.
Bug:

html,
body,
.viewport {
  width: 100%;
  height: 100%;
  margin: 0;
  font-family: 'Open Sans', sans-serif;
  font-size: 11pt;
}

body {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
}

header,
article,
section,
footer {
  padding: 2em;
}

header {
  background-color: red;
}

article {
  background-color: aqua;
  -webkit-flex: 1;
  flex: 1;
}

section {
  background-color: yellow;
  display: flex;
  flex-direction: row;
  flex-grow: 1;
}

.offer {
  background-color: cornflowerblue;
  border: 1px solid black;
}

footer {
  background-color: forestgreen;
}

  Header

  Article

orem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentes

O2

O3

  Footer

A: If you want the container to expand with the content, then don't use a fixed height.
Use min-height instead.
jsFiddle demo

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh; /* allows container to expand with growing content */
  margin: 0;
  font-family: 'Open Sans', sans-serif;
  font-size: 11pt;
}
body > * {
  padding: 2em;
}
header {
  background-color: red;
}
article {
  flex: 1;
  background-color: aqua;
}
section {
  display: flex;
  flex: 1;
  background-color: yellow;
}
.offer {
  background-color: cornflowerblue;
  border: 1px solid black;
}
footer {
  background-color: forestgreen;
}
Header

Article

orem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentes

O2

O3

Footer

A: I'm not sure if this is what you were looking for, but you could add
       "flex-wrap: wrap; "
to the .section (yellow background). That will cause the boxes to stack vertically when they don't have enough space, and keep all of your content inside of the correct borders. The default setting for wrapping is no wrap, which is why your content squishing together like that.


text:
Q: Размещение различных виджетов в листаемом виджете Как сделать так, чтобы каждый виджет шел друг за другом?
Я использовал ScrollView. Понятно, что я установил для каждого виджета вручную размер и это не правильно, потому как у текстового виджеа может быть размер и 25 пикселей и 100 и т.д. И поэтому мои виджеты попадают друг на друга. Есть некоторые сомнения, что для этого лучше использовать не ScrollView. Я не знаю какой( Хоть ткните носом в какой стороне искать.
Вот то, что я попробовал:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
from kivy.lang.builder import Builder
from kivy.uix.image import AsyncImage
from kivy.uix.label import Label

Builder.load_string('''
<OpenScreen>:
    canvas:
        Color:
            rgba:(1,1,1,1)
        Rectangle:
            pos:self.pos
            size:self.size
    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            id:bar_open
            orientation:'horizontal'
            padding:10
            spacing:10
            size_hint:(1,.1)
            canvas:
                Color:
                    rgba:(0,0,1,1)
                Rectangle:
                    pos:self.pos
                    size:self.size
            Button:
                text:'Back'
                on_release:root.manager.current='main'
            Button:
                text:'Redact'
        ScrollView:
            BoxLayout:
                id:content
                padding:10
                spacing:10
                orientation:'vertical'
                size_hint_y:None
                height:self.minimum_height
''')

class OpenScreen(Screen):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        #Этот класс берёт строку,которая создается в другом классе(редакторе), и отрисовывает текст, а если
        #встречается путь к изображению({|image:path/to/pictures|}) то отрисовывает изображение
        self.string_of_text='''some text one
{|image:images/1.png|}
some text

two

{|image:images/3.png|}

some text else

abracadabara abracadabara abracadabara   abracadabara              abracadabara                  abracadabara

{|image:images/2.png|}

end
'''
        self.update_text(self.string_of_text)#вызываем функцию для создания виджетов

    def update_text(self,text):
        find_pic_start=text.find('{|image:')#Находим ключ отвечающий за изображение({|image:path/to/pictures|})
        if find_pic_start==-1:#если изображений нет, то просто отрисовываем текст
            self.ids.content.add_widget(Label(text=text,color=(0,0,0,1),text_size=(Window.width-25,None),
                                              size_hint_y=None,height=100))
        if find_pic_start!=-1:#если изображения есть, то...
            if find_pic_start==0:#если изображение это начало строки - рисуем изображение
                find_pic_end=text.find('|}')
                self.ids.content.add_widget(AsyncImage(source=text[8:find_pic_end],size_hint_y=None,height=50))
                text=text[find_pic_end+3:]#вырезаем путь из строки до текста

            if find_pic_start!=0:#если изображение это не начало строки - отрисовываем текст до изображения
                self.ids.content.add_widget(Label(text=text[:find_pic_start],color=(0,0,0,1),text_size=(Window.width-25,None),
                                              size_hint_y=None,height=100))
                text=text[find_pic_start:]#вырезаем текст из строки до изображения
            self.update_text(text)#вызываем функцию рекурсивно с новой урезанной строкой

class NoteApp(App):
    def build(self):
        sm=ScreenManager()
        sm.add_widget(OpenScreen(name='open'))
        return sm

if __name__ =='__main__':
    NoteApp().run()

И то, что получил:

А хотелось бы, чтобы последовательно друг за другом)

A: После некоторых попыток вот как всё вышло:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
from kivy.lang.builder import Builder
from kivy.uix.image import AsyncImage
from kivy.uix.label import Label

Builder.load_string('''
<OpenScreen>:
    canvas:
        Color:
            rgba:(1,1,1,1)
        Rectangle:
            pos:self.pos
            size:self.size
    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            id:bar_open
            orientation:'horizontal'
            padding:10
            spacing:10
            size_hint:(1,.1)
            canvas:
                Color:
                    rgba:(0,0,1,1)
                Rectangle:
                    pos:self.pos
                    size:self.size
            Button:
                text:'Back'
                on_release:root.manager.current='main'
            Button:
                text:'Redact'
        ScrollView:
            BoxLayout:
                id:content
                padding:10
                spacing:2
                orientation:'vertical'
                size_hint_y:None
                height:self.minimum_height

<MyLabel>:
    height:self.texture_size[1]
''')

class MyLabel(Label):
    #в этом классе в kv файле задаётся высота текстового виджета
    #в зависимости от количества его строк, тоесть текстуры текста по высоте,
    #которая может достигать различных величин. Как сделать это python коде я
    #пока не знаю
    pass

class OpenScreen(Screen):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        #Этот класс берёт строку и отрисовывает текст, а если
        #встречается путь к изображению({|image:path/to/pictures|}) то отрисовывает изображение
        self.string_of_text='''
some text 1
{|image:images/1.jpg|}

***********************
Ваше благородие, госпожа разлука,
Мне с тобою холодно - вот какая штука.
Письмецо в конверте - погоди, не рви...
Не везет мне в смерти - повезет в любви!
Письмецо в конверте погоди, не рви...
Не везет мне в смерти - повезет в любви!

Ваше благородие, госпожа удача,
Для кого ты добрая, а кому - иначе.
Девять граммов в сердце, постой, не зови...
Не везет мне в смерти - повезет в любви!
Девять граммов в сердце, постой, не зови...
Не везет мне в смерти - повезет в любви!

Ваше благородие, госпожа чужбина,
Жарко обнимала ты, да только не любила.
В шёлковые сети постой, не лови...
Не везет мне в смерти - повезет в любви!
В шёлковые сети постой, не лови...
Не везет мне в смерти - повезет в любви!

Ваше благородие, госпожа победа,
Значит, моя песенка до конца не спета.
Перестаньте, черти, клясться на крови...
Не везет мне в смерти - повезет в любви!
Перестаньте, черти, клясться на крови...
Не везет мне в смерти - повезет в любви!
***********************

{|image:images/2.jpg|}
О сколько нам открытий чудных
Готовят просвещенья дух
И опыт, сын ошибок трудных,
И гений, парадоксов друг,
И случай, бог изобретатель...
end
{|image:images/3.jpg|}
'''
        self.string_to_list=[]#этот список нужен для последовательной отрисовки объектов
        self.update_text(self.string_of_text)#вызываем функцию для создания виджетов

    def update_text(self,text):
        find_pic_start=text.find('{|image:')#Находим ключ отвечающий за изображение({|image:path/to/pictures|})
        if find_pic_start==-1:#если изображений нет, то просто отрисовываем текст
            self.string_to_list.append(text)#добавляем текст в список
            print('end!')
            self.create_widgets()

        if find_pic_start!=-1:#если изображения есть, то...
            if find_pic_start==0:#если изображение это начало строки - рисуем изображение
                find_pic_end=text.find('|}')
                self.string_to_list.append(text[:find_pic_end+3])#добавляем изображение в список
                text=text[find_pic_end+3:]#вырезаем путь из строки до текста

            if find_pic_start!=0:#если изображение это не начало строки - отрисовываем текст до изображения
                self.string_to_list.append(text[:find_pic_start])#добавляем текст в список
                text=text[find_pic_start:]#вырезаем текст из строки до изображения
            self.update_text(text)#вызываем функцию рекурсивно с новой урезанной строкой

    def create_widgets(self):#проходим элементы списка и в зависимости от содержимого рисуем соответствующий виджет
        for i in self.string_to_list:
            if '{|image:' in i:
                #пусть высота изображения будет зависима от высоты окна
                self.ids.content.add_widget(AsyncImage(source=i[8:-3],size_hint_y=None,height=(Window.height*0.4)))
            if '{|image:' not in i:
                #Используем собственный виджет MyLabel, у которого высота зависит от текстуры текста
                self.ids.content.add_widget(MyLabel(text=i,color=(0,0,0,1),text_size=(Window.width-25,None),
                                              size_hint_y=None))

class NoteApp(App):
    def build(self):
        sm=ScreenManager()
        sm.add_widget(OpenScreen(name='open'))
        return sm

if __name__ =='__main__':
    NoteApp().run()

И вот результат работы:


text:
Q: Why aren't any items showing in my TextBox's autocomplete dropdown? I have a TextBox in my Windows Forms project which as part of a table holds a description of some material a company will buy. To ensure that the company enforces consistent naming, I have implemented autocomplete on the TextBox as so:
 AutoCompleteStringCollection source = new AutoCompleteStringCollection();
source.AddRange(pastItems);
desc.AutoCompleteCustomSource = source;
desc.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
desc.AutoCompleteSource = AutoCompleteSource.CustomSource;

But when I am typing anything into the TextBox, the dropdown is not populating.


text:
Q: Pandas to_datetime function giving erratic output My data frame has a column 'Date' which is of type object but I want to convert it to pandas time series. So I am using pd.to_datetime function. This function is converting the datatype but giving erratic output.
code:
x1['TS'] = pd.to_datetime(x1['Date'])
x1['Day'] = x1['TS'].dt.dayofweek
x1[['Date', 'TS', 'Day']].iloc[::1430,:]

Now notice the output closely and see the columns Date and TS. it should be same but in some cases, its different.
output :
        Date            TS     Day
0       01-12-2017  2017-01-12  3
1430    01-12-2017  2017-01-12  3
2860    02-12-2017  2017-02-12  6
4290    03-12-2017  2017-03-12  6
5720    04-12-2017  2017-04-12  2
7150    05-12-2017  2017-05-12  4
8580    07-12-2017  2017-07-12  2
10010   08-12-2017  2017-08-12  5
11440   09-12-2017  2017-09-12  1
12870   09-12-2017  2017-09-12  1
14300   10-12-2017  2017-10-12  3
15730   11-12-2017  2017-11-12  6
17160   12-12-2017  2017-12-12  1
18590   13-12-2017  2017-12-13  2
20020   14-12-2017  2017-12-14  3
21450   15-12-2017  2017-12-15  4
22880   16-12-2017  2017-12-16  5
24310   17-12-2017  2017-12-17  6
25740   18-12-2017  2017-12-18  0
27170   19-12-2017  2017-12-19  1
28600   20-12-2017  2017-12-20  2
30030   21-12-2017  2017-12-21  3
31460   22-12-2017  2017-12-22  4
32890   23-12-2017  2017-12-23  5
34320   24-12-2017  2017-12-24  6
35750   25-12-2017  2017-12-25  0
37180   26-12-2017  2017-12-26  1
38610   27-12-2017  2017-12-27  2
40040   28-12-2017  2017-12-28  3
41470   29-12-2017  2017-12-29  4
42900   30-12-2017  2017-12-30  5
44330   31-12-2017  2017-12-31  6
45760   01-01-2018  2018-01-01  0
47190   02-01-2018  2018-02-01  3
48620   03-01-2018  2018-03-01  3
50050   04-01-2018  2018-04-01  6
51480   05-01-2018  2018-05-01  1
52910   06-01-2018  2018-06-01  4
54340   07-01-2018  2018-07-01  6
55770   08-01-2018  2018-08-01  2
57200   09-01-2018  2018-09-01  5
58630   10-01-2018  2018-10-01  0
60060   11-01-2018  2018-11-01  3
61490   12-01-2018  2018-12-01  5
62920   13-01-2018  2018-01-13  5
64350   14-01-2018  2018-01-14  6
65780   15-01-2018  2018-01-15  0
67210   16-01-2018  2018-01-16  1

A: Oops! Looks like your dates start with the day being first. You'll have to tell pandas to handle that accordingly. Set the dayfirst flag to True when calling to_datetime.
x1['TS'] = pd.to_datetime(x1['Date'], dayfirst=True)

A: When you pass in a time without specifying the format, Pandas tries to guess at the format in a naive manner. It was assuming that what is your day is actually your month but then when it sees that it is month 13, realizes that can't be the month column and switches.
The following should work but I like @cᴏʟᴅsᴘᴇᴇᴅ's solution better because it is simpler to just raise the dayfirst flag.
To fix this, provide the current format to the to_datetime function.
The documentation gives the following example which you can modify to fit your situation:
pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')

See details here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html
Time format conventions (what %Y means and so on) are here: https://docs.python.org/3.2/library/time.html


text:
Q: How to enable tracking deep changes in component props I have a component who initialized like this
<custom :opts="{map: false}"></custom>

and there is HTML similar to this
<template id="custom">
    <div v-if="opts.map">
    I'm awesome
    </div>
    <button v-on:click="show"></button>
</template>

where
function show(){
    this.opts = {map:true} // (1) <-- This is working and I could see hidden div
    this.opts.map = true // (2) <-- For some reason not working
    Vue.set(this.opts, 'map', true) // (3) <-- Still not working
}

So my question is why variant 2 doesn't work and what should I change to make my control react to value reset on a button click. Or a proper explanation why (1) is working, but (2) isn't - also will be accepted as an answer.

A: The real problem with the code (all 3 versions) is changing a component's property from within a component. In idiomatic Vue, only the parent should change properties. If a component needs to effect a change, it should emit an event to the parent and let the parent make the necessary changes. Otherwise, there is ambiguity in which component "owns" the property.
One Way Data Flow

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around.

Sending Messages to Parents with Events

A: Can be off base here but I believe this happens because in vue component props are not reactive, so their objects are not being observed in depth. Or rather they are "a little bit reactive", reassigning the root prop does cause the DOM update but is not expected to be done manually and you'll see a warning when doing such on development build:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "..."

And for as why props are not completely reactive in the first place: https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow
To work around the whole issue you must pass any necessary props to the component data and if those props were passed as nested objects you might also want to completely avoid mutating them from within the component since it will propagate to the parent which, unless clearly mentioned, can be a source of bad news.


text:
Q: Python, argparse command line argument Assertion Error My command line arguments that use argparse returns AssertionError. I have two scripts and a directory that stores three data files.
Script:

*

*main.py which does a job of loading data

*data.py which does pre-processing for language data

Data:

*

*three tokens are stored in C:\Users\archive path

data.py script
**#data.py**
import os
from io import open
import torch

class Dictionary(object):
    def __init__(self):
        self.word2idx = {}
        self.idx2word = []

    def add_word(self, word):
        if word not in self.word2idx:
            self.idx2word.append(word)
            self.word2idx[word] = len(self.idx2word) - 1
        return self.word2idx[word]

    def __len__(self):
        return len(self.idx2word)

class Corpus(object):
    def __init__(self, path):
        self.dictionary = Dictionary()
        self.train = self.tokenize(os.path.join(path, 'train.txt'))
        self.valid = self.tokenize(os.path.join(path, 'valid.txt'))
        self.test = self.tokenize(os.path.join(path, 'test.txt'))

    def tokenize(self, path):
        """Tokenizes a text file."""
        assert os.path.exists(path)
        # Add words to the dictionary
        with open(path, 'r', encoding="utf8") as f:
            for line in f:
                words = line.split() + ['<eos>']
                for word in words:
                    self.dictionary.add_word(word)

        # Tokenize file content
        with open(path, 'r', encoding="utf8") as f:
            idss = []
            for line in f:
                words = line.split() + ['<eos>']
                ids = []
                for word in words:
                    ids.append(self.dictionary.word2idx[word])
                idss.append(torch.tensor(ids).type(torch.int64))
            ids = torch.cat(idss)

        return ids

main.py script
**#main.py**
import argparse
import time
import math
import os
import torch
import torch.nn as nn
import torch.onnx

import data

parser = argparse.ArgumentParser(description='PyTorch Wikitext-2 RNN/LSTM/GRU/Transformer Language Model')
parser.add_argument('--data', type=str, default='./data/wikitext-2',
                    help='location of the data corpus')
parser.add_argument('--model', type=str, default='LSTM',
                    help='type of recurrent net (RNN_TANH, RNN_RELU, LSTM, GRU, Transformer)')
parser.add_argument('--emsize', type=int, default=200,
                    help='size of word embeddings')
parser.add_argument('--nhid', type=int, default=200,
                    help='number of hidden units per layer')
parser.add_argument('--nlayers', type=int, default=2,
                    help='number of layers')
parser.add_argument('--lr', type=float, default=20,
                    help='initial learning rate')
parser.add_argument('--clip', type=float, default=0.25,
                    help='gradient clipping')
parser.add_argument('--epochs', type=int, default=40,
                    help='upper epoch limit')
parser.add_argument('--batch_size', type=int, default=20, metavar='N',
                    help='batch size')
parser.add_argument('--bptt', type=int, default=35,
                    help='sequence length')
parser.add_argument('--dropout', type=float, default=0.2,
                    help='dropout applied to layers (0 = no dropout)')
parser.add_argument('--tied', action='store_true',
                    help='tie the word embedding and softmax weights')
parser.add_argument('--seed', type=int, default=1111,
                    help='random seed')
parser.add_argument('--cuda', action='store_true',
                    help='use CUDA')
parser.add_argument('--log-interval', type=int, default=200, metavar='N',
                    help='report interval')
parser.add_argument('--save', type=str, default='model.pt',
                    help='path to save the final model')
parser.add_argument('--onnx-export', type=str, default='',
                    help='path to export the final model in onnx format')
parser.add_argument('--nhead', type=int, default=2,
                    help='the number of heads in the encoder/decoder of the transformer model')
parser.add_argument('--dry-run', action='store_true',
                    help='verify the code and the model')

args = parser.parse_args()

# Set the random seed manually for reproducibility.
torch.manual_seed(args.seed)
if torch.cuda.is_available():
    if not args.cuda:
        print("WARNING: You have a CUDA device, so you should probably run with --cuda")

device = torch.device("cuda" if args.cuda else "cpu")

###############################################################################
# Load data
###############################################################################

corpus = data.Corpus(args.data)

When I run main.py in terminal:
$ python main.py

The assertionError appears as below:
File "main.py", line 67, in <module>
    corpus = data.Corpus(args.data)
File "C:\Users\archive\data.py", line 22, in __init__
    self.train = self.tokenize(os.path.join(path, 'train.txt'))
File "C:\Users\archive\data.py", line 28, in tokenize
    assert os.path.exists(path)
AssertionError


text:
Q: PHP Парсер. Как скопированы данные отображать по ссылкам на отдельных страницах? Я сделал парсер который копирует заголовки с каждой публикации на главной странице сайта. Также парсер копирует ссылки на каждую публикацию, это для того чтобы в дальнейшем парсить содержание публикаций, ну и конечно содержание публикаций парсер тоже парсить.
В результате на экране я получил список заголовков и под заголовками информацию которая находилась внутри статьи, то есть содержание публикации которую я парсил за ссылками.
Как мне сделать так, чтобы каждый заголовок стал автоматически ссылкой а информация которую я парсил отображалась по этой ссылке тоесть на новой странице?
Код парсера:
header('Content-type: text/html; charset=utf-8');
require 'phpQuery.php';

function parseArticle($url){
    $file = file_get_contents($url);
    $doc = phpQuery::newDocument($file);
    $text = $doc->find('.post-body')->html(); //парсинг содержания публикаций (по ссылками)
    print_arr($text);
}

function print_arr($arr){
    echo '<pre>' . print_r($arr, true) . '</pre>';
}

$url = 'http://stvorenonaukoy.blogspot.com/';
$file = file_get_contents($url);

$doc = phpQuery::newDocument($file);

foreach($doc->find('.blog-posts .post-outer .post') as $article){
    $article = pq($article);
    $text = $article->find('.entry-title a')->html(); //парсинг заголовков
    print_arr($text);
    $texturl = $article->find('.entry-title a')->attr('href'); //парсинг ссылок
    parseArticle($texturl);
}


text:
Q: Scandinavian characters get messed up in Shibboleth SP header attributes I have Shibboleth SP 2.5 with Apache 2.4 in front of Domino 9.0.1 server on Windows server 2008 R2.
This is the beginning of the incoming SAML message from Shibboleth SP debug log:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

And here is an attribute value from the same log:
<saml:AttributeValue>Mäkelä Test</saml:AttributeValue>

Attributes are passed as HTTP headers to Domino. In Domino form I do @GetHTTPHeader("cn") to get that attribute value and I get

Mäkelä Test

In Shibboleth SP configuration I haven't set character set anywhere and I believe it should be always UTF-8.
My Apache proxy configuration looks like this:
ServerName my.test.fi:8443
UseCanonicalName On
ProxyPass / http://my.test.fi/

I have tried these:
ProxyHTMLMeta On
RequestHeader unset Accept-Encoding
AddDefaultCharset utf-8
CharsetSourceEnc  UTF-8
CharsetDefault    UTF-8

In domino Web Site document I have "Use UTF-8 for output" set to "Yes" and form character set is set to UTF-8. Domino response headers include this:
Content-Type:text/html; charset=UTF-8

For me it looks like the characters are already messed up when the arrive from Shibbolet SP/Apache to Domino. Any ideas how to fix this?

A: The solution is to use an XPage in Domino. This Server Side Javascript (SSJS) code returns scandinavian characters correctly:
facesContext.getExternalContext().getRequestHeaderMap().get("cn");


text:
Q: webpy and CherryPyWSGIServer I'm using the bottom piece of code for my program http://webpy.org/cookbook/ssl and when I connect to my python server through https all is well. Then when I go to connect to my server as http it does not connect as expected.
But then when I go back to https I get a time out every time and I have to restart my comp so I can connect again.
Can anyone help me with where to start on this problem?
Thanks.

A: In your nginx, or apache server configuration file, you need to redirect the page to https all the time, or handle the http properly.  for example if somebody hits my server I permanently redirect to the https every time like this in Nginx:
server {
    listen 80;
    rewrite ^ https://$host$request_uri permanent;
}

You will also need to define your webpy application handling.  I ended up using Ubuntu, Nginx, uWSGI with webpy and my site works really well.  Hopefully this helps.  I was doing the exact same thing as you until I found this site:
http://fartersoft.com/blog/2012/02/10/deployment-of-web-py-applications-using-uwsgi-and-nginx-on-ubuntu/
Which helped me get started.  I hope it helps you.


text:
Q: Traversable recursive node structures I am trying to implement recursive traversions over a node structure:
sealed class Node(subnodes: Traversable[Node]) extends Traversable[Node] {
  def foreach[U](f: Node => U) {
    f(this)
    subnodes foreach f
  }
}

case class Atom(id: String) extends Node(Nil)

case class Molecule(atoms: List[Node]) extends Node(atoms)

Calling toString on an element like Atom("test").toString causes a stack overflow:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.System.arraycopy(Native Method)
at java.lang.String.getChars(Unknown Source)
at java.lang.AbstractStringBuilder.append(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at scala.collection.mutable.StringBuilder.append(StringBuilder.scala:197)
at scala.collection.TraversableOnce$class.addString(TraversableOnce.scala:297)
at Node.addString(Fail.scala:1)
at scala.collection.TraversableOnce$class.mkString(TraversableOnce.scala:263)
at Node.mkString(Fail.scala:1)
at scala.collection.TraversableLike$class.toString(TraversableLike.scala:615)
at Node.toString(Fail.scala:1)
at java.lang.String.valueOf(Unknown Source)
at scala.collection.mutable.StringBuilder.append(StringBuilder.scala:187)
at scala.collection.TraversableOnce$$anonfun$addString$1.apply(TraversableOnce.scala:300)
[...]
at Node.foreach(Fail.scala:3)
at scala.collection.TraversableOnce$class.addString(TraversableOnce.scala:298)
at Node.addString(Fail.scala:1)
at scala.collection.TraversableOnce$class.mkString(TraversableOnce.scala:263)
at Node.mkString(Fail.scala:1)
at scala.collection.TraversableLike$class.toString(TraversableLike.scala:615)
at Node.toString(Fail.scala:1)
at java.lang.String.valueOf(Unknown Source)
at scala.collection.mutable.StringBuilder.append(StringBuilder.scala:187)
at scala.collection.TraversableOnce$$anonfun$addString$1.apply(TraversableOnce.scala:300)

Note that I haven't called foreach anywhere explicitly. So why do I get a stack overflow?
I solved this particular problem with an additional TraversableNode class and an implicit conversion from Node to TraversableNode, but I would still like to know what caused the stack overflow. Thanks.

A: When you call toString on an Atom, you're getting the one for Traversable, which the documentation describes like this:

By default this string consists of the stringPrefix of this
  collection, followed by all elements separated by commas and enclosed
  in parentheses.

The "followed by all elements" part is implemented in TraversableOnce by calling the collection's foreach. Since your foreach first hits the Node itself, you immediately run into an endless loop.

A: Normally, the toString method on case classes prints the class name and the list of its arguments (those in the first argument list). An exception is made to this rule, if your case class extends a class which has an explicitly defined toString.
Your Node extends Traversable[Node]. Note that it does not have a compiler-generated case-class toString, as shown in its AST (scalac -Xprint:cleanup):
case class Atom extends Node with Product with Serializable {
   ....
    override <synthetic> def hashCode(): Int = ScalaRunTime.this._hashCode(Atom.this);
    override <synthetic> def equals(x$1: Any): Boolean = Atom.this.eq(x$1.asInstanceOf[Object]()).||(x$1.isInstanceOf[Atom]().&&({
      <synthetic> val Atom$1: Atom = x$1.asInstanceOf[Atom]();
      Atom.this.id().==(Atom$1.id()).&&(Atom$1.canEqual(Atom.this))
    }))
  };

Above, the compiler "only" generates hashCode and equals, the toString is inherited from Traversable.
The Traversable trait from the collection package has a toString method which is defined in terms of foreach. Calling toString thus makes the foreach iterate on the node itself (in line with f(this)), resulting in an infinite loop.


text:
Q: Prevent reference loop properties from serializing I am getting a buffer exception in one of my unit tests on my controllers for a aspnet.core project.
System.Net.Http.HttpRequestException: Cannot write more bytes to the buffer than the configured maximum buffer size: 2147483647
Digging into it - it is because of a many to many relationship I have configured where I have included the related collection in the response to an entity:
My model(s):
public class Employee
{
    [Key] public Guid Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public decimal Salary { get; set; }
    public DateTime HireDate { get; set; }
    public Guid? ManagerId { get; set; }
    public Guid AddressId { get; set; }

    public virtual ICollection<EmployeeRole> EmployeeRoles { get; set; }
    public virtual Employee Manager { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
    public virtual Address Address { get; set; }
    public virtual ICollection<EmployeeProject> Projects { get; set; }
}

public class EmployeeProject
{
    [Key]
    [Column(Order = 1)]
    public Guid EmployeeId { get; set; }
    [Key]
    [Column(Order = 1)]
    public Guid ProjectId { get; set; }

    public virtual Project Project { get; set; }
    public virtual Employee Employee { get; set; }
}

My context configuration:
        modelBuilder.Entity<EmployeeProject>(employeeProject =>
        {
            employeeProject.HasKey(ep => new {ep.EmployeeId, ep.ProjectId});
            employeeProject.HasOne(ep => ep.Project)
                .WithMany(p => p.EmployeeProjects)
                .HasForeignKey(ep => ep.ProjectId);
            employeeProject.HasOne(ep => ep.Employee)
                .WithMany(e => e.Projects)
                .HasForeignKey(ep => ep.EmployeeId);

        });

        modelBuilder.Entity<Employee>(emp =>
        {
            emp.HasKey(e => e.Id);
            emp.Property(p => p.Id).ValueGeneratedOnAdd();
            emp.HasMany(e => e.EmployeeRoles);
            emp.HasOne(e => e.Manager).WithMany(e => e.Employees).IsRequired(false);
            emp.HasOne(e => e.Address).WithOne(a => a.Employee)
                .HasForeignKey<Employee>(e => e.AddressId);
            emp.HasMany(e => e.Projects);
        });

The problem is I want to include the ICollection with my result of context.Employess.  i.e.
ctx.Employees.Include(e => e.Projects).ToListAsync();

This is resulting in all of the related Employee records to be included on each EmployeeProject record, which in turn has the related ICollection and so on.  i.e.
[
    {
       "Id": "1",
       "Projects": [
                      {
                         "EmployeId": "1"
                         "ProjectId": "A"
                         "Employee":
                                    {
                                         "Id": "1"
                                         "Projects": [
                                                        {
                                                            "EmployeId": "1"
                                                             "ProjectId": "A"
                                                             "Employee":

And so on.
This when returned in a web response results in a buffer overflow.
I am ignoring the ReferenceLoopHandling in my configuration:
services.AddMvc().AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });

From the Newtonsoft.Json namespace
/// Ignore loop references and do not serialize.
Ignore,
/// Serialize loop references.
Serialize,

A: You can try these attributes :
[JsonObject(IsReference = true)]
This attribute to top of your Class and
[JsonIgnore]
This attribute to top of your Property which is causing the reference loop.
I hope I understand your problem clearly.


text:
Q: Context from ConstraintValidator doesn't return an instance of ExecutionContextInterface Symfony validator seems doesn't work. I've noticed that with the service validator.email. ConstraintValidaotr::$context doesn't return a ExecutionContextInterface instance, so I get the error

Attempted to call an undefined method named "buildViolation" of class "Symfony\Component\Validator\Constraints\EmailValidator".

With a custom constraint validator the same happens:
<?php
namespace MyAppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class Test extends Constraint
{
    public $message = 'Error message';

    public function getTarget()
    {
        return self::CLASS_CONSTRAINT;
    }

    public function validatedBy()
    {
        return 'test_validator';
    }
}

and the validator
<?php
namespace MyAppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class TestValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $this->context->buildViolation('...')->addViolation('test');
    }
}

services.yml
validator.test:
    class: MyAppBundle\Validator\Constraints\TestValidator
    tags:
        - { name: validator.constraint_validator, alias: test_validator }

I got the same error.
And this
public function validate($value, Constraint $constraint)
{
    echo get_class($this->context);
    $this->context->buildViolation('...')->addViolation('test');
}

on controller:
$this->get('validator.test')->validate('', new Test());

Says that context is an instance of MyAppBundle\Validator\Constraints\TestValidator. There's no sense.
I'm using Symfony 3.0.0.

A: I don't know why, but following the documentation tutorial it doesn't worked.
This worked:
$errors = $this->get('validator')->validate($value, new Test());


text:
Q: Using SQLAlchemy to migrate databases (sqlite to Postgres CloudSQL) Trying to migrate the database for an early project of mine to the cloud.  Although the code that built everything is janky, the db structure and data itself are fairly sound.  I could probably figure out a dump method of migrating everything (pgdump, etc), but I still have much to learn about this stuff so I'd rather get the experience by doing it step-by-step.
Source: A ~1gb sqlite database file
Destination: Google CloudSQL running Postgres v9.6
Already created the tables in the cloud db, using the same schema & table names as the sqlite db.  Not worried about schema enforcement errors because I haven't yet defined foreign keys in the cloud.
The Plan: Create distinct, concurrent SQLAlchemy connections to each database, then read sqlite --> write to CloudSQL.  Went back and defined data structures for each table using SQLAlchemy.  Snippet from models.py:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base, declared_attr

Base = declarative_base()

class PublicMixin(object):
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

class Category(PublicMixin, Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)

class Player(PublicMixin, Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)
    username = Column(String)
    notes = Column(String)
[...]

I then duplicated this file as models_lite.py so I could import each model without potential for interference.  Here's the migration.py file I tried to run as a proof of concept:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base, Category, Player
from models_sqlite import Base as Base_lite, Category as Category_lite, Player as Player_lite

# SQLite db
engine_lite = create_engine('sqlite:///mydb.sqlite')
Base_lite.metadata.bind = engine_lite
LiteSession = sessionmaker()
LiteSession.bind = engine_lite
session_lite = LiteSession()

# CloudSQL, via local proxy
engine_cloud = create_engine('postgresql+psycopg2://USER:PW@/DBNAME?host=/cloudsql/INSTANCE')
Base.metadata.bind = engine_cloud
CloudSession = sessionmaker()
CloudSession.bind = engine_cloud
session_cloud = CloudSession()

category_lite = session_lite.query(Category_lite).all()
category_cloud = Category()

for c in category_lite:
    category_cloud = c
    session_cloud.add(category_cloud)

session_cloud.commit()

Running this yields the following error:
File "postgres migration.py", line 68, in <module>
    session_cloud.add(category_cloud)
[...]
sqlalchemy.exc.InvalidRequestError: Object '<Category at 0x11141b908>' is already attached to session '1' (this is '2')

Explicitly setting each column inside the for loop works (i.e.: category_cloud.id = c.id), but there must be a way to avoid having to do this for every column in every table.  How should I approach this?

A: This kind of data transfer operation is much more easily achieved with sqlalchemy core rather than the orm. There is no benefit to mapping database data to objects here if they are only going to be immediately written to another database, it just adds complexity and slows things down. The following code will iterate through every table in Base, select all the columns in the sqlite database and write them one table at a time to the cloud database.
from sqlalchemy import create_engine, select
from models import Base

engine_lite = create_engine('sqlite:///mydb.sqlite')
engine_cloud = create_engine('postgresql+psycopg2://USER:PW@/DBNAME?host=/cloudsql/INSTANCE')

with engine_lite.connect() as conn_lite:
    with engine_cloud.connect() as conn_cloud:
        for table in Base.metadata.sorted_tables:
            data = [dict(row) for row in conn_lite.execute(select(table.c))]
            conn_cloud.execute(table.insert().values(data))


text:
Q: Using Amazon TVM instead of a regular AccessKey/SecretKey I am building an Android application that will send reports to a server. These reports are plain JSON files stored on Amazon S3.
The Amazon user only has the PutObject permission on a specific S3 bucket.
The documentation states that we should use the Token Vending Machine mechanism instead of hardcoded keys within the application.
I cannot see the advantage of this method.
I get that a hacker could decompile my app to find the keys. But his only choice then is to send files to the bucket, nothing else (no file listing, no file retrieval).
If I use the anonymous TVM, the process is:

*

*Get a token valid for 24 hours

*Use this token to send files to the bucket

A hacker could also call the TVM server to request unlimited tokens and send files to my bucket. It does not seem to solve this problem.
What is the real advantage in using TVM?

A: You can attach different authorizations to each mobile UID, giving your finer control over what you allow people to access. You can also control how much AWS access the TVM has using policies. You can also stop it any given time. If they get your keys, you will have to disable the whole account. If you are OK with that, you probably don't need to use the TVM.


text:
Q: Can't get to the DOM element I got voting script on my page (jQuery Raty), everything work's fine but I want to change rate number in my ajax after voting.
Have problem with getting to span class .glosy
My html:

        170
    głosów

My JS:
('.score').raty({

click: function(score) {

var licznik_komentarzy = $(this).find('.glosy').text();
var zapisanie_licznika = $(this).find('.glosy').val(licznik_komentarzy);
var dodanie_licznika = +$(this).find('.glosy').val() + 1;
$(this).find('.glosy').text(dodanie_licznika);
            }
            });

tried different methods (next(), nextAll(), find()) and still cant figure it out.

A: Assuming that this is actually the element (depends on how plugin is written) ... you are looking in the wrong direction in the DOM tree.
closest() looks up the tree for ancestors.
You would need to use find() to look for a descendant of .score


text:
Q: How to remove Creative Cloud Files shortcut from Windows Explorer (left Navigation Pane) after April 2021 update? The "Creative Cloud Files" shortcut was a pain to get rid of in the past, but after a recent update in spring 2021, the damn shortcut is back, and none of the old tricks work anymore.
Has anybody found a method to remove it?

A: According to Adobe, set the following REGKEY to 1 will unpin Creative Cloud Files:
[HKEY_CURRENT_USER\Software\Policies\Adobe\CreativeCloud]
"unPinCCF"=dword:00000001

However it doesn't seem to work. This is what works for me on Windows 10 and Windows 11:

*

*Open Registry Editor

*Navigate Computer\HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID

*Search for "System.IsPinnedToNameSpaceTree", and locate a key that contain a string Creative Cloud Files.

*Set the value of System.IsPinnedToNameSpaceTree to 0

*Restart Windows Explorer for the change to take effect

A: I have been trying all the methods that I found. Nothing works for me.
I did something different, explained as follows:

*

*Open "File Explorer Options" from Control Panel or the Search bar.

*Click on View.

*Click on "Reset Folders"

*Then click on "Restore Default".

*Click on "Apply".

*Cheers.

A: The RegEx approach described in the procedure above or described in other posts would not work for me. I expect Adobe has made a change to their implementation.
This answer gives a tested method for anyone who wants to remove the "Creative Cloud Files" shortcut, using procedure similar to that provided by Adobe.

*

*Go to the Adobe help site Adobe Unlink Tool.

*Download PinCCF.zip from Adobe and extract its content.

*There are 2 files, one for creating the link and the other for removing it.

*Double-click on unPinCCF.reg (the unlink file) from the extracted folder to run it.

*A message appears advising that you want to add unPinCCF.reg to the registry. Click Yes.

*A confirmation message appears once the registry is successfully updated. Click OK.

You may need to restart File Explorer or Windows for the change to take effect. I did not need to do this and the "Creative Cloud Files" shortcut was immediately removed. I am using Windows 11 version 22H2.
If you later want to re-create the shortcut, all you need to do is run the rePinCCF.reg file also provided in the Adobe download zip file.
I hope this helps unclutter File Explorer a little for anyone who is not using "Creative Cloud Files".

A: For me I had to remove this registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\0E270DAA-1BE6-48F2-AC49-5CE0DBECC398
The last part of the number is random, so open Regedit and browse to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace, find a key starting with 0E270DAA-1BE6-48F2-AC49 and remove it.


text:
Q: Set table width for outlook when creating responsive email I have created a responsive email but I can not get outlook to recognize the width of 640 - it always expands too far. I have attempted many different options but nothing helps. Any help would be greatly appreciated.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width"/>

<title>Responsive Email Template</title>

SUPERHEADER

Email not displaying correctly?

View in your web browser.

Main MonaVie Title Here

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec accumsan pharetra ornare. In porttitor suscipit turpis eu tempor. Morbi interdum lacus eget nulla luctus, eu tincidunt lectus venenatis. In hac habitasse platea dictumst. Vestibulum eget neque lobortis lectus pharetra tempus sed vel velit. Proin ac risus sit amet ante mollis rhoncus. Sed aliquam urna id vehicula aliquam.

Sed ipsum sapien, tempus tincidunt dui semper, rhoncus rutrum est. Sed sapien sapien, mattis sodales lacinia non, luctus non massa. Nam id fermentum ligula. Ut convallis elit nibh, eget venenatis nibh ultrices ut. Cras non convallis nunc, ac feugiat dolor. Fusce mauris enim, lacinia ac lacus et, vehicula scelerisque lorem. Maecenas ullamcorper lectus sit amet ultricies gravida. Donec nec sapien lorem. Aliquam consequat tincidunt risus ac condimentum. Integer ultricies risus sed pretium scelerisque. Nam eleifend urna at metus bibendum feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean lobortis tempus ligula, nec euismod est rutrum ut.

Ut rhoncus tellus et dapibus vehicula. In convallis ligula et orci faucibus, ac lacinia mauris varius. Etiam congue ac ligula sed vehicula. Maecenas tincidunt nulla vel eros varius, non luctus velit hendrerit. Donec tempor facilisis rhoncus. Sed non mauris odio. Praesent tempus gravida tellus quis gravida. Duis blandit varius lorem, eu mattis neque. Sed tempor sit amet nisi in convallis. Nam non aliquam massa. Sed mollis feugiat nunc, eget rutrum sem sagittis id. In ipsum diam, iaculis viverra hendrerit a, convallis pretium ipsum. Sed ac varius sapien, a tempus ligula.

MONAVIE EVENTS

Winners Advance Meeting

January 17-18

 READ MORE ››

Winners Advance Meeting Febuary 20-24

 READ MORE ››

Ut rhoncus tellus et dapibus vehicula. In convallis ligula et orci faucibus.Ut rhoncus tellus et dapibus vehicula. In convallis ligula et orci faucib us.Ut rhoncus tellus et dapibus vehicula. In convallis ligula et orci faucibus.Ut rhoncus tellus et dapibus vehicula. In convallis ligula et orci faucibus.

VIEW EVENTS CALENDAR ››

The MORE Project

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec accumsan pharetra ornare. READ MORE.

4x4 Jeep Program

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec accumsan pharetra ornare. READ MORE.

Organizational Call

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec accumsan pharetra ornare. READ MORE.

VIRTUAL OFFICE   |
 ON THE MOVE   |
 MONAVIE EVENTS

To ensure that you continue to receive emails from MonaVie, please add MonaVieNews@monaviecorporate.com to your Address Book or Safe List.

This email was sent to you because you asked to receive updates from MonaVie. MonaVie emails are for informational purposes only; we will never send you an email asking for personal information. To unsubscribe from future MonaVie emails, click on the "Unsubscribe" link below.

Unsubscribe |
Privacy Policy |
MonaVie |
Contact Us

© MONAVIE LLC 2009–2014. ALL RIGHTS RESERVED

A: There are a bunch of things in here that I believe are causing you problems.

*

*Your responsive css should be formated like *[class="container-left] { ... }. They way your css is written right now will not work properly in most email clients.

*I see you have a bunch of colspans and rowspans, although I've heard this can work. I've never had much luck with it. I would recommend nesting tables in tables to get the results you're looking for.

*If consistency in email clients is of concern, I would avoid using padding and margin css. As well, all of your css styling (ie. font-family, font-size, etc..) should be inline. Not in the head. (I'm assuming you're not using an inliner tool.)

*I would recommend framing your HTML a bit differently. (I've adjusted some of your html to illustrate. I didn't clean it up very much so I apologize for the extra inline css and classes. It's also not tested. But this should help get you started. ) See here: http://codepen.io/anon/pen/dgrBA.


text:
Q: To copy the attached file in an email. I have been able to figure out how to get the name of the attached file in an email. i am just stuck after that. I don't know what to do after that, I have tried using os.path.join which just gives the path i want to download the folder to and joins it with the filename. Please suggest something. Thanks.
m = imaplib.IMAP4_SSL('outlook.office365.com',993)
m.login("UN", "PW")
m.select("Inbox")

typ, msgs = mail.search(None, '(SUBJECT "qwerty")')
msgs = msgs[0].split()

for emailid in msgs:
    resp, data = mail.fetch(emailid, "(RFC822)")

    email_body = data[0][1]
    m = email.message_from_bytes(email_body)

    if m.get_content_maintype() != 'multipart':
        continue

    for part in m.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue

        filename = part.get_filename()
        print(filename)

A: Following the sample from this link you can set the path when using the open function. (raw string by prefixing the string with r)
fp = open(r'c:\tmp\folder\' + filename, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
print '%s saved!' % filename


text:
Q: Apply hover overlay to Woocommerce archive listing I am trying to add a hover style to the woocommerce category images on the product page.
I've created the following code, which is working, however it's pretty poor as the overlays 'stick on' or overlay on each other, don't toggle properly etc. It seems the code isn't running quick enough
$('a.woocommerce-LoopProduct-link').on('mouseover', function() {
    $(this).parent('li').css({
        position: 'relative'
    });
    var img = $(this).children('img');
    $("

" + 'SHOP NOW >' + "

").css({
        "position": "absolute",
        "top": "0px",
        "left": "0px",
        "width": img.width(),
        "height": img.height(),
        "background-color": "rgba(0,0,0,.5)",
        "z-index": "10000",
        "vertical-align": "middle",
        "text-align": "center",
        "color": "#fff",
        "font-size": "1rem",
        "cursor": "pointer"
    }).on('mouseout', function() {
        $(this).fadeOut('fast', function() {
            $(this).remove();
        });
    }).insertAfter(this);
});

I would like to have this in CSS, however I cannot account for the variable image size and content of the overlay.

A: You dont have to do it in JavaScript position: absolute elements if set top left bottom right to zero takes the full width and height of their relative parents dynamic in this case. You dont even need an extra div for it when you can make use of pseudo elements.
Overlay using pure CSS affects the performance much less when compared to the script.

ul.test {
  list-style: none;
}

ul.test li {
  position: relative;
  display: inline-block;
}

ul.test li a img {
  display: block;
}

ul.test li:before {
  content: 'SHOP NOW';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  color: #fff;
  font-size: 1.5rem;
  transition: all 0.5s ease;
  cursor: pointer;
  /*To align the content*/
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;
  text-align: center;
}

ul.test li:hover::before {
  opacity: 1;
}


text:
Q: I don't know where to go next in Elden Ring! How do I find out? The story telling in FromSoft games is cryptic at best, but in Elden Ring, you seem to need to talk to the NPCs just to figure out where to go next. The issue is, a lot of them are hard to find and easy to miss, and even if you do find them, you gotta be paying attention to what they're saying - because they do not repeat themselves. It's at this point that I'm keeping a journal to keep track of what everyone has said, and where they are so that I know where I should be going.
Is there an easier way to manage this? An NPC I should talk to to find out where I need to go next? (I want to keep my first playthrough wiki-free if I can)
EDIT: to give an example, the Glintsone Key is a fairly important item that needs to be found in order to progress through the game. I can follow the trails from the sites of Grace, but it won't get me through the gate(s) to the Academy, nor point me to the Item(s) I need in order to progress. A couple of NPCs mention a Glintstone Key, but I was either not paying attention when they first mentioned it, or they didn't give any clues as to its whereabouts. I had to ask a friend for clues.
PS: I am playing offline, so I cannot rely on messages left by other players.

A: I think you may be missing the purpose of the game. Elden Ring is a true open world game. That means you can go anywhere and do anything. The answer to "where to go next?" is wherever you want!
Here's a few tips...

*

*If you want to advance the main story, you can follow the trails from Sites of Grace.

*There will be a little tower icon in sections of your map where you haven't found the map piece. Those indicate where you need to go to grab that map piece:

*You can use Square on the PlayStation to give a more detailed explanation on your quest items in inventory for a hint on where you need to go or what you need to do to activate them/advance the quest.

*If you really, really can't pick where to go, you can find or craft a Grace Mimic. When used, it'll show light pointing in a direction, like a Site of Grace. The only difference is that Grace Mimics point in a random direction each time one is dropped :)

A: When I am unsure which area to approach next, I reference Fextralife's Game Progress Route
There's a map on that page that has minimal spoilers and offers recommendations on appropriate levels and weapon upgrades to have for each area:

I generally prefer to just use the map rather than detailed guides.  If I get stuck, I make a note of it in my notebook to return later.

A: I just started the game as well and this is my first game of this type and I would say I'm at the same position. Sites of Grace show you where you should be going with that dust like line at the "camp", an NPC mentions this as well if i remember correctly. For example at the beginning of the game it will "lead" you to Stornmveil Castle but i strongly recommend to explore all areas before going there because you really need to get some gear and levels to be able to pass through. I embraced the whole exploration side of the game to progress organically...

A: It's as simple as this really: pay attention.
Everything you need to know where to go and what to do is in the game. As the other answers suggest, the Trails of Grace will lead you in the direction of the main plot line. However when it comes to finding an item or npc relevant to your quest; whether it be the main quest or a sub quest, everything you need is in the game.
As I provided in my example, I did not know where to find the Glintstone Key to enter the Academy tower. However there is an Item that does point the location out - the "Meeting Place Map" which does indicate the area you need to look. In my first playthrough, I picked up the item, but did not pay attention and missed the tool tip to investigate this item.

A: And to answer your exact question, you would have found a corpse near the Raya Lucaria gate. If you loot the corpse it will give you a drawing with the description, "The map was received from a person from Raya Lucaria. The marked Location must be important"
And if you can find the location shown in the drawing you will get your Glintstone key.
And for the general question, you can always follow the sites of grace. For example, in this case, by strictly following the sites of grace you directly obtain a map indicating the location of Glintstone key. And as for NPC quests, you can keep journals, but it's ok not to keep it. You will miss things, but usually if you are going back and forth and talking to people again, you will progress through them. For example if you had talked to Rya in the lake gazebo, and you had forgotten about her, just if you follow the sites of grace, you will arrive at the next location after Raya Lucaria being Volcano manor. And she will be there.
So don't worry much about missing things. You can keep a journal but don't stress. It's meant to be surprising when you discover new things by accident. It's not meant to be followed point by point with a through exploration.


text:
Q: Amazon RDS PostgreSQL Performance input/output I am facing this complex challenge with an RDS PostgreSQL instance. I am almost out of any idea how to handle it. I am launching an app (React+Go+PostreSQL) for which I expect to have around 250-300 users simultaneously making the same API GET request for how long the users wish to use it.
It is a questionnaire kind of app and users will be able to retrieve one question from the database and answer it, the server will save the answer in the DB, and then the user will be able to press next to fetch the next question. I tested my API endpoint with k6 using 500 virtual users for 2 minutes and the database returns dial: i/o timeout or even connection rejected sometimes, usually when it reaches 6000 requests and I get around 93% success. I tried to fine-tune the rds instance with tcp_keep_alive parameters but without any luck, I still cannot manage to get 100% of the request pass. I also tried to increase the general storage from 20gb min to 100gb in rds and switch from the free db.t3.micro to db.t3.medium size.
Any hint would be much appreciated. It should be possible for a normal golang server with postgres to handle this requests at the same time, shouldn't it? It is just a regular select * from x where y statement.
EDIT (CODE SAMPLE):
I use a dependency injection pattern and so I have only one instance of the DB passed to all the other repositories including the API package. The db repo looks like this:
func NewRepository() (DBRepository, error) {
  dbname := getenv("POSTGRES_DATABASE", "")
  username := getenv("POSTGRES_ROOT_USERNAME", "")
  password := getenv("POSTGRES_ROOT_PASSWORD", "")
  host := getenv("POSTGRES_HOST", "")
  port := getenv("POSTGRES_PORT", "")

  dsn := fmt.Sprintf("host=%s user=%s password=%s"+
    " dbname=%s port=%s sslmode=disable
    TimeZone=Europe/Bucharest", host, username, password, dbname,
    port)
  db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
  if err != nil {
    return nil, err
  }

  if err != nil {
    return nil, err
  }

  db.AutoMigrate(
   //migrate tables are here
  )

  return &dbRepository{
    db: db,
  }, nil

}
Currently the parameters use in RDS for TCP keepalive are:
tcp_keepalives_count       30
tcp_keepalives_idle        1000
tcp_keepalives_interval    1000
and I also tried with different numbers.
The query I am doing is a simple .Find() statement from gorm package but it seems like this is not the issue since it gets blocked whenever hits the first query/connection with the db. There are 2 query executed in this endpoint I am testing but it gets stuck on the first. If more info is needed I will update but this issue it gets so frustrating.
My k6 test if the following:
import http from 'k6/http';
import { check } from 'k6';
import { sleep } from 'k6';

export const options = {
  insecureSkipTLSVerify: true,
  stages: [
    { target: 225, duration: '2m' },
  ],
};

const access_tokens = []

let random_token = access_tokens[Math.floor(Math.random()*access_tokens.length)];

const params = {
    headers: {'Authorization': `Bearer ${random_token}`}
};

export default function () {
  let res =  http.get('endpoint here', params);
  check(res, {'Message': (r)=> r.status === 202});
  sleep(1);
}

The DB tables are also indexed and tested with the explain statement.


text:
Q: Finding the derivative of an absolute value This one I just don't know how to derive.
$\ln\|x^4\cos x\|$
I know the derivative of $\ln\ x$, is just $\frac{1}{x}$ . It is the absolute value that throws me off. My question is, does the absolute value stay as is or does it disappear?

*

*$\frac{1}{|x^4\cos x|}$

*$\frac{1}{x^4\cos x}$
Or is there an extra step that I should preform?

A: HINT:
$$\frac{d|x|}{dx}=\text{sgn}(x)$$
for $x\ne0$.  Now, use the chain rule, but make sure that $x^4 \cos x\ne0$
SPOILER ALERT: SCROLL OVER SHADED AREA TO REVEAL ANSWER

Let $y=x^4\cos x$.  Then, we have $$\frac{d}{dx}\log|x^4\cos x|=\frac{d\log |y|}{d|y|}\text{sgn(y)}\frac{dy}{dx}=\frac{1}{|x^4\cos x|}\text{sgn}(x^4\cos x)(4x^3\cos x-x^4\sin x)=\frac{1}{x^4\cos x}(4x^3\cos x-x^4\sin x)$$Another way to approach the problem is to split it into two parts, (i) $x^4\cos x>0$, and (ii) $x^4\cos x<0$.  On Part (i), we have $$\frac{d}{dx}\log|x^4\cos x|=\frac{d}{dx}\log(x^4\cos x)=\frac{1}{x^4\cos x}(4x^3\cos x-x^4\sin x)$$On Part (ii), we have $$\frac{d}{dx}\log|x^4\cos x|=\frac{d}{dx}\log(-x^4\cos x)=\frac{1}{-x^4\cos x}(-4x^3\cos x+x^4\sin x)=\frac{1}{x^4\cos x}(4x^3\cos x-x^4\sin x)$$as expected!

A: To elaborate on Dr. MV's answer, we can find the derivative of the absolute value function by noting $$ |x|=\sqrt{x^2}$$ and then using the chain rule. The proof goes:
$$ \frac d{dx} \sqrt{x^2}=\frac1{2\sqrt{x^2}}\cdot \frac{d}{dx}x^2=\frac{2x}{2\sqrt{x^2}}=\frac{x}{|x|}$$
Now just note that $\frac{x}{|x|}=-1$ if $x<0$ and $\frac{x}{|x|}=1$ for $x>0$.

A: You can actually show that the derivative of $\ln{|x|}$ is $\frac{1}{x}$ for all $x\ne 0$. For $x>0$ this should be clear; for $x<0$, we know $|x| = -x$, and hence we want to calculate
$$\frac{d}{dx}(\ln(-x)) = \frac{1}{-x}(-1) = \frac{1}{x}. $$
Once you know that, then you can proceed with the chain rule, as usual.

A: These kinds of problems can be solved using a simple rule for derivatives of logarithms of absolute functions.

Theorem: For any (univariate) differentiable function $f$ we have:
$$\frac{d}{dx} \ln |f(x)| = \frac{f'(x)}{f(x)}
\quad \quad \quad \text{for } f(x) \neq 0.$$
Proof: Since $f$ is differentiable it is continuous, and so, for any point $x$ with $f(x) \neq 0$ there exists a neighbourhood $\mathcal{N}(x)$ where all values of the function have the same sign as $f(x)$ --- i.e., we have: $$\text{sgn} f(x) = \text{sgn} (y) \quad \quad \quad \text{for all } y \in \mathcal{N}(x).$$  Thus, if $f(x) > 0$ then $|f(x)| = f(x)$ over all points in $\mathcal{N}(x)$, and so we have:  $$\frac{d}{dx} \ln |f(x)| = \frac{d}{dx} \ln f(x) = \frac{f'(x)}{f(x)}$$  Contrarily, if $f(x) < 0$ then $|f(x)| = -f(x)$ over all points in $\mathcal{N}(x)$, and so we have:  $$\ \ \frac{d}{dx} \ln |f(x)| = \frac{d}{dx} \ln (-f(x)) = \frac{-f'(x)}{-f(x)} = \frac{f'(x)}{f(x)}. \ \ \blacksquare$$

Applying this general rule to the case where $f(x) = x^4 \cos x$ we have:
$$\frac{d}{dx} \ln |f(x)| = \frac{4 \cos x - x \sin x}{x \cos x}
\quad \quad \quad \text{for all } x \neq \cdots, - \frac{3 \pi}{2}, -\frac{\pi}{2}, 0,  \frac{\pi}{2}, \frac{3 \pi}{2}, \cdots.$$


text:
Q: Finite intersection of finite unions of sets (interchanging) I am aware of this question and I want to know if that identity may be written like this $$\bigcap_{k=1}^{n} \left( \bigcup_{\ell=1}^{m_k} C_{k,\ell} \right) = \bigcup_{\ell_1 =1}^{m_1} \bigcup_{\ell_2 =1}^{m_2} \dots \bigcup_{\ell_n =1}^{m_n} \left( \bigcap_{k=1}^{n} C_{k,\ell_k} \right)$$ Here is my attempt for proving it:
Let $ \ x \in \bigcap_{k=1}^{n} \left( \bigcup_{\ell=1}^{m_k} C_{k,\ell} \right)$. Then, for all $ \ k \in \{ 1,...,n \}$, there exists $ \ \ell \in \{ 1,...,m_k \}$, which depends on $k$, such that $ \ x \in C_{k, \ell} \, $. We can say $\ell_1$ for $ \ k=1$, $\ell_2$ for $ \ k=2$, ..., $\ell_n$ for $ \ k=n$. Hence $ \ x \in \bigcap_{k=1}^{n} C_{k,\ell_k} \subset \bigcup_{\ell_1 =1}^{m_1} \bigcup_{\ell_2 =1}^{m_2} \dots \bigcup_{\ell_n =1}^{m_n} \left( \bigcap_{k=1}^{n} C_{k,\ell_k} \right)$.
For the other hand, let $ \ x \in \bigcup_{\ell_1 =1}^{m_1} \bigcup_{\ell_2 =1}^{m_2} \dots \bigcup_{\ell_n =1}^{m_n} \left( \bigcap_{k=1}^{n} C_{k,\ell_k} \right)$. Then there exists $ \ \ell_1 \in \{ 1,...,m_1 \}$, $\ell_2 \in \{ 1,...,m_2 \}$, ..., $\ell_n \in \{ 1,...,m_n \} \ $ such that $ \ x \in \bigcap_{k=1}^{n} C_{k,\ell_k}$. Rewriting, we have that, for all $ \ k \in \{ 1,...,n \}$, there exists $ \ \ell_k \in \{ 1,...,m_k \} \ $ such that $ \ x \in \bigcap_{j=1}^{n} C_{j,\ell_j} \subset C_{k,\ell_k}$. Again, for all $ \ k \in \{ 1,...,n \}$, we have $ \ x \in \bigcup_{\ell_k = 1}^{m_k} C_{k,\ell_k} = \bigcup_{\ell = 1}^{m_k} C_{k,\ell} \, $. Finally, we arrive at $ \ x \in \bigcap_{k=1}^{n} \left( \bigcup_{\ell=1}^{m_k} C_{k,\ell} \right)$.
Is my proof correct?
Thanks in advance.

A: The formula is correct and I have a rather direct approach for the proof. Have a look at the attached photo.


text:
Q: Table Sections aren't being displayed correctly in a Table View Controller in Swift I have two sections declared in my Storyboard on my TableViewController. In the corresponding swift class, I have:
     override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 2
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 6
}

because I have 2 sections and 6 rows. However, this is giving me continuous Index out of bounds errors which is annoying because the sections are being declared! Am I doing anything wrong at all?
Thanks in advance.
UPDATE
Okay so this is my table view controller:

What I've written in my cellForRow... is:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Identifier", forIndexPath: indexPath)

    // Configure the cell...
    cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"

    return cell

}

I am new to Swift so I'm not sure entirely if this is correct, but basically what I get (with the cellForRow commented out is only the first section.)
Does this help?

A: If you have a different numbers of rows per section you need to separate them, you can't return the total number:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case 0: return 5
    case 1: return 1
    default: return 0
    }
}

In the inspector window, if you have static content try to set it to dynamic, you need only one cell prototype.

A: Answer
Hi all, just in case anyone is interested in the answer:
In Swift, if you are using static cells, you're not meant to have a numberOfSectionsInTableView or numberOfRowsInSection as these are needed only if you are using a data source. If you want to use static cells, be sure to remove these two methods.
Source: https://www.raywenderlich.com/113394/storyboards-tutorial-in-ios-9-part-2
Hope this helps!

A: Here's how I set up my table view Smith multiple rows in multiple sections:
1) At the top of the ViewController class, create this struct and below it, create the variable
struct Objects {
    var sectionName : String!
    var sectionObjects: [String]!
}

var objectsArray = [Objects]()

2) In ViewDidLoad, set the variable
objectsArray = [Objects(sectionName: "Find People", sectionObjects: ["Facebook", "Twitter", "Contacts"]), Objects(sectionName: "Your Account", sectionObjects: ["Edit Info", "Delete Account"]), Objects(sectionName: "Support", sectionObjects: ["Help", "Report a Problem", "Contact Us"]), Objects(sectionName: "App Info", sectionObjects: ["About", "Open Source Libraries", "Privacy Policy",  "Our Twitter", "Our Facebook"])]

3) For numberOfSectionsInTableView
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return objectsArray.count

}

4) For numberOfRowsInSection
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return objectsArray[section].sectionObjects.count

}

5) For cellForRowAtIndexPath
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text = objectsArray[indexPath.section].sectionObjects[indexPath.row]

    return cell
}

6) For setting the titleForHeaderInSection
 override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    return objectsArray[section].sectionName

}

7) In order for any actions to happen when you the user taps on the cell, you must call didSelectRowAtIndexPath -> In my case, I have 4 sections (headers), so I must create 4 switches (cases start at 0, not 1). Then, for each section, I must set a case for each row in each section. Within that case, you can call whatever you want -- for example, you can perform a segue to another viewController. The default essentially refers to the else in an if else statement...as in, if all else fails, display an error to the user that something didn't work right. You can use the built in alertView, but I like to use SCLAlertView available on GitHub!
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if reachabilityStatus == kNOTREACHABLE {

        self.displayError("No Internet Connection", message: "Please connect to the internet before continuing")

    } else {

        switch(indexPath.section) {

        case 0:

            switch(indexPath.row) {

            case 0:

                // Find People through facebook -> test below

                print("Connect with FB")

                return

            case 1:

                // Find People through twitter -> test below

                print("Connect with Twitter")

                return

            case 2:

                // Find People through contacts -> test below

                print("Connect with Contacts")

                return

            default:

                self.displayError("Something Went Wrong", message: "We're sorry, it seems like we can't open that for you. Please try again.")

                return

            }

        case 1:

            switch(indexPath.row) {

            case 0:

                // Edit Account -> test below

                self.performSegueWithIdentifier("editProfileSegue", sender: self)

                return

            case 1:

                // Delete Account -> test below

                print("Delete Account")

                return

            default:

                self.displayError("Something Went Wrong", message: "We're sorry, it seems like we can't open that for you. Please try again.")

                return

            }

        case 2:

            switch(indexPath.row) {

            case 0:

                // Help -> test below

                print("Help")

                return

            case 1:

                // Report a Problem -> test below

                print("Report Problem")

                return

            case 2:

                // Contact Us -> test below

                print("Contact Us")

                return

            default:

                self.displayError("Something Went Wrong", message: "We're sorry, it seems like we can't open that for you. Please try again.")

                return

            }

        case 3:

            switch(indexPath.row) {

            case 0:

                // About App -> test below

                print("About App")

                return

            case 1:

                // Open Source Libraries -> test below

                print("Open Source Libraries")

                return

            case 2:

                // Privacy Policy -> test below

                print("Privacy Policy")

                return

            case 3:

                // Our Twitter -> Test Below

                print("Our Twitter")

            case 4:

                // Our Facebook -> Test Below

                print("Our Facebook")

                return

            default:

               self.displayError("Something Went Wrong", message: "We're sorry, it seems like we can't open that for you. Please try again.")

                return

            }

        default:

            self.displayError("Something Went Wrong", message: "We're sorry, it seems like we can't open that for you. Please try again.")

            print("last error")

            return

        } // close section switch

    }

}

In your case, you only have 3 sections, so just play around with the code to see what works
Let me know if you need any help!


text:
Q: How to implement xsd:decimal data type for Post request XML I seem to be running into some issues while uploading some data,
for whatever reason the system is being picky and requiring me to upload
integers for column 5(row[4] values), so far I have researched various methods
including rewriting the whole xml document with Beautiful Soup however
it seems that the most effective way would be to use xsd:decimal type
but I'm a bit of a novice when it comes to schemas.
Can someone please assist?
I just need to know where do I put the schema in the xml string
XML string:
""<?xml version='1.0' encoding='UTF-8'?>

<call method="importStandardData" callerName="Import Call">
<importDataOptions planOrActuals="Actuals" allowParallel="false" moveBPtr="false" replaceExisting="true"
useMappings="true" /><version name="Actuals" isDefault="False" />
<rowData><header>Account|Level|Split Label|Projects|{}</header><rows>"""
""

Code:
for index,x in df3.iterrows():
#print("Account,Level,Split,Project,Date")
Main="""<row>{}|{}|{}|{}|{}")</row>""".format(x[0],x[1],x[2],x[3],x[4])
#print("This is Project: ",x[3])
Main_parts+=Main

xml=Start+Main_parts+End

def Upload(xml):
soup = BeautifulSoup(xml,"xml")
tree = ET.ElementTree(ET.fromstring(soup.prettify()))
xml2 = bytes(soup.prettify(), encoding = 'utf-8')
#print(xml)
root = etree.XML(xml2)

New_xml=tree
headers = {'Content-Type': 'application/xml'}

req=requests.post('https://api.System.com/api/v20',xml2,headers=headers)
return req.text

A: Update: I have the solution, the issue was in this line of code xml2 = bytes(soup.prettify(), encoding = 'utf-8')) it actually generated Html characters for the end of each row ie '/n', so for the Total column since it was at the end of the row it somehow concatenated the Totals with the XML version of /n which means it was '100.000 #xmlversionof /n' , I ran into another issue with the use of & in the XML file but solved it by doing a str.replace('&','&amp') for all values in the Dataframe that was being used to generate the XML. Will post updated code soon.


text:
Q: Open Search Server set timeout I am using the web crawler in OpenSearchServer and while crawling, it gets stuck during the Extracting url list action. It also gets stuck at times when finishing a session. Is there anyway to set a time limit or a timeout so it aborts if something takes too long to run?

A: I suppose you are using the default web template. In this case each time a crawl session ends, OpenSearchServer build the autocompletion index, even if you abort the session.
To avoid that, go in the panel "/Crawler/Web/Crawl process" and select the blank job.


text:
Q: Webmin Cluster Copy Protocol Just toying with a clustered server farm for fun (as you do) and experimenting with Webmin and its 'clustered' modules.
It has a feature that can copy files from one server to another on a repeating basis. Does this feature/module use cron jobs and what protocol does it use to copy the files?
I have searched all about the net and yet I cannot find any decent documentation on webmin or its features. Is it just poorly documented or am I missing something?

A: My guess is that it uses rsync with cron, which is the canonical way of handling this type of replication. I would be very surprised if they used anything else.

A: I have recently discovered that it uses it's OWN protocol using a specific port. A few above 10000 if I remember correctly.


text:
Q: Add spacing between letters in environment % Defines the rSection environment for the large sections within the CV
\newenvironment{rSection}[1]{ % 1 input argument - section name
  \sectionskip
  \hrule % Horizontal line
  \MakeUppercase{\bf #1} % Section title <----
  \sectionlineskip
  \begin{list}{}{ % List for each individual item in the section
    \setlength{\leftmargin}{0em} % Margin within the section
  }
  \item[]
}{
  \end{list}
}

I would like to add some spacing between the letters of the section title. I have tried {\addfontfeature{LetterSpace=10.0}\MakeUppercase{\bf #1}} but this didn't work. What should I do? I am using XelaTex.
I have a lot of trouble finding documentation for stuff like this. Where should I be looking?
I have tried the solution at XeLaTeX: Space between letters but it didn't work.

A: You can't use \addfontfeatures on a font that has not been explicitly loaded.
\documentclass{article}
\usepackage{fontspec}

\setmainfont{Latin Modern Roman}

\NewDocumentCommand{\spaceduppercase}{m}{%
  {\addfontfeatures{LetterSpace=10}\MakeUppercase{#1}}%
}

\begin{document}

\spaceduppercase{Test} TEST

\textbf{\spaceduppercase{Test}} \textbf{TEST}

\end{document}

So change your (wrong) \MakeUppercase{\bf #1} into
\textbf{\spaceduppercase{#1}}

A: Are you restricted to using XeLaTeX? If you were free to use LuaLaTeX, you could load either the microtype package or the letterspace package (which is, basically, a much stripped down version of microtype). If using LuaLaTeX is feasible, just change
\MakeUppercase{\bf #1}

to
\textls*{\MakeUppercase{\bfseries #1}}

(Aside: \bf is deprecated for LaTeX documents. Use either {\bfseries ...} or \textbf{...}.)
See section 7 of the user guide of the microtype package for more information on \textls and how to change the amount of letterspacing (aka tracking).