text:
Q: Angular 2 - Get removed character from input Is there anyway to detect removed character from a text using ngModel in Angular 2 ?
I want something like:
Original text: @Hello World !
Modified text : Hello World !
Console.log
Removed character: '@'

I've found a cool example on Javascript with Jquery by Arie Xiao below:
https://stackoverflow.com/a/17005983/5668956
But I wonder if I can use another thing beside Jquery, as I find that Jquery is pretty hard to implement in Angular 2

A: I would suggest a Forms controller for acting on changes on the input field. The snippet displays the character add or deleted from the input field.
Check out my  Plunker to see the code running.

@Component({
  selector: 'app-root',
  template: `
    <input type="text" [formControl]="form"  class="form-control" >
    <h3 *ngIf="initial">
      Text <span [style.color]="textadd ? 'green' : 'red'" > {{textadd ? "add" : "removed" }} </span>: {{change}}
    </h3>
  `,
})
export class App {
  form;
  textadd;
  text = "@Hello World!";
  initial = false;
  change;
  ngOnInit() {
    this.form = new FormControl({ value: this.text, disabled: false });

    this.form.valueChanges.subscribe(val => {
      let change;
      if (val.length > this.text.length) {
        change = val;
        for (let variable of this.text) {
          change = change.replace(variable, '');
          this.textadd = true;
        }
      } else {
        change = this.text;
        for (let variable of val) {
          change = change.replace(variable, '');
          this.textadd = false;
        }
      }
      this.change = change;
      this.text = val;
      this.initial = true;
    });
  }
}


text:
Q: How to finish 'Retrieve the GECK for Arroyo' quest?
 I just got it from Vault 13 by helping deathclaws. I found Hakunin
 dying and telling about the raid but I don't get xp and quest isn't
 marked as done. Is there something wrong or do I need to do more
 stuff?

A: You need to rescue the village as you can't very well give them the GECK if they aren't there.

A: This happens when you either locate the GECK, or if time runs out. You need to rescue your tribe at this point in order to complete the main quest.
Hint 1:

 To rescue your tribe, start by going to San Francisco.

Hint 2:

 San Francisco is located in the bottom left corner of the world map.

Hint 3:

 In San Francisco, you must find a way to get the tanker (large boat) operational.

Hint 4:

 This requires fuel, a FOB, and a NavCom part. Once the tanker is operational, you can travel to a place where you can rescue your tribe.

Hint 5:

 You can only go to this place once, and once there you cannot leave until you've finished rescuing your tribe. Prepare yourself before going.

Major Plot spoilers:

 Rescuing your tribe and escaping The Enclave will complete the game and display the final cinematic showing the outcomes of the different locations in Fallout 2 based on what quests you did or did not do.

 You can keep playing the game as long as you want after completing this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I use the 1.8 inch TFT LCD SD slot for other purposes other than displaying images on the display? Can I use the 1.8 inch TFT LCD SD slot for other purposes other than displaying images on the display? For example, storing text files on that SD card (that's on the display's SD slot)? Can I use that display SD card slot like a normal SD card slot (no images, no bitmaps). Something like this:

A: the display uses I2C communication. the SD card uses SPI communication. they are two independent devices on the module. the SPI pins for the SD module are on the left side on the picture.


text:
Q: Pharo FileSystem: setUp of SUnit test which uses a file I want to write a SUnit test which uses a file with the Pharo 4.0 FileSystem.
I want to write a file and then later read it.
Something like this

  fname := 'TabularTestExport1.xlsx'.
  (FileLocator temp / fname ) delete.
  TabularXSLXExport workbook: myWorkbook fileName: (FileLocator temp / fname ).

Questions

*

*temp directory What is the method to use for using a temporary file in a platform independant way. FileLocator temp or FileLocator tempDirectory is not implemented.

*deleting an existing test file How do I ensure that a file is deleted? I.e. How do I avoid a walkback in case the file does not exist.

*Alternatively everything could be done in the memory: 1. creation of test file, 2. exporting test file, 3. Importing test file back

A: For tests, unless you have a real big archive, is better to do things in memory.
FileSystem provides you a way to do it, you just need to do:
fs := FileSystem memory.

It will give you a compatible API so you can make your tests.
If you want a file and not a directory, you can do:
file := FileSystem memory / 'myFile'.

EDIT: I forget a couple of things:

*

*FileLocator temp is implemented and should work fine for you. Why you say is not implemented? Are you not finding it for some reason, maybe?

*myFileReference ensureDelete will... well, ensure your file is deleted :)


text:
Q: How to find actual path of the image in php I want to find real path of the image. Simply I want to store base64 of the image but not the image on the server. simply I want to use this code.
$image = file_get_content(filepath);
$encoded = base64_encode($image);

in file path I just want to pass the file path. How can I do this. Or any other method to store base64 only not image on the server using php.

A: Here's the thing :
If you're using PHP to upload an image to the server and want to store the base64 version of it :
HTML :
<input type="file" name="myimage">

PHP :
if(isset($_FILES["myimage"])) {

    //file has been submitted, you might want to check for errors

    $image = file_get_contents($_FILES["myimage"]["tmp_name"]);
    $encoded = base64_encode($image);

    //store the encoded version
}

If you don't intend to use PHP to upload images, and want to store immediately base64 version of an image, you can't do that using PHP as it doesn't make sense at all (PHP has no access whatsoever to the user's file system, and thank God it doesn't). Instead, you'd need to do some Javascript.
Please remember that this snippet is for example purpose, you'd have to check the upload for errors and stuff if you're willing to use it in a production environment.

A: If you upload a file via a <input name="picture" /> tag you can get the file path with $_FILES["picture"]["tmp_name"].


text:
Q: Rails turbolink js issue one click dropdown js not load Rails js load issue Turbolinks gem.
Navbar Dropdown one click not open after page refresh or second click to open dropdown how to solve this isssue. and also kuse turbolinks gem and boostrap gem.

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="true" aria-label="Toggle navigation">

</button>

  <% if current_user.present? %>

     <% Tabs::NAVBAR.each do|tab_key, tab|%>
       <% if tab[:type].eql?('dropdown_tab') %>
         <li class="nav-item dropdown <%= active_navbar(tab_key) %>">
           <% if current_user.projects.present? %>
              <%= link_to tab[:title], fetch_route(tab_key), class: 'nav-link dropdown-toggle', id: 'myTab', data: { toggle: "dropdown" }%>
          <%else%>
          <%end%>

          <% dropdown_options(tab_key).each do|option| %>
            <%= link_to option[:title], option[:path], class:'dropdown-item' %>
          <% end %>

       <% else %>
        <li class="nav-item <%= active_navbar(tab_key) %>">
         <%= link_to tab[:title], fetch_route(tab_key), class: 'nav-link'%>

     <% end %>
    <% end %>

    Profile

<%= link_to " Profile", edit_user_registration_path, class: "dropdown-item" %>

<%= link_to " Sign Out", destroy_user_session_path, method: :delete, class: "dropdown-item" %>

<%end%>

A: I think you need to reinitialize the elements that requires bootstrap js when the event turbolinks:load is fired, check this question Rails Bootstrap 4 with Turbolinks
It's about the tooltip js, but the same applies for any element that requires js initialization.
Something like:
$(document).on('turbolinks:load', function() {
  $('.dropdown-toggle').dropdown()
})

A: May be you need Dropdown.parseDocument(element) or Bulma(element).dropdown() in turbolinks:load event when used @vizuaalog/bulmajs.
// global `bulmaOptions` object should be defined before BulmaJS has loaded
// disable autoParse to prevent repeated `turbolinks:load` event
window.bulmaOptions = {
  autoParseDocument: false
}
// import Dropdown from '@vizuaalog/bulmajs/src/plugins/dropdown';
import Bulma from "@vizuaalog/bulmajs";

document.addEventListener("turbolinks:load", () => {
  Bulma.parseDocument();
  // Dropdown.parseDocument(document.getElementsByTagName('body')[0]);

  Array.from(document.querySelectorAll('.dropdown')).forEach(element => {
    Bulma(element).dropdown();
  });
});

Note: bulmaOptions.autoParseDocument = false


text:
Q: Create filtered JSON form exising JSON using JavaScript I got below JSON data:
[
{
    "ric": "ADAG.DE",
    "sedol": "5653487",
    "quantity": 107479,
    "activityQuantity": null,
    "businessDate": 20141023
},
{
    "ric": "ADAG.DE",
    "sedol": "BBJPFY1",
    "quantity": 2758,
    "activityQuantity": null,
    "businessDate": 20141023
}]

And from above JSON data I have to create below JSON data with ric as Key and businessDate and quantity as values below using JavaScript:
[
{
    "key": "ADAG.DE",
    "values": [
        [
            20141023,
            107479
        ],
        [
            20141023,
            2758
        ]
    ]
}]

Would you please help me. This question is not duplicate as I searched all where I see it has only one key with one value where I have to create one key with set of two dimensional array value JSON.


text:
Q: Масштабируемый TextView Помогите пожалуйста настроить масштабирование TextView.
Всё, что касается параметров app:autoSizeTextType="uniform" и android:breakStrategy="simple" я перепробовал. Масштаб меняется, но не для всех случаев. Мне нужно, чтобы масштабирование текста работало для слов любой длины, но если я вставляю в TextView длинное слово, то android начинает глупые переносы слов на новую строку.
Например:
автоматизац
ия
Пример моего кода:
<TextView
    android:id="@+id/textViewSize"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Автоматизация"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="2sp"
    app:autoSizeMaxTextSize="60sp"
    app:autoSizeStepGranularity="1sp"
    android:breakStrategy="simple"
    android:maxLines="10"
    />

Как я понял, если android видит, что ему можно разместить текст на 10 линий - android:maxLines="10", то он будет увеличивать масштаб текста до самого большого app:autoSizeMaxTextSize="60sp", и ему без разницы, что слово перенеслось на новую строку. Почему android не делает выбор в пользу размера слова, чтобы оно вошло в строку без переносов? Было бы удобно, если автомасштабирование чувствовало, что пора прекратить увеличивать размер текста, так как слово сейчас начнет переносится на новую строку и остановилось на размере например 50sp.
Параметр android:hyphenationFrequency="full" тоже не срабатывает. По сути данный параметр должен переносить слова на новую строку по слогам, но он не работает даже на английском тексте.
Моё TextView в разных случаях может показывать разное количество текста, от одного слова до абзаца, поэтому я указал android:maxLines="10"

A: Нашел решение самостоятельно. Возможно для кого-то будет полезно.
@RequiresApi(api = Build.VERSION_CODES.O)
public class MainActivity extends AppCompatActivity {

private TextView textView;
float sizeWidthTextView;
int textMaxAutoSize = 50;
StringBuilder singleWordBuilder = new StringBuilder();

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.textViewSize);
}

@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
protected void onResume() {
    super.onResume();

    //Определяем ширину экрана в пикселях
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int widthDisplay = size.x;
    textView.setTextSize(textMaxAutoSize);

    //Определяем ширину TextView в пикселях
    sizeWidthTextView = textView.getLayoutParams().width;

    //Если ширина TextView задана как wrap_content либо match_parent, то будут возвращены значения -1 и -2
    //нас это не устраивает и мы присваиваем переменной ширину всего дисплея.
    if(sizeWidthTextView == -1 || sizeWidthTextView == -2) {
        sizeWidthTextView = widthDisplay;
    }

    //Считаем длину каждого слова в пикселях и уменьшаем размер шрифта так, чтобы слово вмещалось в ширину TextView
    for(int i = 0; i < textView.getText().length(); i++) {
        if (textView.getText().charAt(i) != ' ') {
            singleWordBuilder.append(textView.getText().charAt(i));
            String singleWord = String.valueOf(singleWordBuilder);
            float sizeWord = textView.getPaint().measureText(singleWord);
            //Уменьшаем максимальный размер шрифта до тех пор пока слово не вместится в ширину TextView
            while (sizeWidthTextView  < sizeWord) {
                textMaxAutoSize--;
                textView.setTextSize(textMaxAutoSize);
                sizeWord = textView.getPaint().measureText(singleWord);
            }
        } else {
            singleWordBuilder.setLength(0);
        }
    }
}

}
<TextView
    android:id="@+id/textViewSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:breakStrategy="simple"
    android:maxLines="10"
    android:gravity="center"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:text="Авто авто Автоматизационный авто"/>


text:
Q: Do you use Jest and React Testing Library for automated tests on your react-admin app? Do you use:

*

*Jest

*React Testing Library

I'm having a hard time figuring out what to test and how to test it. react-admin has so much based in redux and contexts that it's hard to mock those things so you're focusing on just a single component instead of testing react-admin itself.


text:
Q: Swift Firebase load array of arrays I am trying to load an array of arrays with Firebase and would appreciate any help on how to do so. Thanks! Picture is of database.

A: You need to observe defense then inside the callback
self.ref.child("defense").observeSingleEvent(of: .value, with: { snap in
   let res = snap.value as! [String:[String:Int]]
   let all = Array(res.values).map { Array($0.values) } // [[-1,-1,-1],[...]]
})


text:
Q: android showing text within a image In project I need to show first text within the image (Q letter image) and second text below the Q letter as show in the picture.  How can I place the text as shown in the image?

The Q icon image can be shown on map as like this:

A: You can use a TextView and set its background property to your image.
<TextView
    android:id="@+id/q_text
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/q_placeholder_text"
    android:background="@drawable/q_drawable" />

Or even better, add both the ImageView and the TextView to a FrameLayout.  (The TextView and ImageView order matters)
<FrameLayout
     android:id="@+id/q_layout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content">

     <ImageView
          android:id="@+id/q_image"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:src="@drawable/q_drawable />
     <TextView
          android:id="@+id/q_text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:text="@string/q_placeholder_text />

</FrameLayout>

A: To achieve this:
1. Create a Linear layout which have white background.
2. Use LinearLayout in side above layout and set q image as back ground. this q image is png image.
2. Use Textview in side linear layout and set text what you want with new line.
I hope, it will work.


text:
Q: Can FD_ISSET be called with a descriptor that was not added to the select set? I'm debugging a select loop that normally works OK but dies with segmentation fault under heavy load. I've figured out that the program is sometimes invoking FD_ISSET() for a (correct) descriptor that was not added to the select set. Like in a following snippet:
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

void die(const char* msg)
{
    fprintf(stderr, "fatal %s", msg);
    exit(1);
}

int main(void)
{
    FILE* file = fopen("/tmp/test", "r");
    if (file == NULL)
        die("fopen");

    int file_fd = fileno(file);
    fd_set read_fds;
    int max_fd = 0;

    FD_ZERO(&read_fds);
    // Only stdin is added to read_fds.
    FD_SET(0, &read_fds);

    if (select(max_fd + 1, &read_fds, NULL, NULL, NULL) < 0)
        die("select");
    if (FD_ISSET(0, &read_fds))
        printf("Can read from 0");
    // !!! Here FD_ISSET is called with a valid descriptor that was
    // not added to read_fds.
    if (FD_ISSET(file_fd, &read_fds))
        printf("Can read from file_fd");
    return 0;
}

It is obvious that the check marked with !!! should never return true, but is it possible that it can be the cause of the SEGFAULT? When I run this snippet under valgrind, no errors are reported, but when I run my load test under valgrind I'm ocasionnaly seing errors like:
==25513== Syscall param select(writefds) points to uninitialised byte(s)
==25513==    at 0x435DD2D: ___newselect_nocancel (syscall-template.S:82)

A: FD_ISSET() tests to see if a file descriptor is a part of the set read_fds. This means that FD_ISSET should not cause the segmentation fault.
Try checking for errno value set prior to calling the FD_ISSET. The select should be causing the segfault.
Also check that the file_fd value isn't greater than FD_MAX.


text:
Q: Error handling for AWS CLI in bash script for duplicate security group I am creating a security group using AWS CLI using Bash script. I want to implement an error handling in the script for example if I create a security group with the same name I can handle it with if-else or any other iteration.
read -p "Enter the Security group name :" group_name
read -p "Enter the Security group description :" description
sgGroup_id=$(aws ec2 create-security-group --group-name $group_name --description "$description" --vpc-id vpc-547eae32 --output json | sed 's/}//g;s/"//g;s/ //g;s/{//g;s/GroupId://g')

while [ "$?" -eq "255" ]; do
echo "Dublicate name, enter detials again"
    read -p "Enter the Security group name :" group_name
    read -p "Enter the Security group description :" description
    sgGroup_id=$(aws ec2 create-security-group --group-name $group_name --description "$description" --vpc-id vpc-547eae32 --output json | sed 's/}//g;s/"//g;s/ //g;s/{//g;s/GroupId://g')
done

But this is not working for me.
this is the error code that comes for duplicate sg creation.
An error occurred (InvalidGroup.Duplicate) when calling the CreateSecurityGroup operation: The security group 'testsg1w' already exists for VPC 'vpc-547eae32'
Please tell me how can I handle this error.

A: I found an answer for this by myself,
What I did is compared the name given by the user with the already existing name in AWS.
If the name already existed them asked for a different name.
read -p "Enter the Security group name :" group_name
    STR=`aws ec2 describe-security-groups --filters Name=vpc-id,Values=$vpcId --query 'SecurityGroups[*].GroupName' --output text`
    echo $STR | grep $group_name &> /dev/nul
    while [ $? == 0 ];
    do
    echo ""
    echo "A security-group already exists by this name, please try a different name"
    echo ""
    read -p "Enter the Security group name :" group_name
    STR=`aws ec2 describe-security-groups --filters Name=vpc-id,Values=$vpcId --query 'SecurityGroups[*].GroupName' --output text`
    echo $STR | grep $group_name &> /dev/nul
    if [ $? == 0 ]; then
        echo ""
        echo "A security-group already exists by this name, please try a different name"
        continue
    else
        break
    fi
    done
    read -p "Enter the Security group description :" description
    aws ec2 create-security-group --group-name $group_name --description "$description" --vpc-id $vpcId


text:
Q: show sip user agent and ip only tcpdump I have been playing with some tcpdump commands and egrep
tcpdump -i eth1 port sip -l -A | egrep -i 'User-Agent'

i leave this running on asterisk pbx server and I can see all the useragents flow down the screen.
What i would like to see is the user agent and the ip of the sip client
then ignore a few different types of user-agents so that when I am done I only see ip address and user-agents coming down the screen of unknown traffic.
Here is a example of the full sip packets from the command without the egrep. I do not have a example in it where the user agent of sipcli/v1.8 maybe later I can get that.
07:54:24.358716 IP xxx.xx.xx.xxx.5060 > 10.1.44.10.5060: SIP, length: 543
EH.;.5..8.y..UF.&..
.....'!SSIP/2.0 401 Unauthorized
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK49b7b7d0;received=10.1.44.10;rport=5060
From: <sip:12345_3@voipprovider3.domain.com>;tag=as5afba40a
To: <sip:12345_3@voipprovider3.domain.com>;tag=as14777e11
Call-ID: 0e860af7278712754385ce784282c772@127.0.1.1
CSeq: 604 REGISTER
Server: voip.ms
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH, MESSAGE
Supported: replaces, timer
WWW-Authenticate: Digest algorithm=MD5, realm="voipprovider3.domain.com", nonce="7810c539"
Content-Length: 0

07:54:24.384512 IP 10.1.44.10.5060 > xxx.xx.xx.xxx.5060: SIP, length: 558
E`.Jrn..@..S&..
.UF......6..REGISTER sip:voipprovider3.domain.com SIP/2.0
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK6ef2d7d2;rport
Max-Forwards: 70
From: <sip:12345_3@voipprovider3.domain.com>;tag=as5afba40a
To: <sip:12345_3@voipprovider3.domain.com>
Call-ID: 0e860af7278712754385ce784282c772@127.0.1.1
CSeq: 605 REGISTER
User-Agent: unknown
Authorization: Digest username="12345_3", realm="voipprovider3.domain.com", algorithm=MD5, uri="sip:voipprovider3.domain.com", nonce="7810c539", response="5d6ac715deff942d1a3b22b39f83c0b1"
Expires: 120
Contact: <sip:s@10.1.44.10:5060>
Content-Length: 0

07:54:24.387070 IP xxx.xx.xx.xxx.5060 > 10.1.44.10.5060: SIP, length: 549
EH.A.6..8.y..UF.&..
.....-.GSIP/2.0 200 OK
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK6ef2d7d2;received=10.1.44.10;rport=5060
From: <sip:12345_3@voipprovider3.domain.com>;tag=as5afba40a
To: <sip:12345_3@voipprovider3.domain.com>;tag=as14777e11
Call-ID: 0e860af7278712754385ce784282c772@127.0.1.1
CSeq: 605 REGISTER
Server: voip.ms
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH, MESSAGE
Supported: replaces, timer
Expires: 120
Contact: <sip:s@10.1.44.10:5060>;expires=120
Date: Tue, 22 Nov 2016 12:54:24 GMT
Content-Length: 0

07:54:24.813579 IP 10.1.44.10.5060 > xxx.xx.xx.xxx.5060: SIP, length: 551
E`.C_...@.0.&..
.UF....../..REGISTER sip:voipprovider.domain.com SIP/2.0
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK3b0c2176;rport
Max-Forwards: 70
From: <sip:12345@voipprovider.domain.com>;tag=as5b82aabf
To: <sip:12345@voipprovider.domain.com>
Call-ID: 6face5f36fdd29c31d3a10182e207048@127.0.1.1
CSeq: 604 REGISTER
User-Agent: unknown
Authorization: Digest username="12345", realm="voipprovider1.domain.com", algorithm=MD5, uri="sip:voipprovider.domain.com", nonce="236a06e2", response="13d3528c45792fb242a47f1c18b43879"
Expires: 120
Contact: <sip:s@10.1.44.10:5060>
Content-Length: 0

07:54:24.816319 IP xxx.xx.xx.xxx.5060 > 10.1.44.10.5060: SIP, length: 539
EH.7Jy..7.Ou.UF.&..
.....# .SIP/2.0 401 Unauthorized
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK3b0c2176;received=10.1.44.10;rport=5060
From: <sip:12345@voipprovider.domain.com>;tag=as5b82aabf
To: <sip:12345@voipprovider.domain.com>;tag=as15b40d21
Call-ID: 6face5f36fdd29c31d3a10182e207048@127.0.1.1
CSeq: 604 REGISTER
Server: voip.ms
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH, MESSAGE
Supported: replaces, timer
WWW-Authenticate: Digest algorithm=MD5, realm="voipprovider1.domain.com", nonce="168d0f22"
Content-Length: 0

07:54:24.842388 IP 10.1.44.10.5060 > xxx.xx.xx.xxx.5060: SIP, length: 551
E`.C_...@.0.&..
.UF....../..REGISTER sip:voipprovider.domain.com SIP/2.0
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK69d58133;rport
Max-Forwards: 70
From: <sip:12345@voipprovider.domain.com>;tag=as5b82aabf
To: <sip:12345@voipprovider.domain.com>
Call-ID: 6face5f36fdd29c31d3a10182e207048@127.0.1.1
CSeq: 605 REGISTER
User-Agent: unknown
Authorization: Digest username="12345", realm="voipprovider1.domain.com", algorithm=MD5, uri="sip:voipprovider.domain.com", nonce="168d0f22", response="724e79293e8d587a2b8106df991486d7"
Expires: 120
Contact: <sip:s@10.1.44.10:5060>
Content-Length: 0

07:54:24.899968 IP xxx.xx.xx.xxx.5060 > 10.1.44.10.5060: SIP, length: 545
EH.=Jz..7.On.UF.&..
.....)..SIP/2.0 200 OK
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK69d58133;received=10.1.44.10;rport=5060
From: <sip:12345@voipprovider.domain.com>;tag=as5b82aabf
To: <sip:12345@voipprovider.domain.com>;tag=as15b40d21
Call-ID: 6face5f36fdd29c31d3a10182e207048@127.0.1.1
CSeq: 605 REGISTER
Server: voip.ms
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH, MESSAGE
Supported: replaces, timer
Expires: 120
Contact: <sip:s@10.1.44.10:5060>;expires=120
Date: Tue, 22 Nov 2016 12:54:24 GMT
Content-Length: 0

Here is with the egrep and the line with the ip addresses on it.  i really just want to show only the lines that show a user agent. this shows without useragent also.
tcpdump -i eth1 port sip -l -A | egrep -i 'User-Agent|SIP/2.0/UDP'

Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK6fd0af5a;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 158.85.70.151:5060;branch=z9hG4bK64939182;rport
User-Agent: VoipProvider
Via: SIP/2.0/UDP 158.85.70.151:5060;branch=z9hG4bK64939182;received=158.85.70.151;rport=42872
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK600d27fe;rport
User-Agent: Asterisk PBX
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK600d27fe;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK374f1905;rport
User-Agent: Asterisk PBX
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK374f1905;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK4ac13138;rport
User-Agent: Asterisk PBX
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK4ac13138;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK370927b1;rport
User-Agent: Asterisk PBX
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK370927b1;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;rport
User-Agent: sipcli/v1.8
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK7a1517ef
User-Agent: Asterisk PBX
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK7a1517ef;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK425ae339
User-Agent: Asterisk PBX
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK425ae339;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK7ac74b27
User-Agent: Asterisk PBX
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK7ac74b27;received=10.1.44.10;rport=5060
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 185.40.4.96:5070;branch=z9hG4bK-ac834e0a1d92fc96bb7b4da395a5ead5;received=185.40.4.96;rport=5070
Via: SIP/2.0/UDP 10.1.44.10:5060;branch=z9hG4bK7723c051
User-Agent: Asterisk PBX

I would like to see something like this
sipcli/v1.8 185.40.4.96

A: you could try something like that:
tshark -Y 'sip.User-Agent == "foo bar"' -T fields -e sip.User-Agent -e sip.Contact

keep in mind that user-agent is optional in sip packets.


text:
Q: Given a cube that is defined by an affine matrix how can we determin if a point is in the cube? I have a affine matrix ($M_{4,4}$) that represent the position of a bounding cube. given $v = \{0,0,0,1\}$, we get the center of the cube to be $M.v = \{x, y, z, 1\}$.
How can we determine if a point $\{a, b, c\}$ is in the cube?

A: As the vertices of the cube are not given, there is no way to tell whether a point lies inside the cube or not. However, if the cube before transformation is $C=[-r,\,r]^3$, the solution is easy. Given a point $\mathbf{p}=\pmatrix{a\\ b\\ c}$, calculate $M^{-1}\pmatrix{a\\ b\\ c\\ 1}=\pmatrix{\mathbf{q}\\ 1}$, where $\mathbf{q}\in\mathbb{R}^3$. Then $\mathbf{p}$ lies inside the bounding cube if and only if $\mathbf{q}\in C$, i.e. if and only if every coordinate of $\mathbf{q}$ is between $-r$ and $r$.


text:
Q: file upload (php) two warnings I am working on small page where I update MySQL records via PHP page, all the functionality is well working but I constantly get warnings for an Undefined array.
Here are the warnings:
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 22
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 22

I was looking at many topics like this but did not manage to fix my own one...
Here is the code of edit.php
include 'db.php';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
    if(in_array($fileType, $allowTypes)){
    }
        // Upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
        }

I have also a pcs of HTML for that in <form:
<form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >

                Нов сертификат:
                <input type="file" name="file" >

I have a feeling that I missed something very simple.
----- update -------
here is my full code: in one file I put php with the html
// include database connection file
include_once("config.php");
//тук стартирам за фаил ъплоад
// Include the database configuration file
include 'db.php';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
    if(in_array($fileType, $allowTypes)){
    }
        // Upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
        }
// край на фаил ъплоад

// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
    $id = $_POST['id'];
    $toolnr=$_POST['toolnr'];
    $status=$_POST['status'];
    $toolname=$_POST['toolname'];
    $serial=$_POST['serial'];
    $usedat=$_POST['usedat'];
    $owner=$_POST['owner'];
    $calibrated=$_POST['calibrated'];
    $nextcalibration=$_POST['nextcalibration'];
    $vendors=$_POST['vendors'];

    // update user data
    $result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
    // Redirect to homepage to display updated user in list
    header("Location: index.php");
}

?>
<?php
// Display selected user data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech user data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
    $toolnr = $user_data['toolnr'];
    $status = $user_data['status'];
    $toolname = $user_data['toolname'];
    $serial = $user_data['serial'];
    $usedat = $user_data['usedat'];
    $owner = $user_data['owner'];
    $calibrated = $user_data['calibrated'];
    $nextcalibration = $user_data['nextcalibration'];
    $vendors = $user_data['vendors'];
    $momenten = $user_data['file_name'];
}

?>

    <title>Актуализация</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

 В момента работите с най-високо ниво на достъп, моля бъдете внимателни.
 Всички направени от Вас промени са необратими.

     <form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >

                Номер
                <input type="text" name="toolnr" class="form-control" value=<?php echo $toolnr;?>>

                Статус

                <select name="status" id="status" class="form-control" required>
    <?php
        include "dbConn.php";
        $records = mysqli_query($db, "SELECT status FROM tools WHERE id=$id UNION SELECT currentstatus FROM statuses");

        while($data = mysqli_fetch_array($records))
        {
            echo "<option value='". $data['status'] ."'>" .$data['status'] ."</option>";
        }
    ?>  </select>

                Найменование
                <input type="text"  name="toolname" class="form-control" value="<?php echo $toolname;?>">

                Сериен номер
                <input type="text" name="serial" class="form-control" value="<?php echo $serial;?>">

                Локация

                <select name="usedat" id="usedat" class="form-control" required>
    <?php
        include "dbConn.php";
        $records = mysqli_query($db, "SELECT usedat FROM tools WHERE id=$id UNION SELECT locations From whereused");
        while($data = mysqli_fetch_array($records))
        {
            echo "<option value='". $data['usedat'] ."'>" .$data['usedat'] ."</option>";
        }
    ?>  </select>

                Отговорник

                <select name="owner" id="owner" class="form-control"  required>
    <?php
        include "dbConn.php";
        $records = mysqli_query($db, "SELECT owner FROM tools WHERE id=$id UNION SELECT responsiblepersons From responsibles");
        while($data = mysqli_fetch_array($records))
        {
            echo "<option value='". $data['owner'] ."'>" .$data['owner'] ."</option>";
        }
    ?>  </select>

                Калибриран на:
                <input type="date" name="calibrated" class="form-control" value=<?php echo $calibrated;?>>

                Следваща
                <input type="date" name="nextcalibration" class="form-control"  value=<?php echo $nextcalibration;?>>

                Сертификат
                <?php echo " Свали ";?>

                Нов сертификат:
                <input type="file" name="file" >

                Калибрира се при

                <select name="vendors" id="vendors" class="form-control" required>
    <?php
        include "dbConn.php";
        $records = mysqli_query($db, "SELECT vendors FROM tools WHERE id=$id UNION SELECT vendoren FROM vendors");
        while($data = mysqli_fetch_array($records))
        {
            echo "<option value='". $data['vendors'] ."'>" .$data['vendors'] ."</option>";
        }
    ?>  </select>

                <input type="hidden" name="id" value=<?php echo $_GET['id'];?>>
                <input type="submit" name="update"  class="btn btn-success" value="Запис">
                 Отказ

    </form>

A: Posting working code:
final-fixed code (only php part). The problem was that the part of the code responsible for file upload was out of the if statement
<?php

// include database connection file
include_once("config.php");

// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{

    $id = $_POST['id'];
    $toolnr=$_POST['toolnr'];
    $status=$_POST['status'];
    $toolname=$_POST['toolname'];
    $serial=$_POST['serial'];
    $usedat=$_POST['usedat'];
    $owner=$_POST['owner'];
    $calibrated=$_POST['calibrated'];
    $nextcalibration=$_POST['nextcalibration'];
    $vendors=$_POST['vendors'];

// Include the database configuration file
include 'db.php';
$statusMsg = '';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){

    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
    if(in_array($fileType, $allowTypes)){
    }
    }
        // Upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
        }

    // update user data
    $result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
    // Redirect to homepage to display updated user in list
    header("Location: index.php");
}

?>


text:
Q: OSM doesn't show in Android 5.1 but is shown in Android 4.1.1, How i can resolve it? i'm developing an hybrid app with cordova using leafletjs and osm. The open street map is shown in android 4.1.1 but not in android 5 (it shows gray panel). How i can resolve it?

A: EDIT following below comments
In addition to the Cordova whitelist, it looks like you also need to explicitly set your Content-Security-Policy (CSP) in your page HTML Head.
Probably something like:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' *.tile.osm.org">

See also: https://content-security-policy.com/
Note: from your error log, it looks like you should also allow other sources.

Have you white listed the openstreetmap.org website (with subdomains)?
https://cordova.apache.org/docs/en/6.x/guide/appdev/whitelist/index.html

A: //onde mostra a imagem do mapa
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));

Use is code within on create


text:
Q: Matrix function If we have $n$ by $n$ A matrix  I want to ask about the general method to compute the matrix function.
For example how I can compute:
$cos(A)$ or
$sin(A)$ or
$e^{A}$ or
$log(A)$
or any other functions?

A: We can define functions $F: \mathcal{M}_{n\times n}(\mathbb{R})\rightarrow \mathcal{M}_{n\times n}(\mathbb{R})$ analogous to analytic functions $f: \mathbb{R}\rightarrow\mathbb{R}$ in the following way:
Let $A\in\mathcal{M}_{n\times n}(\mathbb{R})$. Define $A^0 = I$. Then, define $A^k = A\cdot A^{k-1}$ recursively, via the usual matrix product. For any polynomial $p(x) = \sum\limits_{i=1}^k c_ix^i$, we can now define the matrix polynomial $P(A) = \sum\limits_{i=1}^k c_iA^i$.
For functions which are not polynomials, but are analytic, we can use their power series expansion. Let $f(x)$ be an analytic function with power series $\sum\limits_{i=1}^\infty c_ix^i$. Then, we can define the matrix function $F(A)$ by its power series $ \sum\limits_{i=1}^\infty c_iA^i$, given that such a series converges to a unique matrix value for each $A$. Here is an example of proving convergence for the matrix exponential, $\exp(A) := \sum\limits_{i=1}^\infty \frac{1}{i!}A^i$. A similar method can be used to show convergence of other matrix power series corresponding to real analytic functions.

A: A consequence of the Cayley-Hamilton theorem is that any analytic function $f$ of an $n\times n$ matrix $A$ can be expressed as a polynomial $p(A)$ of degree at most $n-1$. It's also the case that if $\lambda$ is an eigenvalue of $A$, then $f(\lambda)=p(\lambda)$. If you know $A$'s eigenvalues, you can therefore generate a system of linear equations in the unknown coefficients of $p$. If there are repeated eigenvalues, this system will be underdetermined, but you can generate additional independent equations by repeatedly differentiating $f$ and $p$.

A: Calculate the eigenvalue decomposition of the matrix
$$A=QDQ^{-1}$$ where $D$ is a diagonal matrix whose entries are the eigenvalues of $A$, and the columns of $Q$ are the corresponding eigenvectors.
With this decomposition in hand, any function can be evaluated as
$$f(A)=Q\,f(D)\,Q^{-1}$$
which is very convenient; just evaluate the function at each diagonal element.
If $A$ cannot be diagonalized or $Q$ is ill-conditioned, add a small random perturbation to the matrix and try again.
$$\eqalign{
A' &= A+E \cr
\|E\| &\approx \|A\|\cdot 10^{-14} \cr
}$$


text:
Q: What is meaning of this Scheduler expression -> *~*~*~*~*/6~0~0? What is meaning of this Scheduler expression. Not sure is it a Quartz Expression or timer service of ejb but i am sure the projects are using among this.

*~*~*~*~*/6~0~0
*~*~*~*~5~15~0

So not able to understand especially the one */6
Could anyone please elaborate on same?

A: / used to specify repetitive schedules,
For Example 2/3 in minutes range specifies,

Every 3 minutes, starting at 2 minutes past the hour

Quartz scheduler dose not support */6, in quartz */6 is equivalent to 0/6
/ - used to specify increments. For example, "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". You can also specify '/' after the '' character - in this case '' is equivalent to having '0' before the '/'. '1/3' in the day-of-month field means "fire every 3 days starting on the first day of the month".
from: http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html


text:
Q: rectangle overlay on Camera for OCR using Xamarin Android I am new to Xamarin and Android development.
I have a camera in my android app. with which I can take pictures and send it for OCR using Tesseract. But, the results are not at all accurate.
So, I want to reduce the scannable area by customizing the camera view.
For that, I need a overlay rectangle, so that when a picture is taken, only the image inside the overlay will be sent to OCR.
How can I put this overlay this overlay in camera view.
I need some kind of start.

A: I am using Xlabs for taking photos using the ,
var result = await _mediaPicker.TakePhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
}
);

But before doing this, I need to customize the camera view so that I can put a transparent overlay, and the image which is captured is only the part which is inside the overlay.
Custom renderer is on my mind.
I will be implementing a custom renderer view
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/view/
But, I am not sure exactly how it is done.
Inside the custom renderer, I guess, I will have to draw a rectangle class.
I am really stuck here. I just need a path or some guidance with which I could go ahead


text:
Q: Verificar se um documento foi assinado digitalmente Estou precisando verificar se um documento PDF foi assinado digitalmente. Encontrei este codigo na internet e funcionou, mas não para todas assinaturas. Alguém poderia me ajudar?
function isStringInFile($file,$string){

        $handle = fopen($file, 'r');
        $valid = false; // init as false
        while (($buffer = fgets($handle)) !== false) {
            if (strpos($buffer, $string) !== false) {
                $valid = true;
                break; // Once you find the string, you should break out the loop.
            }
        }
        fclose($handle);

        return $valid;

}

Chamada da função acima
        $retorno = isStringInFile($file["tmp_name"], 'adbe.pkcs7.detached');


text:
Q: Generating a midi signal from switches or digital logic I have a control board I have wired up consisting of various buttons and momentary switches. (For an art project)
There are enough for exactly two octaves (C3 to C5). I want to connect these control voltages to some off the shelf board that will generate the correct midi notes for me, which I can then connect to a synth to generate the actual sounds.
So my flowchart is:
control board -> ? -> synth -> PA.
What exactly is the board called that goes in that space? Basically something that can convert switches / logic into a midi signal?
There must be something off the shelf that can do this.

A:
There must be something off the shelf that can do this.

Not really. Every MIDI controller (that's what the thing you're making is typically called) that's sold has a slightly different set of functions besides the main note-generating keys, so it will want slightly different programming of the relationship between the input controls and the MIDI outputs.
And it's more complex and expensive to build two boards/modules where one does the notes and the other does other functions. (Especially if the other functions modify the MIDI, like arpeggiation.) That doesn't mean that what you want is hard, it just means that it's not automatically an off-the-shelf part found in normal controller hardware.

What exactly is the board called that goes in that space?

It wouldn't have a name besides "the (main) board" for that product, likely.
What goes on that board is:

*

*a keyboard matrix — an arrangement of wires plus possibly diodes and/or multiplexer chips to reduce the 24 separate switches into something that can be scanned using a reasonable number of IO lines. (This is exactly the same technology that you'd use for a computer keyboard or a 16-key numeric keypad or anything else with lots of buttons. There are lots of ways to do it and information is readily available — look for "key matrix" and "scanning".)

*A microcontroller, which has been programmed to scan the keyboard and generate MIDI commands.

*Possibly an output buffer for the MIDI signal.

*Power supply and other such supporting components.
The thing which is most likely to be off-the-shelf in this bundle is the code to generate the MIDI commands, which might be reused among many products. (I don't know myself if there's recommendable open-source code for the purpose.)
If you're willing to program, a 24-key diode-matrixed keyboard can be scanned with 10 GPIO pins, which is well within the capabilities of an Arduino board or most any other microcontroller dev board. So you'd need some diodes and an Arduino and you're done but for the software.

That said, there are ready-made boards that you could drop in to do this job.
I searched for "midi controller board" and found this company selling boards specifically for custom MIDI controllers. Here's another one, or here. (Not a buying recommendation; just examples.) Of course, you'll pay a fair bit for a specialized, low-volume development board that does more than you need.
You could also find an old junked controller (or piano with MIDI out) and salvage the board from it, wiring up your replacement key switches, as long as it doesn't turn out to need any of the stuff you'd be cutting away (e.g. expecting some front-panel slide switch to be making contact, which you could fix by wiring across the relevant terminals; troubleshooting skills are useful here to figure out how to make it work).


text:
Q: How do I make a non absolute connection string so my small database works with my published C# application? I'm working on a small project to track information. This C# application will take information uploaded via CSV/Excel and store/sort it.
My current connection string is an absolute path (off thumb drive). I'm worried that when I publish it, the database connection won't work on a random users computer.
            <add name="PPP_Project.Properties.Settings.Database1ConnectionString"
        connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Other PPP Projects\PPP_Project_Test\PPP_Project\Database1.mdf;Integrated Security=True;User Instance=True"
        providerName="System.Data.SqlClient" />

How do I have this set so it will work when the application is published?

A: you can use this:
Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Customers.mdf;Integrated Security=True;User Instance=True

as described here.
For a winform application, the default |DataDirectory| is the same where the application is installed. Of course you can use aa a part of a more nested path.
If you want to specifyng something else you can use the AppDomain.SetData method.

A: The easiest way to manipulate connection strings is with the ConnectionStringBuilder classes:
OleStringBuilder = new OleDbConnectionStringBuilder(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';");

OleStringBuilder.DataSource = MapPath(@"~\App_Datav\MyExcelWorksheet.xls");


text:
Q: Update existing table by migration I have a database created by "database first" approach. But now I want to update records in the specific table by "code first" approach, by migrations. I can insert records by using EntityTypeBuilder.HasData() in IEntityTypeConfiguration instance, but how to update existing records?

A: You can use migrationBuilder.Sql command to execute pure SQL-expressions during migration:
 protected override void Up(MigrationBuilder migrationBuilder)
 {
    migrationBuilder.Sql("Your UPDATE sentence here");
 }


text:
Q: Error installing testacular with latest version of nodejs 0.8.19 I get the following error when I run below command..
⚡ sudo npm -g install testacular
module.js:340
    throw err;
          ^
Error: Cannot find module 'npmlog'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at /usr/local/bin/npm:19:11
    at Object.<anonymous> (/usr/local/bin/npm:87:3)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

A: Try re-installing node.js - http://nodejs.org/download/
This happened to me after an old version of n failed to install node v0.10.5, then I upgraded n and had it install node. It apparently didn't install npm quite correctly.


text:
Q: How can i change the name of facebook page? I need to change the name of my facebook page.
Is it possible? Facebook doesn't allow to do this. But maybe someone had a successful experience?

A: No, this is not possible as far as I know, at least not through an API. Refer to the help section at Facebook.

A: There is no such a possibility


text:
Q: How to prevent Devise from auto logout user on specific page? I have devise-based auth system on my RoR-site, and I need to auto sign out user after some time of inactivity. But also I have some pages on my site, that created to be opened for long time (user will just watch to page, where info is updated by ajax) and I want to NOT sign out user when this page is opened.
Is anybody has a idea how to do that? Or how to tell Devise that ajax request is a user activity too?

A: First make sure you have devise 1.5.2 installed, if not, upgrade it, its been 6 months at this question :-) and I hope you already solved the problem.
You can change the timeout_in return value when you are at the page you want to prevent auto signout at.
For example:
class Student < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :timeoutable

  def timeout_in
      if session[:auto_sign_out] then
         #the normal period of signout
         30.minutes
      else
         #very long period, to prevent sign-out
         100.years
      end
  end
end

Then, you can easily add a before_filter at ApplicationController to set the session[:auto_sign_out] value
like this:
before_filter :manage_page_auto_sign_out

def manage_page_auto_sign_out
# check the params, and see if the id is the id of the specific page
if params[:id] == EXCLUDED_PAGE_ID then
session[:auto_sign_out]= false
else
session[:auto_sign_out]= true
end
end

additionally, you can add other conditions to make sure that you are checking against the page you want, by checking the controller name of page like this:
def manage_page_auto_sign_out
# check the params, and see if the id is the id of the specific page
if controller_name == 'pages' && params[:id] == EXCLUDED_PAGE_ID then
session[:auto_sign_out]= false
else
session[:auto_sign_out]= true
end
end

you need to check the name of the page controller, I hope this helps


text:
Q: Robo 3T able to bypass MongoDB auth=true I used robo 3t to login to a database and was surprised that I was able to write on the collection despite having a read only role, by adding a document via the GUI or sending commands through Robo 3T.
What could be the problem? On mongosh (mongo shell) I wasnt able to.
tonidoclouddb> db.getRole("test", {showPrivileges:true})
{
  role: 'test',
  db: 'tonidoclouddb',
  isBuiltin: false,
  roles: [],
  inheritedRoles: [],
  privileges: [
    {
      resource: {
        db: 'tonidoclouddb',
        collection: 'users'
      },
      actions: [ 'find' ]
    }
  ],
  inheritedPrivileges: [
    {
      resource: {
        db: 'tonidoclouddb',
        collection: 'users'
      },
      actions: [ 'find' ]
    }
  ]
}

{
  _id: 'tonidoclouddb.mynewuser',
  userId: UUID("46bdf5e7-fb0a-4616-a1ee-5fc46fd0f97f"),
  user: 'mynewuser',
  db: 'tonidoclouddb',
  roles: [ { role: 'test', db: 'tonidoclouddb' } ],
  mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
} ```


text:
Q: Is it possible to treat the time dimension as the rate of change of an extra spatial dimension? In Minkowski Spacetime metric the time dimension is multiplied with $c$. This would allow us to swap it against a fourth space dimension: $cdt=dx_4$. One interpretation would be that the rate of change in this fourth space dimension is the observed time. In other words it looks like you can treat the fourth dimension as a representative for both space and time. Is this really possible?
As an example, consider a one dimensional wave, which can be described by two dimensions, viewed by an observer in different states . In both cases below the absolute speed is the speed of light c. The difference is that in Case A the wave is moving in both x (horizontal) and y (vertical) direction, while in Case B it is just moving in the x direction.
$c^2=v_x^2+v_y^2$
Case A 0: $\wedge$       1: $-$       2: $\vee$       3: $-$      4: $\wedge$
Case B 0: $\wedge$       1: $\wedge$       2: $\wedge$
The timeperiod T according to an observer for the wave in Case A to go from state 0 to state 4, or complete one oscillation and get back to the original state, would be decscibed by the distance s divided by c.
$T=s/c$
-> $cdT=ds$
The path of the wave could be descibed by Pythagoras
$ds^2=dx^2+dy^2$
The proper time period t would just be the distance in the y direction, simply moving up and down.
$dy=cdt$
Combining it all and we would get
$c^2*dT^2=dx^2+c^2*dt^2$
Reshuffle to express proper time as a function of observed time + space components
-> $-c^2*dt^2=dx^2-c^2*dT^2$
Now we have the produced the metric (-,+). Add two more space dimensions and you get (-,+,+,+). But we clearly started with two space dimensions and it is obviuos that we can use it mathimatically like taking the derivative of y with repect to x for example.
Now take a big jump to Kaluza-Klein theory. Using the logic from above, it means that we dont have to add a fifth dimension to get a fourth spatial dimension but rather we already have it if we decide to treat the time dimension as a spatial one. Working out the geometry of the fourth dimension with respect to the other three and you'll get electromagnetism without the extra scalar field (obs, this in an unsupported claim). Switching it back to the time view and you arrive back to standard General Relativity.

A: The thing which ultimately distinguishes a temporal dimension from a spatial one is not the choice of units (which are arbitrary) but rather the sign of the corresponding term in the metric.  In Minkowski spacetime and cartesian coordinates, one has that
$$\mathrm ds^2 = \color{red}{-} c^2\mathrm dt^2 + \mathrm dx^2 + \mathrm dy^2 + \mathrm dz^2$$
In the coordinate system $(t,x,y,z)$, the first coordinate has dimensions of time while the others have dimensions of length; the metric components are $g_{\mu\nu} = \mathrm{diag}(-c^2,1,1,1)$ which makes the spacetime interval $\mathrm ds^2$ have dimensions of length. On the other hand, we could choose coordinates $(x^0,x^1,x^2,x^3)\equiv (ct,x,y,z)$, in which case all of the coordinates have dimensions of length and the metric components are $g_{\mu\nu}=\mathrm{diag}(-1,1,1,1)$.  Either choice is perfectly fine; the important thing is the minus sign before the first term in $\mathrm ds^2$.
I'm afraid I don't quite understand your point about Kaluza-Klein.  The idea of that theory is to add an additional compact dimension; under certain conditions, the extra degrees of freedom essentially behave like the electromagnetic 4-potential, suggesting that one might be able to understand electromagnetism as a manifestation of a compact extra dimension in addition to the "large" dimensions we readily observe.  This idea is very nice, but it does not match what we know from experiment (e.g. it predicts a concrete relationship between the mass and charge of a body).  In any case, there is no sense in which "reinterpreting" $ct$ as a spatial coordinate has any correspondence with Kaluza-Klein.


text:
Q: Incorrect Hibernate HQL / DAO function / while coding Spring Security - Annotations I learn the hibernate framework and I am so confused with generated sql.
I have the following code:
Table:
CREATE TABLE users (
 user_id int NOT NULL AUTO_INCREMENT,
 login varchar(20) UNIQUE,
 pass varchar(20),
 user_name varchar(20),
 surname varchar(20),
 PRIMARY KEY (user_id)
)

Model:
@Entity
 @Table(name="users", catalog="maximodb")
 public class User implements Serializable{

@Id
@Column(name="user_id")
@GeneratedValue(strategy =GenerationType.IDENTITY)
private Integer userId;

@Column(name = "login", unique = true, length = 20)
private String login;

@Column(name = "pass", length = 20)
private String pass;

@Column(name = "user_name", length = 20)
private String userName;

@Column(name = "surname", length = 20)
private String surname;

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "users_roles", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
private Set<Role> userRoles = new HashSet<Role>();

public User() {
}

public User(String login, String pass, String userName, String surname) {
    this.login = login;
    this.pass = pass;
    this.userName = userName;
    this.surname = surname;
}

public Integer getUserId() {
    return this.userId;
}

public void setUserId(Integer userId) {
    this.userId = userId;
}

public String getLogin() {
    return this.login;
}

public void setLogin(String login) {
    this.login = login;
}

public String getPass() {
    return this.pass;
}

public void setPass(String pass) {
    this.pass = pass;
}

public String getUserName() {
    return this.userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getSurname() {
    return this.surname;
}

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

public Set<Role> getUserRoles() {
    return userRoles;
}

public void setUserRoles(Set<Role> userRoles) {
    this.userRoles = userRoles;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((login == null) ? 0 : login.hashCode());
    result = prime * result + ((pass == null) ? 0 : pass.hashCode());
    result = prime * result + ((surname == null) ? 0 : surname.hashCode());
    result = prime * result + ((userId == null) ? 0 : userId.hashCode());
    result = prime * result + ((userName == null) ? 0 : userName.hashCode());
    result = prime * result + ((userRoles == null) ? 0 : userRoles.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    User other = (User) obj;
    if (login == null) {
        if (other.login != null)
            return false;
    } else if (!login.equals(other.login))
        return false;
    if (pass == null) {
        if (other.pass != null)
            return false;
    } else if (!pass.equals(other.pass))
        return false;
    if (surname == null) {
        if (other.surname != null)
            return false;
    } else if (!surname.equals(other.surname))
        return false;
    if (userId == null) {
        if (other.userId != null)
            return false;
    } else if (!userId.equals(other.userId))
        return false;
    if (userName == null) {
        if (other.userName != null)
            return false;
    } else if (!userName.equals(other.userName))
        return false;
    if (userRoles == null) {
        if (other.userRoles != null)
            return false;
    } else if (!userRoles.equals(other.userRoles))
        return false;
    return true;
}

}
And now... dao function (two variants):
The first:
List<User> users = new ArrayList<User>();

    users = sessionFactory.getCurrentSession()
        .createQuery("from User where login= :login")
        .setString( "login", login )
        .list();

    if (users.size() > 0) {
        return users.get(0);
    } else {
        return null;
    }

Returned sql:
select
    user0_.user_id as user_id1_1_,
    user0_.login as login2_1_,
    user0_.pass as pass3_1_,
    user0_.surname as surname4_1_,
    user0_.user_name as user_nam5_1_
from
    maximodb.users user0_
where
    user0_.login=?

And the second variant:
    Criteria criteria =  sessionFactory.getCurrentSession().createCriteria(User.class);
    List<User> a = (List<User>) criteria.list();

User us = a.get(0);

    return us;

Returned sql:
select
    this_.user_id as user_id1_1_0_,
    this_.login as login2_1_0_,
    this_.pass as pass3_1_0_,
    this_.surname as surname4_1_0_,
    this_.user_name as user_nam5_1_0_
from
    maximodb.users this_

The second variant is quite correct and gets user from the db. But in the first case there is a null pointer exception instead of User object. What is incorrect?
It is worth to higilight that generated sql works good in MySql Workbench (first case).

A: The first variant try to get a user with the given login but no user found for this login (verify that there is a user with the given login in database).
The second variant list all users in the database and than get the first one. Your User table contain some users that's why this variant return a user and not null.


text:
Q: vuejs - Changing a computed property via a method I am trying to adjust a computed property within a vue component inside a method. When this property changes I am trying to show/hide a div.  Currently when I perform the click event, I am seeing the correct boolean log under the set function, but not seeing any change to the showBanner prop.
Here's where I'm at.
HTML
<template>
  <div v-if="someConfig.displayBanner && showBanner" class="bn-banner">
    {{showBanner}}
  </div>
</template>

<script>
  import { mapActions, mapState } from 'vuex';

  export default{

    name: "myComponentShell",

    computed: {
      ...mapState('utilitiesStore', [
        'someConfig'
        ]),

        styleObject () {
          return {
            background: this.someConfig.colorHex
          }
        },

    showBanner:{

      get () {
        return (this.someConfig.text === localStorage.getItem("gma_alerts_hide")) ? false : true
      },

      set (value) {
        console.log(value)
        return value
      }
    }

    },

    methods: {
      ...mapActions('utilitiesStore', [
          'getJSON'
        ]),

        closeBreaking () {
          localStorage.setItem("someData", this.someConfig.text)
          this.showBanner = false;
        }
    },

  }

</script>

A: you can use && operator in your code to fixed "text is undefined" error
(this.someConfig && this.someConfig.text)

Inside this code:
data () {
return {
    showBanner: (this.someConfig.text === localStorage.getItem("gma_alerts_hide")) ? false : true
}}

A: That's because you're returning a value instead of assigning a value in your set method of showBanner computed property.
Try something like
set (value) {
  this.someConfig.text = value; // I assign a value so get() method will trigger
}

Keep in mind that set  method must modify something in order to see changes in showBanner
https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter

A: showBanner is not truly a computed property, it is simply a variable who's state is initialized from a ternary. Therefore you should just declare it as a data property.
data () {
    return {
        showBanner: (this.someConfig.text === localStorage.getItem("gma_alerts_hide")) ? false : true
    }

}

Then this.showBanner = false; makes sense.
Edit Updated data declaration because you're using single file components.


text:
Q: Rails 4 - On click render ruby partial in js.erb I'm trying to render a partial on click through a JavaScript function. The partial is a checkbox form but when I click the element that has an event listener attached to it nothing happens but I also get no errors.
$("#organization_profile_lock").addEventListener("onclick", profileLockConfig);

function profileLockConfig() {
  $("#organization_profile_lock").replaceWith("<%= escape_javascript(render partial: "setup_organizations/_profile_lock_settings") %>");
}

This is the controller which handles the change
def edit_configuration
  @form = SuperAdmins::EditConfigurationForm.new(@organization)
end

Does anyone know how I can achieve this functionality, thanks in advance:)!


text:
Q: List should be clicked on button Hover I have created one DIV with button and list.I want when I Hover on button, list should display as well as I  can click on items in List. currently list displaying on button hover but when I want some List item to clicked its Disappearing .
My Html is

            <button id='rentInbutton'>Buy/Rent In</button>

Accomodation

Vehicles

And my Jquery Code is
$(document).ready(function(){
             $('#rentin ul').hide();
             $("#rentInbutton").hover(function(){
                     $('#rentin ul').show();},function(){
                       $('#rentin ul').hide();
});
}  )

A: You can hover retin instead of hovering retinInButton because button and list is inside retin and initially when list is hidden retin area is almost equal to button area and when list is visible then retin will take space equal to button plus list and you will not loose list because mouse pointer is still inside retin, see below code
$(document).ready(function(){
       $('#rentin ul').hide();
        $("#rentin").hover(function(){
           $('#rentin ul').show();},function(){
          $('#rentin ul').hide();
        });
});

JSFiddle Demo

A: Try this:
$(document).ready(function() {
    $('#rentin ul').hide();
    $("#rentInbutton").hover(function() {
        $('#rentin ul').show();
    });
})

A: The problem is that you are hiding the UL when the mouse leaves the button, instead you should hide it only when the mouse leaves the UL or its container - Demo
$("#rentInbutton").mouseover(function(){
    $('#rentin ul').show();
});
$('#rentin').mouseleave(function(){
    $('#rentin ul').hide();
});


text:
Q: Removing Rails/Spree image upload limit? My client called today because they couldn't upload their images to their shopping site, and I have absolutely no idea where the upload file size limits are configured.
So here's my server configuration: Ubuntu 10.04LTS, Spree on Rails 2.3, Nginx.
Basically I want to remove the file-size upload limit.
Anyone know where I should go to get started?

A: Have you checked your Nginx config?
More specifically the client_max_body_size directive?
To make sure your Spree install is not rejecting the file, fire up script/server locally and try uploading a big file to it.

A: Spree uses Paperclip (http://github.com/thoughtbot/paperclip) for it's image processing and management. You might also check there for a size limit.

A: Be sure to also checkout spree-user google group for Spree-related questions.  You might get a faster response there.

A: So you really want your client to upload their 18 megapixel images from their DSLR directly to the site? Or, did you ask them how large the images are they want to upload? As others already said, there are several places where file size can be limited. In addition, the image files might be encoded, so the limit can be much lower than you'd expect.


text:
Q: How to open Excel file with Read Only protection? I have opened Excel file in my C# WinForm Application adding reference to Microsoft.Office.Interop.Excel.dll and using DSO FRAMER CONTROL. But i want to open my excel file with read only protection.I have successfully done this for WORD Application like this
Word.Document wordDoc = (Word.Document)axFramerControl1.ActiveDocument;
Word.Application wordApp = wordDoc.Application;
wordDoc.Protect(Word.WdProtectionType.wdAllowOnlyReading);

In the same i want to do this work for Excel.But i couldn't able to protect Excel file on that way.
string path = "C:\\test-wb.xlsx";
axFramerControl1.Open(path, true,"excel.sheet", "", "");

Excel._Workbook excelDoc   =(Microsoft.Office.Interop.Excel._Workbook)axFramerControl1.ActiveDocument;
Excel.Application excelApp =excelDoc.Application;
//What code should i write to protect Excel Workbook with read - only.
excelDoc.Protect(misval, true, misval);//It is not working.

A: Call theOpen method with third parameter (ReadOnly) = true.
See MSDN documentation :
ReadOnly
Optional Object. True to open the workbook in read-only mode.

A: The WorkBook class has a Protect method, similar (but not identical) to the one supported by Word. I can't find the COM/interop documentation, but the VSTO documentation covers the same ground, and the method signatures are the same:
Protect

Protects a workbook so that it cannot be modified.

public virtual void Protect (
    [OptionalAttribute] Object Password,
    [OptionalAttribute] Object Structure,
    [OptionalAttribute] Object Windows
)

(This all assumes that what you wanted to achieve was to protect the document, since that's what the Word code does, as opposed to opening the document read only, which is what your narrative seems to be saying, in which case, @gdoron's answer is more suitable


text:
Q: How to set minDate value in CoreUI bootstrap? I read the documentation here: https://coreui.io/docs/forms/date-range-picker/#disabled-dates
However I cant seem to make it work by putting the attribute instead of javascript: https://coreui.io/docs/forms/date-range-picker/#options
<div data-coreui-toggle="date-picker"
    data-coreui-indicator="false"
    data-coreui-cleaner="true"
    data-coreui-size="sm"
    data-coreui-locale="en-US"
    data-coreui-date="{{ old('date-picker-check_in') }}"
    data-coreui-min-date="10/01/2022"
    class="bottom"
    id="check_in">
</div>

has anyone have experienced this as well?
I also tried emailing support but they have not replied yet.


text:
Q: Django Ubuntu 16.04 "unsupported hash type" I've deployed a web app to an Ubuntu 16.04 VM. I implemented the standard Django login by the books. Everything is working properly on my production environment (OS X); however, when I attempt to login I receive the error

ExceptionValue: unsupported hash type

Ubuntu is running python 3.5.2

OS X is running python 3.6.1

Both are running Django Version 1.11.6
My requirements.txt
blessings==1.6
bpython==0.16
certifi==2017.7.27.1
chardet==3.0.4
curtsies==0.2.11
Django==1.11.6
django-extensions==1.9.6
geopy==1.11.0
greenlet==0.4.12
idna==2.6
psycopg2==2.7.3.2
Pygments==2.2.0
pytz==2017.2
requests==2.18.4
six==1.11.0
urllib3==1.22
wcwidth==0.1.7

I am using a virtual environment to run this project.
The traceback path is as follows,
Traceback:

File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/core/handlers/exception.py"
  in inner
    41.             response = get_response(request)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/core/handlers/base.py"
  in _get_response
    187.                 response = self.process_exception_by_middleware(e, request)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/core/handlers/base.py"
  in _get_response
    185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/views.py"
  in inner
    54.         return func(*args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/views.py"
  in login
    150.     )(request)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/views/generic/base.py"
  in view
    68.             return self.dispatch(request, *args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py"
  in _wrapper
    67.             return bound_func(*args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/views/decorators/debug.py"
  in sensitive_post_parameters_wrapper
    76.             return view(request, *args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py"
  in bound_func
    63.                 return func.get(self, type(self))(*args2, **kwargs2)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py"
  in _wrapper
    67.             return bound_func(*args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py"
  in _wrapped_view
    149.                     response = view_func(request, *args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py"
  in bound_func
    63.                 return func.get(self, type(self))(*args2, **kwargs2)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py"
  in _wrapper
    67.             return bound_func(*args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/views/decorators/cache.py"
  in _wrapped_view_func
    57.         response = view_func(request, *args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py"
  in bound_func
    63.                 return func.get(self, type(self))(*args2, **kwargs2)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/views.py"
  in dispatch
    90.         return super(LoginView, self).dispatch(request, *args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/views/generic/base.py"
  in dispatch
    88.         return handler(request, *args, **kwargs)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/views/generic/edit.py"
  in post
    182.         if form.is_valid():
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/forms/forms.py"
  in is_valid
    183.         return self.is_bound and not self.errors
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/forms/forms.py"
  in errors
    175.             self.full_clean()
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/forms/forms.py"
  in full_clean
    385.         self._clean_form()
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/forms/forms.py"
  in _clean_form
    412.             cleaned_data = self.clean()
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/forms.py"
  in clean
    187.             self.user_cache = authenticate(self.request, username=username, password=password)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/init.py"
  in authenticate
    70.             user = _authenticate_with_backend(backend, backend_path, request, credentials)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/init.py"
  in _authenticate_with_backend
    115.     return backend.authenticate(*args, **credentials)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/backends.py"
  in authenticate
    24.             if user.check_password(password) and self.user_can_authenticate(user):
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/base_user.py"
  in check_password
    118.         return check_password(raw_password, self.password, setter)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/hashers.py"
  in check_password
    52.     is_correct = hasher.verify(password, encoded)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/hashers.py"
  in verify
    265.         encoded_2 = self.encode(password, salt, int(iterations))
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/hashers.py"
  in encode
    258.         hash = pbkdf2(password, salt, iterations, digest=self.digest)
File
  "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/crypto.py"
  in pbkdf2
    140.             digest().name, password, salt, iterations, dklen)
Exception Type: ValueError at /login/ Exception Value: unsupported
  hash type

The traceback is entirely within my venv folder. The final error is shown below. Lines 133-146 of

/home/user_name/proj_folder/my_env/lib/python3.5/site-packages/django/utils/crypto.py
  in pbkdf2

        if digest is None:
            digest = hashlib.sha256
        if not dklen:
            dklen = None
        password = force_bytes(password)
        salt = force_bytes(salt)
        return hashlib.pbkdf2_hmac(
            digest().name, password, salt, iterations, dklen) ...
else:
    def pbkdf2(password, salt, iterations, dklen=0, digest=None):
        """
        Implements PBKDF2 as defined in RFC 2898, section 5.2
        HMAC+SHA256 is used as the default pseudo random function.

The final exception is thrown at digest().name, password, salt, iterations, dklen)
With Local Vars:
digest      <built-in function openssl_sha256>
dklen       None
iterations  36000
password    b'mypassword'
salt        b'saltshownhere'

I've seen similar questions relating to Solaris 10 where there may have been a problem with SSL installation/version. OpenSSL is installed on both machines. Although they are different versions.
Ubuntu - OpenSSL 1.0.2g

OS - OpenSSL 0.9.8zh

I am able to successfully run my application by removing the login requirement. I'd like to have a better understanding of what is going on here. Could this be a version error between my development and production environment caused by python or OpenSSL?


text:
Q: New Customer Orders, but only if they purchased 1 week after registering So what I'm trying to do is understand what products my new customers purchase, 1 week after they registered.
Currently, this is my query:
SELECT
    item_description_1,
    t3.new_division,
    quantity_ordered
FROM
    mdwh.us_raw.order_report
    INNER JOIN l_act_account t2 ON customer_id = SUBSTRING(t2.channel_uid,4,18)
    FULL OUTER JOIN item_master_zs t3 ON SUBSTRING(upc,1,6) = t3.item_code
WHERE
    quantity_ordered > 0
    AND customer_id IS NOT NULL
    AND customer_id != ('')
    AND customer_id LIKE 'US%'
    AND oms_order_date IS NOT NULL
    AND extended_amount < 1000 --NO BULK ORDERS
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND (quantity_ordered * unit_price_amount) > 0
    AND oms_order_date BETWEEN '2019-03-01' AND '2019-03-31'
    AND t2.create_timestamp BETWEEN '2019-03-01' AND '2019-03-31'
    AND SUBSTRING(upc,1,6) IN (SELECT item_code FROM item_master_zs WHERE new_division BETWEEN '11' AND '39') --Overall
GROUP BY
    item_description_1,
    t3.new_division,
    quantity_ordered
ORDER BY
    quantity_ordered desc
LIMIT 60

This query is giving me the top 60 items purchased within March, from new customers I gained in March. Here's what the output looks like right now:

All I need now is an output that looks exactly like the above, but only showing me the items purchased 7 days AFTER their create_timestamp date (when they registered).
The point of this is as follows: some new customers may register an account and immediately make a purchase because of some sort of coupon or perhaps a referral. However, if I can see which products users purchased (where they seem to have waited a week before making a purchase), then I can see which products triggered them to come and make that purchase.
Please let me know if I made anything unclear, or if you need additional info.
Any help would be greatly appreciated!!

A: It appears you only want to include orders where the order date (oms_order_date) is within 7 days after registration date (create_timestamp).
Assuming that the order date is a DATE and the registration is a TIMESTAMP, you can only work in full days, not down to the hour.
Therefore, you'd use:
WHERE oms_order_date - create_timestamp <= INTERVAL '7 days'


text:
Q: Importance of periodic orbits In the study of dynamical systems, one often talks about solutions that repeat themselves after a certain time, hence their name of "periodic orbits". Then one moves to the distinction of "stable" (e.g. a harmonic 2D pendulum) or "unstable" periodic orbits.

First question:

*

*Do all dynamical systems (integrable or not) exhibit stable and unstable periodic orbits and if yes, why are periodic orbits inherent to all systems? (e.g. does the non-chaotic 2D simple pendulum ever exhibit unstable periodic orbits?)

Second question:

*

*In the study of dynamical systems (namely also chaotic ones), why is there so much emphasis on the study of periodic orbits (solutions) of a system (be it stable or unstable) instead of the other types of solutions that can be found (e.g. any closed orbit not being periodic, or other types)?

A: 1st question:
Yes all systems have areas of periodic (or almost-periodic, or isolated periodic) motion. For integrable systems this is the expected. But in fact the existence of isolated periodic solutions is a form of non-integrability a well (related to 2nd question as well). For the exact meaning of isolated periodic solution check the link on integrability above.
Considering stability, yes all systems (integrable or not) can have stable or unstable periodic solutions, of course for non-linear chaotic systems this is the norm.
The simple non-chaotic 2D pendulum, does not exhibit unstable periodic orbits (it does exhibit unstable equilibrium points, though)
2nd question:
You might want to check the KAM theory, which simply states that a no-integrable system which is close to an integrable system will have areas where the orbits are sustained (or in other words any sufficiently small perturbation away from an integrable system, can be studied by KAM theory using the periodic orbits, or invariant tori in phase space)
UPDATE:
Stable periodic solutions (as per the links in question) are periodic solutions which are dynamically stable, in other words if slightly perturbed the orbit will remain close to the original,
Unstable periodic solutions are those periodic solutions which are not stable in the previous sense.
Isolated periodic solutions are special kinds of solutions which relate to tests of non-integrability for some special cases of hamiltonians
Almost periodic solutions are solutions which are periodic in a probability sense. Meaning the system does not return exactly to the same point but close to it with probability 1 at certain periods.
Another link about (measuring) chaos in hamiltonian systems http://www.staff.science.uu.nl/~verhu101/SAMOSpap.pdf


text:
Q: MediaPlayer Listview onItemClick not playing Trying to make a MediaPlayer work on with a ListView however it doesn't seem to play when I press the item on the ListView. Not sure what I'm doing wrong. Any help would be great. Kinda new to this sorry if its obvious.
 public class soundboard2 extends AppCompatActivity implements AbsListView.OnScrollListener {

private int lastTopValue = 0;

private ImageView backgroundImage;
private ArrayAdapter adapter;
private String[] mFragmentTitles;
private ListView mDrawerList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listviewsound);

    final MediaPlayer sound01 = MediaPlayer.create(this, R.raw.sound01);

    mDrawerList = (ListView)findViewById(R.id.list);
    mFragmentTitles = getResources().getStringArray(R.array.fragments);

    adapter = new ArrayAdapter(this, R.layout.list_row, mFragmentTitles);
    mDrawerList.setAdapter(adapter);
    // inflate custom header and attach it to the list
    LayoutInflater inflater = getLayoutInflater();
    ViewGroup header = (ViewGroup) inflater.inflate(R.layout.custom_header, mDrawerList, false);
    mDrawerList.addHeaderView(header, null, false);

    // we take the background image and button reference from the header
    backgroundImage = (ImageView) header.findViewById(R.id.listHeaderImage);
    mDrawerList.setOnScrollListener(this);

            mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView a, View v, int position, long id) {
            if (mDrawerList.getItemAtPosition(position)=="Player") {
                try {
                    sound01.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                sound01.start();
                sound01.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    public void onCompletion(MediaPlayer mp) {
                        mp.release();
                    }
                });
            }
        }
    });
    @Override
public void onScrollStateChanged(AbsListView view, int scrollState) {

}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    Rect rect = new Rect();
    backgroundImage.getLocalVisibleRect(rect);
    if (lastTopValue != rect.top) {
        lastTopValue = rect.top;
        backgroundImage.setY((float) (rect.top / 2.0));
    }
}

}

Strings
   <string-array name="fragments">
    <item>Player</item>
    <item>two</item>
    <item>three</item>
      </string-array>

A: There could be a lot of things going wrong here, but I'll point out two things:
You need to prepare your media before it can be started.  You probably don't want to wait until the last second to create and prepare the media before playing it.
You're creating a MediaPlayer in your onCreate but aren't doing anything with it.
Perhaps also consider instead using SoundPool which is more appropriate for shorter clips that need to play very quickly in response to events.


text:
Q: What are these line-boxes called in Chart.js, and how do I turn them off? I'm displaying a Chart.js doughnut chart via react-chartjs-2 in React, and by default, there are these line-box things showing for each doughnut section. Here's an example:

What are these line-box things called, and how do I turn them off?
Also, for what it's worth, they don't seem to show up by default in the base Chart.js library, but they show up for doughnut (and probably pie) charts in the react-chartjs-2 npm package. I've searched and searched, and tried toggling a bunch of options for the legend, legend labels and tooltips, but to no avail. I cannot figure out how to turn these off. Thank you for your help.

A: Thanks again to LeeLanalee for pointing me in the right direction.
Unbeknownst to me, there was a Chart.js global plugin set up for all the doughnut charts called chartjs-plugin-piechart-outlabels (https://www.npmjs.com/package/chartjs-plugin-piechart-outlabels). As per following SO post, I was able to disable the line-box labels for specific instances of the doughnut charts (in React) as follows:
ChartJs - Pie Chart - how to remove labels that are on the pie chart
options={ {
    plugins: {
        outlabels: false
    }
} }

Thanks again!


text:
Q: Kubernetes GPU pods /Kubeflow I have 2 servers with 4 tesla K40 GPUs.
I have successfully created a kubernetes cluster installed kubeflow 1.0 and evertything needed for it to work fine.
I can successfully create a Jupyter notebook server with 4 GPUs and use keras multigpu model on it and everything works fine.
Can I use 8 gpu (4 from one server and 4 from another) to create jupyter notebook server or run any gpupod or only 4 for one gpupod is avaliable for me?
When I try use 8 GPUs I get 0/2 nodes are available: 2 Insufficient nvidia.com/gpu

A:
Can I use 8 gpu (4 from one server and 4 from another) to create jupyter notebook server or run any gpupod or only 4 for one gpupod is avaliable for me?

No, Kubernetes pods can only use resources from one machine(node) at a time.
You can learn more here.

As a workaround, you can run your jupyter server on one cluster, but train on GPUs from multiple clusters with some minimal code changes, depending on which framework you're working.
kubeflow even has some nice UI support for that. Here are some sources to learn more about:

*

*Clustering multiple GPUs from different machines and remotely run Jupyter Notebook #2720

*Using IPython for parallel computing

*How-To: Multi-GPU training with Keras, Python, and deep learning

A: A kubeflow jupyter notebook is a pod, and a simple training job can scale up to the number of free GPUs you have in one GPU node of your kubernetes cluster.
To scale out your training horizontally and utilize more GPUs in your training job, you need to use a distributed training framework. Kubeflow provides tfjob for that purpose.


text:
Q: how to display or get all names of access database by ID i have like 10 contacts on my database but the ID not Arrangement from 1 to 10 it like 1 2 3 5 6 8.... and im setting a button when click the lll1 is increase like lll1++ and Take lll1 value to ID so it display contacts by click button but when it get to number 4 or 7 for example (1 2 3 5 6 8....)
the form stop and show error that Value Cannot be null is there way to skip number if not have value
also when the ID of database finish like after 10 contacts when i press button and lll1 increase to 11 and database dont have contacts 11 it show same error Value cannot be null , help me plz this important to me thanks
private void button6_Click(object sender, EventArgs e)
{
     OleDbConnection cn = new OleDbConnection();
     cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database9.accdb";
     OleDbCommand cmd = new OleDbCommand();
     cn.Open();
     cmd.Connection = cn;
     cmd.CommandText = "Select * from Contacts where ID=" + lll1.Text;
     OleDbDataReader reader = cmd.ExecuteReader();

     string sql = "select Attachments.FileData from Contacts where ID =" + lll1.Text;
     OleDbCommand vcom = new OleDbCommand(sql, cn);
     byte[] ImageByte = (byte[])vcom.ExecuteScalar(); //contains 20 extra bytes
     MemoryStream MemStream = new MemoryStream(ImageByte.Skip(20).ToArray()); //Read bytes starting at position 20
     Image image = Image.FromStream(MemStream);
     pictureBox1.Image = image;
     while (reader.Read())
     {
         fl1.Text = reader.GetString(reader.GetOrdinal("First Name"));
     }
     cn.Close
}
public int o { get; set; }
private void button5_Click(object sender, EventArgs e)
{
    o++;
    lll1.Text = o.ToString();
    button6_Click(sender, e);
}

  `   string sql = "select Attachments.FileData from Contacts where ID =" +
       lll1.Text;
         if (DBNull.Value.Equals("Attachments.FileData"))
                {
            MessageBox.Show("no value");
                }
         else
                {
            OleDbCommand vcom = new OleDbCommand(sql, cn);
            byte[] ImageByte = (byte[])vcom.ExecuteScalar(); //contains 20
            extra bytes
            MemoryStream MemStream = new
            MemoryStream(ImageByte.Skip(20).ToArray()); //Read byte starting at position 20
            Image image = Image.FromStream(MemStream);
            pictureBox1.Image = image;
            }`

A: You need to check if ExecuteScalar returns NULL.
            var result = vcom.ExecuteScalar(); //contains 20 extra bytes
            if (result != null && result != DBNull.Value)
            {
                byte[] imageByte = result as byte[];

                if (imageByte.Length > 20)
                {
                    using (MemoryStream memStream = new
                        MemoryStream(imageByte.Skip(20).ToArray())) //Read byte starting at position 20
                    {
                        Image image = Image.FromStream(memStream);
                        pictureBox1.Image = image;
                    }
                }
            }
            else
            {
                MessageBox.Show("No image");
            }

Looking at the rest of the code, please consider using object/control names that make sense in the context, like avoiding lll1, button5, buton6 etc.
Read about ExecuteScalar here
Also consider using parameterised SQL queries, read here
Finally, wrap your connection object, cn, in a using statement.


text:
Q: Get and Set Methods in C++ OOP In my computer science class I have an enum value in a header file and I'm having troubles with the get and set functions. I'm quite new to C++. This is part of my header file:
enum class SchoolType {
    Elementary = 1,
    Secondary = 2
};

class School : public Institution
{
    public:
        // There are a couple more values here

    SchoolType GetSchoolType();
    void SetSchoolType(SchoolType typeSchool);
};

And this is part of my .cpp file:
SchoolType GetTypeSchool()
{
    return this->_typeSchool;
}
void SetTypeSchool(SchoolType typeSchool)
{

}

But 'this' brings up an error and says that 'this' may only be used inside a nonstatic member function. How can I get that function to work? My computers teacher told me that that is how I should code the get function but I still don't understand, is there something that I'm doing wrong in the header?

A: For the .cpp file, you should have:
SchoolType School::GetSchoolType() {
    return this->_typeSchool;
}
void School::SetSchoolType(SchoolType typeSchool) {
    // Insert code here...
}

Basically, in C++ you need to specify what class the function is part of (in this case, School) when defining the member functions, or else the compiler doesn't see it as being part of any class. You also need to keep your method names consistent (GetSchoolType vs GetTypeSchool).