text:
Q: Split string into elements of a string array I've got a string with the format of:

blockh->127.0.0.1 testlocal.de->127.0.0.1 testlocal2.com

Now I need to seperate the elements, best way would be a string array I think. I would need to get only these elements seperated:

127.0.0.5 somerandompage.de
127.0.0.1 anotherrandompage.com

How to split and filter the array to get only these elements?
Using the .Filter() Methode doesn't to the job.

A: You can use the string Split method:
 var st = "blockh->127.0.0.1 testlocal.de->127.0.0.1 testlocal2.com";
 var result = st.Split(new [] { "->" }, StringSplitOptions.None);

You can achieve the same with a Regex:
var result = Regex.Split(st, "->");

As a note from @Chris both of these will split the string into an array with 3 elements:

*

*blockh

*127.0.0.1 testlocal.de

*127.0.0.1 testlocal2.com

In case you want to get rid of blockh, you can do a regex match using an IP address and domain regex:
 var ip = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b\s*(([\w][\w\-\.]*)\.)?([\w][\w\-]+)(\.([\w][\w\.]*))");
 var result = ip.Matches(st).Cast<Match>()
        .Select(m => m.Value)
        .ToArray();

This will get only the two elements containing IP addresses.

A: You can use a string Split() method to do that.
var s = "testlocal->testlocal2";
var splitted = s.Split(new[] {"->"}, StringSplitOptions.RemoveEmptyEntries); //result splitted[0]=testlocal, splitted[1]=testlocal2

A: If the simpler versions for splitting a string don't work for you, you will likely be served best by defining a Regular Expression and extracting matches.
That is described in detail in this MSDN article: http://msdn.microsoft.com/en-us/library/ms228595.aspx
For more information on how Regular Expressions can look this page is very helpful: http://regexone.com/


text:
Q: Changing font size based on screen area? I am trying to make it so that when the screen area changes the font will too! I have got it to calculate the font size correctly and have checked with breakpoints. However, fontSize does not change appropriately, for example I run my program on 1300x740 and the fontSize is calculated to be 13 however it will not change the font to that size even though the variable FontSize does equal 13, instead the font is much much smaller than 13. I have tried making a temporary variable Dim fontSize As Integer = 13 and this changed the textbox to the correct size.
Here is my code:
Private Function Resizing()
    Dim totalBaseScreenArea As Double = 1936 * 1100
    Dim totalCurrentScreenArea As Double = Me.Width * Me.Height
    Dim value As Double = totalCurrentScreenArea / totalBaseScreenArea
    Dim fontSize As Integer = Math.Ceiling(txtEnterMP.Font.Size * value)
    txtEnterMP.Font = New Font(txtEnterMP.Font.FontFamily, fontSize, txtEnterMP.Font.Style)
End Function

Any help would be highly appreciated!

A: This solution calculates a new font size based on the size/area of the form. In the designer, add a label called lblFont to a blank form and anchor it to all four corners.
In the code behind, add this code:
Public Class Form1

    Private OriginalFontSize As Single = Me.Font.Size

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Call Resizing()
    End Sub

    Private Sub Form1_ResizeEnd(sender As Object, e As EventArgs) Handles MyBase.ResizeEnd
        Call Resizing()
    End Sub

    Private Sub Resizing()
        Try
            'Get the screen resolution of your monitor (may not be the monitor the program is running on)
            Dim iWidth As Integer = SystemInformation.PrimaryMonitorSize.Width
            Dim iHeight As Integer = SystemInformation.PrimaryMonitorSize.Height

            'Calculate screen area
            Dim totalBaseScreenArea As Double = iWidth * iHeight
            Dim totalCurrentScreenArea As Double = Me.Width * Me.Height

            'Calculate the new font size
            Dim value As Single = (totalCurrentScreenArea / totalBaseScreenArea) * 30
            Dim NewFontSize As Single = Math.Ceiling(OriginalFontSize * value)

            'Stop the font from being super tiny and hard to read
            If NewFontSize < 8 Then NewFontSize = 8

            'Display the new font size
            Me.Text = "Calculated: " & NewFontSize
            Me.Font = New Font(Me.Font.FontFamily, NewFontSize, Me.Font.Style)
            lblFont.Text = "The font size of this label is " & NewFontSize
        Catch Exp As Exception
            lblFont.Text = Exp.Message
        End Try
    End Sub

End Class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting error while opening excel file in Python I am very new to Python, here I'm trying to open an Excel XLS file in Python code but it is showing me some error as below.
Code:
from xlrd import open_workbook
import os.path
wb = open_workbook('K:\NEW_GIS\NEW Data\Garpani_NLRMP_Data\ROR_Files\part-1.xlsx')

I am also following below link for upgrade version:
https://openpyxl.readthedocs.org/en/latest/
Error:
Traceback (most recent call last):

  File "C:/Users/n/.qgis2/python/plugins\Importtool\Import_tool.py", line 327, in select_output_file_5
    workbook = open_workbook(r'K:\NEW_GIS\NEW Data\Garpani_NLRMP_Data\ROR_Files\Part-1.xlsx')

  File "C:\PROGRA~1\QGISWI~1\apps\Python27\lib\site-packages\xlrd\__init__.py", line 429, in open_workbook
    biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)

  File "C:\PROGRA~1\QGISWI~1\apps\Python27\lib\site-packages\xlrd\__init__.py", line 1545, in getbof
    bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])

  File "C:\PROGRA~1\QGISWI~1\apps\Python27\lib\site-packages\xlrd\__init__.py", line 1539, in bof_error
    raise XLRDError('Unsupported format, or corrupt file: ' + msg)

XLRDError: Unsupported format, or corrupt file: Expected BOF record; found 'PK\x03\x04\x14\x00\x06\x00'

A: Excel workbooks carry a considerable amount of formatting that can make them tough to deal with in python. I have found that it is easier to work with tabular data in python using the built-in csv module. In case you aren't familiar, CSV is a standard way to simplify reading & writing of a singular tabular data table.
To export as a CSV open the spreadsheet in Excel and choose 'Save as'. In the 'Save as type' drop-down choose 'CSV (Comma Delimited)'
Once your data is in the CSV format, use the built-in 'csv' module to read it contents.
import csv
csv_file_path = r"..\myData.csv"

with open(csv_file_path, 'r') as csv_file:
    for row in csv.reader(csv_file):
        print row

A: You haven't escaped your backslashes. Try using a raw string by placing the letter 'r' in front of the string.
from xlrd import open_workbook
import os.path
wb = open_workbook(r'K:\NEW_GIS\NEW Data\Garpani_NLRMP_Data\ROR_Files\part-1.xlsx')

A: Your spreadsheet is in Excel 2007+ .xlsx OOXML format. The link in your question is to the openpyxl docs which can read .xlsx but you're not using openpyxl, you're trying to open the .xlsx file with xlrd which only reads the old Excel binary .xls format.
Here is some more information on working with Excel spreadsheets in Python.


text:
Q: Does this Covetous Shen quote have a deeper meaning? After you rescue Covetous Shen from the water way in Act 2, he's pretty chatty. He talks about the architecture at one point stating, "You could walk all the way around the world and never see its like."
Immediately following, he says something very curious, "Except for this part. I've seen this somewhere before."

How intriguing. Is Covetous Shen hinting at something in particular? Could it be a nod at a previous Diablo game? Basically, should the player have any idea what he's talking about?

A:
"Except for this part. I've seen this somewhere before."

This is a hint at the fact that some of the models in the dungeons are reused.  Blizzard is poking fun at themselves here.
The easiest example case is the underbridge zone in act 3 (random side dungeon sometimes accessible from Rakkis Crossing), you'll often see that exact shape appear in the Keep (somewhere between level 1-3)

A: It's actually a throwback to Big Trouble In Little China where the actor was in the sewers near the end of the movie.

A: In reference to architecture, I thought he might be talking about those bearded faces in the sewers you meet him in.  They look almost exactly like the face from Harry Potter: Chamber of Secrets that is in the chamber if you've ever seen the movie.


text:
Q: u-boot flash emmc ttl serial I used to update firmware on embedded system through tools like tftp (with ethernet port or ethernet over usb), sd card  or a simple usb stick.
I am currently working on a system without ethernet port, no usb port. Only a ttl/usb connexion to be able to access the console and a micro usb to supply it. I am currently building a linux image and a rootfs. The storage used on the board is emmc.
Is there a standard way to update linux/rootfs in Emmc, etc.. with u-boot by using a simple ttl/usb connexion ? I guess that I can part my flash in u-boot thanks to mmc command but I don't understand how to transfer my kernel image and my rootfs in emmc with a simple ttl/usb link.

A:
Is there a standard way to update linux/rootfs in Emmc, etc.. with u-boot by using a simple ttl/usb connexion ?

Yes, when only the serial console connection is available, a binary transfer protocol can be employed.  These methods are identical to what is used with phone modems.
A U-Boot command for one transfer method is loadb.
=> help loadb
loadb - load binary file over serial line (kermit mode)

Usage:
loadb [ off ] [ baud ]
    - load binary file over serial line with offset 'off' and baudrate 'baud'
=>

Another U-Boot command for a transfer method is loads for binary data formatted as a Motorola S-record file:
=> help loads
loads - load S-Record file over serial line

Usage:
loads [ off ] [ baud ]
    - load S-Record file over serial line with offset 'off' and baudrate 'baud'
=>

These methods of course require the appropriate sending program on the other end of the serial link, just like tftpboot requires a TFTP server.  A decent terminal emulator program, such as Minicom or TeraTerm, can perform the PC side of these transfers.  Note that it's the sender that determines the file to transfer; the U-Boot side cannot request the file by name but only receives it.
If these commands are not already available in your U-Boot, then you'll have to edit the configuration and rebuild U-Boot.


text:
Q: Samba issue local folders replaced my mount point I have a permissions issue with a samba mount to a Windows 10 box. I am trailing FileMaker Server 19 on CentOS and want to backup the DBs to a samba mount point.
using:
mount -t cifs -o username=myname,password=mypassword //192.168.1.128/fmsbackup "/opt/FileMaker/FileMaker Server/Data/Backups"

//192.168.1.128/fmsbackup is the mount point on the Windows 10 box
/opt/FileMaker/FileMaker Server/Data/Backups is the location of the database backups
There is one folder in fmsbackup.
before running the mount command the FileMaker Backups folder contains the DBs backed up.
After running the mount command the FileMaker Backups folder contains the contents of fmsbackup
When I unmount the share point all is back as it should be.
Any tips on where I am going wrong?


text:
Q: How do you iterate and apply logic to rows in DataGrid So I am trying to add a timer into a new column "Duration" that subtracts the time started, which is a date time, and displays how long it has been active. So far this is what I have:
XAML:
<DataGridTextColumn Binding="{Binding BlockName}" Header="Block" Width="200"/>
<DataGridTextColumn Binding="{Binding Auditor}" Header="Auditor" Width="200"/>
<DataGridTextColumn Binding="{Binding AcctAuditor}" Header="Accounting Auditor" Width="200"/>
<DataGridTextColumn Binding="{Binding BlockLeader}" Header="Block Leader" Width="200"/>
<DataGridTextColumn x:Name="TimeStarted" Binding="{Binding TimeStarted}" Header="Started" Width="200"/>
<DataGridTextColumn x:Name="Duration" Header="Elapsed Time" Width="200"/>

Code Behind:
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    foreach (DataRowView dr in BlockStatus.ItemsSource)
        {
        var diff = dr.Row.Field<DateTime>("TimeStarted").Subtract(DateTime.Now);
        if (diff.TotalSeconds > 0)
        {
            dr.Row["Duration"] = string.Format("{0} d {1:D2}:{2:D2}:{3:D2}", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);
        }
        else
        {
            dr.Row["Duration"] = "0 d 00:00:00";
        }
    }
}

I am trying to have a column that will count up in mm:ss in a new column based on another column.
Here is a picture:

This was solved using dispatch timer.


text:
Q: Cannot pass custom result from resolver to Graphql I am trying to fetch data with sequelize with an attribute and pass it to graphql.
The result is fine in console but the graphql query is returning null for the attribute field.
my resolver
    getUnpayedLessons: async (_, args, { models }) => {
  const { Attendance, Student } = models;
  return await Attendance.findAll({
    include: {
      model: Student,
    },
    where: {
      fk_lessonsSerieId: { [Op.is]: null },
    },
    attributes: ["id", [sequelize.fn("count", sequelize.col("absenceFlag")), "unpayedLessons"]],
    group: ["student.id"],
  });
},

query
getUnpayedLessons {
  id
  unpayedLessons
  student {
    id
    firstName
    lastName
  }
}

schema
type UnpayedLessons {
  id: Int
  unpayedLessons: Int
  student: Student
  }

extend type Query {
  getUnpayedLessons: [UnpayedLessons]
  }

and this is the console.log of the resolver when I run the query
    [
   attendance {
    dataValues: { id: 2, unpayedLessons: 8, student: [student] },
    _previousDataValues: { id: 2, unpayedLessons: 8, student: [student] },
    _changed: Set {},
    _options: {
      isNewRecord: false,
     _schema: null,
     _schemaDelimiter: '',
      include: [Array],
      includeNames: [Array],
      includeMap: [Object],
      includeValidated: true,
      attributes: [Array],
      raw: true
     },
]

and from graphql
    {
  "data": {
    "getUnpayedLessons": [
      {
        "id": 2,
        "unpayedLessons": null,
        "student": {
          "id": 2,
          "__typename": "Student"
        },
        "__typename": "UnpayedLessons"
      },
     ]
    }
   }

Any idea how I can have unpayedLessons passed to graphql?

A: To debug this you need to check what is returned from DB, the shape:
const values = await Attendance.findAll({...
console.log( values );
// adapt structure to match query requirements
// finally return
return values;


text:
Q: What is the correct method for class import in multiple project solution The solution consists of a Main project containing a main.cpp file and a separate Shape project consisting of a Shape.h and Shape.cpp.
When I define a class function inline in the header file and reference it in the main file the code executes, however defining it in a separate .cpp file results in LNK1120 and LNK2019 errors.
The folder structure is as follows:
+-- MainProj
|   +-- main.cpp
+-- Shape
|   +-- Shape.h
|   +-- Shape.cpp

I have tried adding the path containing Shape.cpp to includes directory but the issue persists.
main.cpp
#include <iostream>
#include "Shape/Shape.h"

using namespace std;

void main()
{
    Shape s(2, 3);
    cout << s.Area() << endl;
}

The following code works.
Shape.h
#pragma once
class Shape
{
public:
    Shape(float l, float w) : length(l), width(w)
    {
    }

    float Area()
    {
        return length * width;
    }
protected:
    float length;
    float width;
};

The following code results in the link errors below.
Shape.h
#pragma once
class Shape
{
public:
    Shape(float l, float w);
    float Area();
protected:
    float length;
    float width;
};

Shape.cpp
#include "Shape.h"

Shape::Shape(float l, float w) : length(l), width(w)
{
}
float Shape::Area()
{
    return length * width;
}

Severity    Code    Description Project File    Line    Suppression State
Error   LNK1120 2 unresolved externals  Main    C:\CPP\Main\x64\Debug\Main.exe  1
Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "public: float __cdecl Shape::Area(void)" (?Area@Shape@@QEAAMXZ) referenced in function main MainProj    C:\CPP\MainProj\main.obj    1
Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "public: __cdecl Shape::Shape(float,float)" (??0Shape@@QEAA@MM@Z) referenced in function main    MainProj    C:\CPP\MainProj\main.obj    1


text:
Q: terminate called after throwing an instance of 'std::length_error' what(): basic_string::_M_create The problem is to reverse words in a string ...
Eg. - This is Nice
Output -Nice is This

so here's the error
terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_M_create

Here's my actual code, don't know where it went wrong I just started c++, but I'm sure I'm trying to access an index that isn't defined. Pls correct me if I'm wrong
string reverseWords(string s) {
        vector<string> v;
        string x="";
        for(int i=0;i<s.size();i++)
        {
            if(isspace(s[i]))
            {
                v.push_back(x);
                x="";
                v.push_back(" ");

            }
            else
            {
                x=x+s[i];
            }
        }
        v.push_back(x);
        x="";
        for(int j=v.size();j>=0;j--) x=x+v[j];
        return x;
    }

A: Your approach is inefficient.
Also you are not reversing the source string but building a new string in the reversed order.
The compound statement of the if statement
if(isspace(s[i]))
{
    v.push_back(x);
    x="";
    v.push_back(" ");

}

does not make great sense when the source string contains adjacent spaces because it appends empty strings to the vector.
Also if the last character of the string is space then this statement after the for loop
v.push_back(x);

again appends a redundant empty string to the vector.
This for loop
for(int j=v.size();j>=0;j--) x=x+v[j];

invokes undefined behavior when j is equal to v.size().
If you are dealing with an object of the type std::string then you should use methods of the class and standard algorithms as for example the algorithm std::reverse.
Here is a demonstration program that shows how a string can be reversed.
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

std::string & reverseWords( std::string &s, const char *delim = " \t" )
{
    auto first = s.find_first_not_of( delim );

    if (first != std::string::npos)
    {
        auto last = s.find_last_not_of( delim ) + 1;

        std::reverse( std::next( std::begin( s ), first ), std::next( std::begin( s ), last ) );

        while ( first != last )
        {
            auto pos = s.find_first_of( delim, first );

            if (pos == std::string::npos) pos = last;

            std::reverse( std::next( std::begin( s ), first ),
                std::next( std::begin( s ), pos ) );

            first = pos;

            if ( first != last ) first = s.find_first_not_of( delim, first );
        }
    }

    return s;
}

int main()
{
    std::string s( "The quick brown fox jumps over the lazy dog" );

    std::cout << s << '\n';
    std::cout << reverseWords( s ) << '\n';
}

The program output is
The quick brown fox jumps over the lazy dog
dog lazy the over jumps fox brown quick The


text:
Q: Is there a way to track clicks on my Google Adsense ads? I have a page with Google Adsense ads. Is there any way to track when a user clicks on one of these these ads?
I thought about adding a javascript onclick of some sort, perhaps one that logs the click and then passes on to the ad. But I'm not sure how this would work, is it possible?
Thanks for any assistance!
dylan


text:
Q: constructing future coupon payment dates for bonds I have a Problem and would be very grateful if you could help me.
starting Situation:

*

*Bonds: "026351AZ9" "026351BC9"

*First Coupon Date of These Bonds: "2029-02-15" "2010-09-11" (class date)

*Count of the years where the bonds pay coupons: 3 years and 1 years

*each years has also a Coupon frequency: 2 and 4, that means that during the next year there will be 2 payments (4 payments)

First case: 3 years and each year 2 times Coupon payment -> so every 6 month Coupon payment for the next 3 years. Same with 1 year and 4 times coupn payment.
Result:
It should be look like this:
datesBond1 = "2029-02-15" "2029-08-15" "2030-02-15" "2030-08-15" "2031-02-15" "2031-08-15"
datesBond2 = "2010-09-11" "2010-12-11" "2010-03-11" "2010-06-11"
This is just a sample. In my case I have a lot more ISINS, Dates, and various years and Coupon frequencies.
Thank you

A: You can use the months function to contruct future coupon payments dates and wrap the calculation in a
custom function that could be accessed for individual bonds.
There is typo in your expected output for bond 2 where last two values should correspond to year 2011.
fn_cpnPayDates = function(cpnStartDt = as.Date("2029-02-15"),numYears = 3, freq = 6) {

# number of coupon payments per year
numPayPerYear = 12 / freq

#total payments
numPayments = numYears * numPayPerYear

cpnDatesAll = rep(cpnStartDt, numPayments)

for(i in 1:numPayments) cpnDatesAll[i] = cpnDatesAll[i] + months((i-1)* freq)

return(cpnDatesAll)

}

datesBond1 = fn_cpnPayDates(cpnStartDt = as.Date("2029-02-15"),numYears = 3, freq = 6)
datesBond1
#[1] "2029-02-15" "2029-08-15" "2030-02-15" "2030-08-15" "2031-02-15" "2031-08-15"

datesBond2 = fn_cpnPayDates(cpnStartDt = as.Date("2010-09-11"),numYears = 1, freq = 3)
datesBond2
#[1] "2010-09-11" "2010-12-11" "2011-03-11" "2011-06-11"


text:
Q: Magic Line CSS/Javascript code - Adding sub navigation I am implementing this "Magic Line" code into my navigation menu, but I seem to be having troubles when adding a sub menu. When you hover over any sub menu items, the magic line shoots all the way to the left side of the page. I would like it to stay on the menu item that the submenus are under.
You can view my site here: http://www.christmaslightsinstallation.ca/
Original script (without sub nav): http://css-tricks.com/examples/MagicLine/
(I tried a fiddle for this, but since it's in wordpress it wasn't translating very well)
My javascript is as follows:
$(function() {

var $el, leftPos, newWidth,
    $mainNav = $("#menu-main-menu");

$testing = $(".menu-header");

$testing.append("");
var $magicLine = $("#magic-line");

$magicLine
    .width($(".current_page_item").width())
    .css("left", $(".current_page_item a").position().left)
    .data("origLeft", $magicLine.position().left)
    .data("origWidth", $magicLine.width());

$("#menu-main-menu li a").hover(function() {
    $el = $(this);
    leftPos = $el.position().left;
    newWidth = $el.parent().width();
    $magicLine.stop().animate({
        left: leftPos,
        width: newWidth
    });
}, function() {
    $magicLine.stop().animate({
        left: $magicLine.data("origLeft"),
        width: $magicLine.data("origWidth")
    });
});
});

I tried creating a second hover function using "#menu-main-menu li li a", and trying to use a "preventdefault();" event. Which just caused a ton of errors.
I'm fairly new to javascript, so limited on things I can think of/know how to do, to try a fix for this.

A: $("#menu-main-menu li a").hover(function() {
Change the above line to:
$("#menu-main-menu > li").hover(function() {
Edit:
Also change:
newWidth = $el.parent().width();

to:
newWidth = $el.width();


text:
Q: SSL Error and Google_IO_Exception in just 1 program So I have a script that was a cronjob and worked for 7 months already. It uploads a 300ish MB file, and has never failed until a week ago. The error that pops out is:
    Uncaught exception 'Google_IO_Exception' with message 'error:1409442E:SSL rou$
Stack trace:
#0 /libs/src/Google/IO/Abstract.php(136): Google_IO_Curl->executeRequest(Object(Google_Http_Request))
#1 /libs/src/Google/Auth/OAuth2.php(342): Google_IO_Abstract->makeRequest(Object(Google_Http_Request))
#2 /libs/src/Google/Auth/OAuth2.php(278): Google_Auth_OAuth2->refreshTokenRequest(Array)
#3 /root/scriptEnCrontab/libs/src/Google/Client.php(457): Google_Auth_OAuth2->refreshToken('TOKEN...')
#4 /root/scriptEnCrontab/respaldoDrive.php(61): Google_Client->refreshToken('TOKEN...')
#5 {main}
  thrown in /root/scriptEnCrontab/libs/src/Google/IO/Curl.php on line 115

I can't seem to find information about that SSL Error or how to solve it. I don't think is the token the problem or the script as it has been working for a long time already. Is it the server? Other scripts that I have still work and using the same auth and credentials that this script uses. Any help is appreciated.

A: I solved it. Apparently it was a problem with the SSLVERSION in the Curl.php. I haven't updated my api library from google on a while so that might have been solved in another iteration. Here's the line I changed
ORIGINAL: curl_setopt($curl, CURLOPT_SSLVERSION, 3);

CHANGED: curl_setopt($curl, CURLOPT_SSLVERSION, 1);


text:
Q: How to convert Hexadecimal NSData to Decimal array? I have an array with hexadecimal value like below:
const UInt8 request_MifareID[] = {
        0x00, 0xCA, 0x01, 0x0A, 0x00
    };

then i transfer it to NSData for communication:
NSData *data = [[NSData alloc] initWithBytesNoCopy:(UInt8 *)request_MifareID length:5];

Sent "data" to server and get the server response:
Printing description of resp:
<ee97562d 02280400 00000000 21074400 9000>

NSUInteger len = [resp length];

Printing description of len:
(NSUInteger) len = 18

the "resp" is also a Hexadecimal format NSData
now, i have to transfer the "resp" to Decimal array
how should i do?
------------------------------------------------------Edit
Ok, first
i have to transfer the NSData which server response(it is not String, just numbers):
ee97562d 02280400 00000000 21074400 9000

into what kind of object?
Byte?
when i use
NSString * str = [[NSString alloc] initWithData: resp
                                           encoding:NSUTF8StringEncoding];

it returns nil

A: int number = 0xe; // or 0x3, 0x6, 0x8, 0x2

NSString * decimalString = [NSString stringWithFormat:@"%d", number];
NSString * hexString = [NSString stringWithFormat:@"%x", number];

A: **NSData *data = [NSData dataWithBytes:"FF3C" length:4];
NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
string = [@"0x" stringByAppendingString:string];

unsigned short value;
sscanf([string UTF8String], "%hx", &value);

NSLog(@"%d", value)**


text:
Q: Which kind of STL should I use for this task? I need a queue that must add/remove some structs I have, such as:
struct MyObject
{
  int offset;
  BYTE status, data1, data2;
  double beatPos;

  enum Status
  {
    isOff = 8,
    isOn = 9,
  };
}

When I .Add() an element, this queue must put the element at the correct position, due to the beatPos value, which must be ordered from the lower (top of the queue, i.e. the next element I'll pop) to the upper (the last element I'll extract from it).
I see there is std::priority_queue, but I'm not sure if I can select which is the field for the ordering.
Also, once I add some structs in the list, I'd like to remove the first element that have (for example) beatPos=1,567 (which could be in the middle of the list, for example; not necessarily at the beginning).
Any clues?

A: What you want is a std::multiset.  It takes a compare template parameter and it is defaulted to std::less for the type the container is going to store but you can specify a different comparator.  To do that we can create a lambda that will compare two MyObjects and return which object should have a higher priority based on the beatPos member
auto my_compare = [](const MyObject & lhs, const MyObject & rhs)
                    {
                        return lhs.beatPos < rhs.beatPos;
                    }

And then we can use that like
std::multiset<MyObject, decltype(my_compare)> data(my_compare);

This will give you an ordered container that can store multiple objects with the same beatPos and allow you access into the middle of the container.

A: You can use std::multiset with a user-defined comparator.  For example:
bool MyObjectComp(const MyObject& lhs, const MyObject& rhs) {
    return lhs.beatPos < rhs.beatPos;
}

typedef std::set<MyObject, MyObjectComp> MyObjectSet;

Now the ordering within MyObjectSet is always from lowest to highest beatPos.  You can search using lower_bound() and upper_bound(), and you can get the smallest value using begin().
Note that due to the nature of double values (IEEE floating point), exact comparison may not work, so you can't necessarily say mySet.find(0.5) but you can say mySet.upper_bound(0.49999).
The same user-defined comparator can be used for priority_queue as well, but that container does not support searching for an element by value, which is one of your requirements.


text:
Q: MySQL join with one table. List values with a where clause, then list values beneath I am writing a small script for a bit of fun and to learn a little more about PHP/MySQL and I have come to a dead end with generating the menu. My intention is to generate a CSS styled dropdown menu where you hover over the menu items and then a list of sub pages is displayed beneath.
The pages in my script are stored in a MySQL table named 'pages'. Here is an example of the MySQL.
---------------------------------------------------------------------------------
id   title         linkText    menu       pageContent
1    Home          Home        top        This is my home page.
2    Projects      Projects    top        This page is a list of my projects
3    Music         Music       Projects   This page is about my music
4    Photography   Photos      Projects   This page has photography work
5    Art & Craft   Artwork     Projects   This page is all about art and craft work
6    Contact Me    Contact     top        Send me a message

What I would like to be able to do with the MySQL statement is to list the items where the 'menu' field equals 'top' which would be simple.
SELECT title, linkText, menu FROM pages WHERE menu = 'top'

But the part I am stuck on is listing the top items then below each top item list the sub items to give an output like so.
Home
Projects
--Music
--Photos
--Artwork
Contact

I imagine this would be done with a mysql join, but after trying many different combinations and following a bundle of examples I can't seem to get it working.
Any help is much appreciated.
Thank you

A: If you want an answer in PHP I can give you :
try
{
  $bdd = new PDO('mysql:host=localhost;dbname=cours', 'root', 'root');
}
catch(Exception $e)
{
  die('Erreur : '.$e->getMessage());
}

$answer = $bdd->query('SELECT linkText FROM stack WHERE menu = \'top\'');

while ($data = $answer->fetch())
{
  echo $data['linkText'] . "
 \n";
  $answer2 = $bdd->prepare('SELECT linkText FROM stack WHERE menu = ?');
  $answer2->execute(array($data['linkText']));
  while ($data2 = $answer2->fetch())
  {
    echo "--" . $data2['linkText'] . "
 \n";
  }
  $answer2->closeCursor();
}
$answer->closeCursor();

Which gave me the result HTML :
Home

Projects

--Music

--Photos

--Artwork

Contact

A: You can do it like this:
<?php
// SQL for creating database
/*
 CREATE TABLE `menu` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `linkText` varchar(255) NOT NULL,
  `menu` varchar(255) NOT NULL,
  `pageContent` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
*/

class Menu {
    /**
     * @var PDO
     */
    private $_dbh;

    /**
     * Constructor
     *
     * @param PDO $dbh database connection
     */
    public function __construct(PDO $dbh){
        $this->_dbh = $dbh;
    }

    /**
     * Get menu
     *
     * @return array
     */
    public function getMenu(){
        return $this->getTree($this->getTop());
    }

    /**
     * Get top menu
     *
     * @return array
     */
    private function getTop(){
        return $this->_dbh->query("SELECT * FROM menu WHERE menu = 'top'")->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get children menu for specified parent menu
     *
     * @param array $menu
     * @return array
     */
    private function getChildren(array $menu){
        $stmt = $this->_dbh->prepare("SELECT * FROM menu WHERE menu = :menu");
        $stmt->bindParam(':menu', $menu['linkText']);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get menu tree
     *
     * @param array $parents parent menus
     * @param array $tree tree representing menu
     * @return array
     */
    private function getTree(array $parents, array $tree = array()){
        foreach ($parents as $parent){
            $tree[$parent['id']] = $parent;
            $children = $this->getChildren($parent);

            if (!empty($children)){
                $parent['children'] = $children;
                $tree[$parent['id']] = $parent;
                $this->getTree($children, $tree);
            }
        }

        return $tree;
    }
}

$dbh = new PDO('mysql:host=localhost;dbname=stackoverflow', 'root', 'root');
$menu = new Menu($dbh);

echo '
'; print_r($menu->getMenu());

Result is a tree (implemented by array) representing whole menu structure:
Array
(
    [1] => Array
        (
            [id] => 1
            [title] => Home
            [linkText] => Home
            [menu] => top
            [pageContent] => This is my home page.
        )

    [2] => Array
        (
            [id] => 2
            [title] => Projects
            [linkText] => Projects
            [menu] => top
            [pageContent] => This page is a list of my projects
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [title] => Music
                            [linkText] => Music
                            [menu] => Projects
                            [pageContent] => This page is about my music
                        )

                    [1] => Array
                        (
                            [id] => 4
                            [title] => Photography
                            [linkText] => Photos
                            [menu] => Projects
                            [pageContent] => This page has photography work
                        )

                    [2] => Array
                        (
                            [id] => 5
                            [title] => Art & Craft
                            [linkText] => Artwork
                            [menu] => Projects
                            [pageContent] => This page is all about art and craft work
                        )

                )

        )

    [6] => Array
        (
            [id] => 6
            [title] => Contact Me
            [linkText] => Contact
            [menu] => top
            [pageContent] => Send me a message
        )

)

You can find the code here as well: http://pastebin.com/NcmrJmY3


text:
Q: How to Create Login query with android orm? I need to create a login page with Android Studio and my question is how to
create login query with Suger ORM? Please answer me just with orm (netter answer me with Suger ORM but is not different in other orms) because I know how to create login query with SQLite database. Thanks everyone and sorry for bad English :)
    Suger.findWithQuery(User.class, "SELECT user_name and password from suger where " + "user_name= ? AND password= ?", name, pass);

This my Code!!!
i create Method and my Method return The true;
i sayd in clicklistener button if this method return a true Toast to me (Successful) else  sayd to me show Failed!!
But is my problem its is always for any typing in edit text The Toast is show successful !!!!
the field name and pass i get the text from two edit text

A: Welcome to SO, Ali!
Since you have not provided enough information about your question I'm going to assume that you are familiar with android enough to create an activity, having two edittext in it and a login button,
so on the onClickListener event of the login button you need to query your database for the provided Login info (say email address as user name). following snippet is a simple way to query a table in Sugar Orm
List<User> users = User.findWithQuery(User.class,"SELECT * FROM USER WHERE email = ?",email);

obviously users may have zero length which means no user exists with this email or one member which is your user, now you need to verify the password, preferably stored using a hash algorithm.
moreover, I would like to mention Android Room which is a component from Android Arch Components , an orm designed by Android team which is simpler than other ORMs and have great benefits such as being Lifecycle aware.


text:
Q: How to parse a string received via a get request using form2Json? I get the error

SyntaxError: Unexpected token: in JSON at position 5759 (line 42)

on the first request, and on the second everything is fine, what could be the problem and how can it be solved?
function myFunction() {
var one = "leads%5Bupdate%5D%5B0%5D%5Bid%5D=30896454&leads%5Bupdate%5D%5B0%5D%5Bname%5D=%D0%94%D0%B0%D1%80%D1%8C%D1%8F+%28%D0%90%D0%BB%D0%B8%D0%BD%D0%B0%29+23.11.2021+12%3A30&leads%5Bupdate%5D%5B0%5D%5Bstatus_id%5D=33131353&leads%5Bupdate%5D%5B0%5D%5Bold_status_id%5D=33131347&leads%5Bupdate%5D%5B0%5D%5Bprice%5D=0&leads%5Bupdate%5D%5B0%5D%5Bresponsible_user_id%5D=7490283&leads%5Bupdate%5D%5B0%5D%5Blast_modified%5D=1637662097&leads%5Bupdate%5D%5B0%5D%5Bmodified_user_id%5D=0&leads%5Bupdate%5D%5B0%5D%5Bcreated_user_id%5D=0&leads%5Bupdate%5D%5B0%5D%5Bdate_create%5D=1636435650&leads%5Bupdate%5D%5B0%5D%5Bpipeline_id%5D=1635139&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B0%5D%5Bid%5D=451580&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B0%5D%5Bname%5D=tilda&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B1%5D%5Bid%5D=469607&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B1%5D%5Bname%5D=%D0%92%D0%B2%D0%BE%D0%B4%D0%BD%D0%BE%D0%B5&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B2%5D%5Bid%5D=475269&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B2%5D%5Bname%5D=%D0%9F%D0%B0%D1%80%D1%82%D0%BD%D0%B5%D1%80%D0%BA%D0%B0&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B3%5D%5Bid%5D=476169&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B3%5D%5Bname%5D=%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD-%D0%B7%D0%B0%D0%BD%D1%8F%D1%82%D0%B8%D1%8F&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B4%5D%5Bid%5D=480372&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B4%5D%5Bname%5D=%D0%92%D0%A3&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B5%5D%5Bid%5D=483228&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B5%5D%5Bname%5D=%D0%90%D0%BA%D1%86%D0%B8%D1%8F+%2B2&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B6%5D%5Bid%5D=485614&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B6%5D%5Bname%5D=%D0%9E%D1%82%D0%BA%D0%BB%D0%B0%D0%B4%D1%8B%D0%B2%D0%B0%D1%8E%D1%82&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B7%5D%5Bid%5D=486524&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B7%5D%5Bname%5D=%D0%97%D0%B2%D1%83%D0%BA+%C2%AB%D0%9B%C2%BB&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B8%5D%5Bid%5D=486530&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B8%5D%5Bname%5D=%D0%9B%D0%BE%D0%B3%D0%BE%D0%BF%D0%B5%D0%B4%D0%B8%D1%8F&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B9%5D%5Bid%5D=487240&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B9%5D%5Bname%5D=%D0%9F%D0%9A&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B10%5D%5Bid%5D=490756&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B10%5D%5Bname%5D=%D0%A7%D1%82%D0%B5%D0%BD%D0%B8%D0%B5&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B11%5D%5Bid%5D=493262&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B11%5D%5Bname%5D=%D0%BD%D0%B5%D0%B4%D0%B5%D0%BB%D1%8F+%D0%B2+%D0%BF%D0%BE%D0%B4%D0%B0%D1%80%D0%BE%D0%BA&leads%5Bupdate%5D%5B0%5D%5Baccount_id%5D=24809335&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bid%5D=683303&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bname%5D=utm_referrer&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bcode%5D=UTM_REFERRER&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B1%5D%5Bid%5D=681646&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B1%5D%5Bname%5D=%D0%A1%D0%BE%D1%82%D1%80%D1%83%D0%B4%D0%BD%D0%B8%D0%BA%2C+Yclients&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B1%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=%D0%93%D0%B0%D0%B2%D1%80%D0%B8%D1%87%D0%B5%D0%BD%D0%BA%D0%BE+%D0%94%D0%B0%D1%80%D1%8C%D1%8F&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B2%5D%5Bid%5D=681648&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B2%5D%5Bname%5D=%D0%94%D0%BB%D0%B8%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C+%D0%BF%D1%80%D0%BE%D1%86%D0%B5%D0%B4%D1%83%D1%80%D1%8B%2C+Yclients&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B2%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=45+%D0%BC%D0%B8%D0%BD.&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B3%5D%5Bid%5D=928932&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B3%5D%5Bname%5D=%D0%9C%D0%B5%D0%BD%D0%B5%D0%B4%D0%B6%D0%B5%D1%80+1+%D0%BB%D0%B8%D0%BD%D0%B8%D0%B8&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B3%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=%D0%93%D1%83%D1%81%D0%B5%D0%B2%D0%B0+%D0%9D%D0%B0%D1%82%D0%B0%D0%BB%D0%B8%D1%8F&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B3%5D%5Bvalues%5D%5B0%5D%5Benum%5D=4204978&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B4%5D%5Bid%5D=678201&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B4%5D%5Bname%5D=%D0%A0%D0%B5%D0%B3%D0%B8%D0%BE%D0%BD&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B4%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=%D0%A2%D0%B2%D0%B5%D1%80%D1%81%D0%BA%D0%B0%D1%8F+%D0%BE%D0%B1%D0%BB%D0%B0%D1%81%D1%82%D1%8C&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B5%5D%5Bid%5D=913962&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B5%5D%5Bname%5D=%D0%92%D0%BE%D0%B7%D1%80%D0%B0%D1%81%D1%82+%D1%80%D0%B5%D0%B1%D0%B5%D0%BD%D0%BA%D0%B0&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B5%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=6&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B5%5D%5Bvalues%5D%5B0%5D%5Benum%5D=4198694&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B6%5D%5Bid%5D=681336&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B6%5D%5Bname%5D=%D0%9E%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD+%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D0%B8&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B6%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=%D0%97%D0%B2%D1%83%D0%BA%D0%BE%D0%BF%D1%80%D0%BE%D0%B8%D0%B7%D0%BD%D0%BE%D1%88%D0%B5%D0%BD%D0%B8%D0%B5&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B6%5D%5Bvalues%5D%5B0%5D%5Benum%5D=4188232&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B7%5D%5Bid%5D=673089&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B7%5D%5Bname%5D=ID+%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B8%2C+Yclients&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B7%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=290330-375075392&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B8%5D%5Bid%5D=673093&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B8%5D%5Bname%5D=%D0%94%D0%B0%D1%82%D0%B0+%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B8%2C+Yclients&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B8%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=23.11.2021&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B9%5D%5Bid%5D=673091&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B9%5D%5Bname%5D=%D0%92%D1%80%D0%B5%D0%BC%D1%8F+%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B8%2C+Yclients&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B9%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=12%3A30&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B10%5D%5Bid%5D=928936&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B10%5D%5Bname%5D=%D0%A2%D1%80%D0%B5%D0%B1%D1%83%D0%B5%D1%82+%D0%B4%D0%BE%D0%B7%D0%B2%D0%BE%D0%BD%D0%B0+%28%D0%A2%29&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B10%5D%5Bvalues%5D%5B0%5D=1636405200&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B11%5D%5Bid%5D=928940&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B11%5D%5Bname%5D=%D0%9F%D0%BE%D0%B4%D1%82%D0%B2%D0%B5%D1%80%D0%B4%D0%B8%D0%BB%D0%B8+%D0%92%D0%A3+%28%D0%A2%29&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B11%5D%5Bvalues%5D%5B0%5D=1637528400&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B12%5D%5Bid%5D=928942&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B12%5D%5Bname%5D=%D0%97%D0%B0%D0%BD%D1%8F%D1%82%D0%B8%D0%B5+%D0%BF%D1%80%D0%BE%D1%88%D0%BB%D0%BE+%28%D0%A2%29&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B12%5D%5Bvalues%5D%5B0%5D=1637614800&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B13%5D%5Bid%5D=928944&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B13%5D%5Bname%5D=%D0%97%D0%B0%D0%BF%D0%B8%D1%81%D0%B0%D0%BD+%D0%BD%D0%B0+%D0%BF%D1%80%D0%BE%D0%B1%D0%BD%D0%BE%D0%B5+%28%D0%A2%29&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B13%5D%5Bvalues%5D%5B0%5D=1636405200&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B14%5D%5Bid%5D=670612&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B14%5D%5Bname%5D=REFERER&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B14%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=https%3A%2F%2Fmylogoped.online%2Freading%3Futm_source%3Dblogger%26amp%3Butm_campaign%3Ddaria_moguchaya%26amp%3Butm_medium%3Drg%23rec319161715&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B15%5D%5Bid%5D=680880&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B15%5D%5Bname%5D=FORMNAME&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B15%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=%D1%84%D0%BE%D1%80%D0%BC%D0%B0&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B15%5D%5Bcode%5D=FORMNAME&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B16%5D%5Bid%5D=671845&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B16%5D%5Bname%5D=UTM_SOURCE&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B16%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=blogger&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B17%5D%5Bid%5D=671847&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B17%5D%5Bname%5D=UTM_MEDIUM&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B17%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=rg&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B18%5D%5Bid%5D=671849&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B18%5D%5Bname%5D=UTM_CAMPAIGN&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B18%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=daria_moguchaya&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B19%5D%5Bid%5D=670608&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B19%5D%5Bname%5D=TRANID&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B19%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=2225828%3A2655884701&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B20%5D%5Bid%5D=670610&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B20%5D%5Bname%5D=FORMID&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B20%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=form319161715&leads%5Bupdate%5D%5B0%5D%5Bcreated_at%5D=1636435650&leads%5Bupdate%5D%5B0%5D%5Bupdated_at%5D=1637662097&account%5Bsubdomain%5D=mylogoped&account%5Bid%5D=24809335&account%5B_links%5D%5Bself%5D=https%3A%2F%2Fmylogoped.amocrm.ru";
var two = "leads%5Bupdate%5D%5B0%5D%5Bid%5D=30983426&leads%5Bupdate%5D%5B0%5D%5Bname%5D=Lead+from%3A+https%3A%2F%2Fmylogoped.online%2F%23rec367114784&leads%5Bupdate%5D%5B0%5D%5Bstatus_id%5D=24809344&leads%5Bupdate%5D%5B0%5D%5Bprice%5D=0&leads%5Bupdate%5D%5B0%5D%5Bresponsible_user_id%5D=7420479&leads%5Bupdate%5D%5B0%5D%5Blast_modified%5D=1637662184&leads%5Bupdate%5D%5B0%5D%5Bmodified_user_id%5D=7420479&leads%5Bupdate%5D%5B0%5D%5Bcreated_user_id%5D=0&leads%5Bupdate%5D%5B0%5D%5Bdate_create%5D=1637661669&leads%5Bupdate%5D%5B0%5D%5Bpipeline_id%5D=1635139&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B0%5D%5Bid%5D=451580&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B0%5D%5Bname%5D=tilda&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B1%5D%5Bid%5D=475269&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B1%5D%5Bname%5D=%D0%9F%D0%B0%D1%80%D1%82%D0%BD%D0%B5%D1%80%D0%BA%D0%B0&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B2%5D%5Bid%5D=476169&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B2%5D%5Bname%5D=%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD-%D0%B7%D0%B0%D0%BD%D1%8F%D1%82%D0%B8%D1%8F&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B3%5D%5Bid%5D=483228&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B3%5D%5Bname%5D=%D0%90%D0%BA%D1%86%D0%B8%D1%8F+%2B2&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B4%5D%5Bid%5D=493262&leads%5Bupdate%5D%5B0%5D%5Btags%5D%5B4%5D%5Bname%5D=%D0%BD%D0%B5%D0%B4%D0%B5%D0%BB%D1%8F+%D0%B2+%D0%BF%D0%BE%D0%B4%D0%B0%D1%80%D0%BE%D0%BA&leads%5Bupdate%5D%5B0%5D%5Baccount_id%5D=24809335&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bid%5D=683303&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bname%5D=utm_referrer&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B0%5D%5Bcode%5D=UTM_REFERRER&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B1%5D%5Bid%5D=928932&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B1%5D%5Bname%5D=%D0%9C%D0%B5%D0%BD%D0%B5%D0%B4%D0%B6%D0%B5%D1%80+1+%D0%BB%D0%B8%D0%BD%D0%B8%D0%B8&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B1%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=%D0%9A%D1%80%D1%83%D1%82%D0%BE%D0%B2%D0%B0+%D0%AF%D0%BD%D0%B0&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B1%5D%5Bvalues%5D%5B0%5D%5Benum%5D=4205136&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B2%5D%5Bid%5D=681336&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B2%5D%5Bname%5D=%D0%9E%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD+%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D0%B8&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B2%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=%D0%97%D0%B2%D1%83%D0%BA%D0%BE%D0%BF%D1%80%D0%BE%D0%B8%D0%B7%D0%BD%D0%BE%D1%88%D0%B5%D0%BD%D0%B8%D0%B5&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B2%5D%5Bvalues%5D%5B0%5D%5Benum%5D=4188232&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B3%5D%5Bid%5D=670612&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B3%5D%5Bname%5D=REFERER&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B3%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=https%3A%2F%2Fmylogoped.online%2F%23rec367114784&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B4%5D%5Bid%5D=670608&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B4%5D%5Bname%5D=TRANID&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B4%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=2225828%3A2723274121&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B5%5D%5Bid%5D=670610&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B5%5D%5Bname%5D=FORMID&leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B5%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=form367114784&leads%5Bupdate%5D%5B0%5D%5Bcreated_at%5D=1637661669&leads%5Bupdate%5D%5B0%5D%5Bupdated_at%5D=1637662184&account%5Bsubdomain%5D=mylogoped&account%5Bid%5D=24809335&account%5B_links%5D%5Bself%5D=https%3A%2F%2Fmylogoped.amocrm.ru";
Logger.log(form2Json(one));
}

Here is the form2Json script itself
 /**
 *
 * @file Parse data that could contain objects nested up to 5 levels deep.
 * It's able to deal with both rather complex data, but not fail to decode a URI as simple as id=213.
 * @author Elias Van Ootegem {@link https://stackoverflow.com/users/1230836/elias-van-ootegem}
 * @see https://stackoverflow.com/a/10881657/1393023
 */

/**
 *
 * @param {string} formString
 * @return {object}
 */
function form2Json(formString) {
  'use strict';
  let obj;
  let i;
  let pt;
  let keys;
  let j;
  let ev;
  if (typeof form2Json.br !== 'function') {
    form2Json.br = function(repl) {
      if (repl.indexOf(']') !== -1) {
        return repl.replace(/\](.+?)(,|$)/g, function($1, $2, $3) {
          return form2Json.br($2 + '}' + $3);
        });
      }
      return repl;
    };
  }
  formString =
    '{"' +
    (formString.indexOf('%') !== -1
      ? decodeURIComponent(formString)
      : formString) +
    '"}';
  obj = formString
    .replace(/\=/g, '":"')
    .replace(/&/g, '","')
    .replace(/\[/g, '":{"');
  obj = JSON.parse(
    obj.replace(/\](.+?)(,|$)/g, function($1, $2, $3) {
      return form2Json.br($2 + '}' + $3);
    })
  );
  pt = ('&' + formString)
    .replace(/(\[|\]|\=)/g, '"$1"')
    .replace(/\]"+/g, ']')
    .replace(/&([^\[\=]+?)(\[|\=)/g, '"&["$1]$2');
  pt = (pt + '"').replace(/^"&/, '').split('&');
  for (i = 0; i < pt.length; i++) {
    ev = obj;
    keys = pt[i].match(/(?!:(\["))([^"]+?)(?=("\]))/g);
    for (j = 0; j < keys.length; j++) {
      if (!Object.prototype.hasOwnProperty.call(ev, keys[j])) {
        if (keys.length > j + 1) {
          ev[keys[j]] = {};
        } else {
          ev[keys[j]] = pt[i].split('=')[1].replace(/"/g, '');
          break;
        }
      }
      ev = ev[keys[j]];
    }
  }
  return obj;
}

A: The issue is in the form value
leads[update][0][custom_fields][14][values][0][value]

The following section of your string:
leads%5Bupdate%5D%5B0%5D%5Bcustom_fields%5D%5B14%5D%5Bvalues%5D%5B0%5D%5Bvalue%5D=https%3A%2F%2Fmylogoped.online%2Freading%3Futm_source%3Dblogger

will become decoded to the following:
leads[update][0][custom_fields][14][values][0][value]=https://mylogoped.online/reading?utm_source=blogger

The incriminating value being the url:
https://mylogoped.online/reading?utm_source=blogger

form2Json attempts to create a JSON object out of the string using conventional replacement methods:
formString =
    '{"' +
    (formString.indexOf('%') !== -1
        ? decodeURIComponent(formString)
        : formString) +
    '"}';

obj = formString
    .replace(/\=/g, '":"')
    .replace(/&/g, '","')
    .replace(/\[/g, '":{"');

Where formString is the string you pass to it (in your case, one).
Due to the line .replace(/\=/g, '":"') the = signifying a URL parametergets converted to a ":", and so then in the string that is provided to JSON.parse() reads:
"leads": {
  "update": {
    "0": {
      "custom_fields": {
        "14": {
          "values": {
            "0": {
              "value": "https://mylogoped.online/reading?utm_source": "blogger"
            }
          }
        }
      }
    }
  }
}

Which is an invalid JSON string and throws the error
SyntaxError: Unexpected token : in JSON at position 5759

Fix:
You need to encode the = in the URL before putting it into form2Json in some way
Perhaps change all = characters in the raw input to a different character string (such as {{ EQUALS_SIGN }}) and then after calling form2Json(one) replace all instances of the {{ EQUALS_SIGN }} string for an = whenever it is to be displayed anywhere


text:
Q: TYPO3 Extbase Dependency Injection Error/Bug in v7? I am currently upgrading an extbase-extension to be TYPO3 v7 compatible,
and there is a very strange extbase behavior I simply have no clue to.
Within BackendController, A derived model has to be updated,
which looks like this:
/**
 * action update
 *
 * @param \Vendor\MyExt\Domain\Model\Thing $thing
 * @return void
 */
public function updateAction(\Vendor\MyExt\Domain\Model\Thing $thing) {
    if ($this->request->hasArgument('exit')) {
        $this->redirect('list');
        exit;
    }

    $this->setFalItems($thing);
    $this->updateStuff($thing);
    $this->updateTypeModel($thing);
    //...
}

protected function updateTypeModel( \Vendor\MyExt\Domain\Model\Thing $thing ) {
    //...
    $objectManager    = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
    $mytypeRepository = $this->objectManager->get('Vendor\MyExt\Domain\Repository\TypeWhateverRepository');
    $typeModel        = $mytypeRepository->findByUid( $TypeId );
    //...

in v6, vardump( $typemodel ) showed the corresponding Object,Vendor\MyExt\Domain\Model\TypeWhatever
in v7, vardump( $typemodel ) is showing the parent Object,Vendor\MyExt\Domain\Model\Thing
Why is it working in v6?
Why is the exact same code not working in v7 anymore?
[dreams of dreaded bugs at night]
I digged a little bit deeper, This problem is somehow related to Dependency Injection.:
/**
 * typeWhateverRepository
 *
 * @var \Vendor\MyExt\Domain\Repository\TypeWhateverRepository
 * @inject
 */
protected $typeWhateverRepository;

protected function updateTypeModel(\Vendor\MyExt\Domain\Model\Thing $thing) {
//  $typeWhateverRepository = $this->objectManager->get('Vendor\\MyExt\\Domain\\Repository\\TypeWhateverRepository');
    $typeModel = $this->typeWhateverRepository->findByUid($thing->getTypeId());

    ->  still the same problem,
    ->   Call to undefined method Vendor\MyExt\Domain\Model\Thing::setWhatever()

So, DI didn't work at all, Grmpf.
What other prerequisites are necessary to get the DI right?
(BTW, inbetween tests, i un-and reinstall the ext, clearing all caches via installtool.)
Thank you in advance.

A: First of all... lets do some clean up...
I would recommend to use the inject of your repository:
/**
 * seminarRepository
 *
 * @var \Vendor\MyExt\Domain\Repository\TypeWhateverRepository
 */
protected $typeWhateverRepository;

/**
 * @param \Vendor\MyExt\Domain\Repository\TypeWhateverRepository $typeWhateverRepository
 */
public function injectTypeWhateverRepository(TypeWhateverRepository $typeWhateverRepository)
{
  $this->typeWhateverRepository= $typeWhateverRepository;
}

Then I would use an Relation from Thing to Type so you don't have to fetch these from your Repository:
/**
 * @lazy
 * @var \Vendor\MyExt\Domain\Model\TypeWhatever
 */
protected $typeWhatever = null;

/**
 * @return \Vendor\MyExt\Domain\Model\TypeWhatever $typeWhatever
 */
public function getTypeWhatever()
{
  return $this->typeWhatever;
}

/**
 * @param \Vendor\MyExt\Domain\Model\TypeWhatever $typeWhatever
 *
 * @return void
 */
public function setTypeWhatever(TypeWhatever $typeWhatever)
{
  $this->typeWhatever = $typeWhatever;
}

In your Thing TCA put than:
'type_whatever' => [
  'exclude' => 0,
  'label'   => 'LLL:EXT:my_ext/Resources/Private/Language/locallang_db.xlf:tx_myext_domain_model_thing.type_whatever',
  'config'  => [
    'type'          => 'select',
    'foreign_table' => 'tx_myext_domain_model_typewhatever',
    'items'         => [

 ['LLL:EXT:my_ext/Resources/Private/Language/locallang_db.xlf:tx_myext_domain_model_thing.choose', 0],
    ],
    'minitems'      => 1,
    'maxitems'      => 1,
  ],
],

A: The Solution to this is trivial, but was hard to find, since I was doing an Extension Update.
the extbase-typoscript setup was missing the subclasses definition m)
extbase setup is usually found in the filetypo3conf/ext/my_ext/Configuration/TypoScript/setup.txt:
config.tx_extbase.persistence.classes {
    Vendor\MyExt\Domain\Model\Thing {
         subclasses {
                 0 = Vendor\MyExt\Domain\Model\TypeWhatever
         }
    }
}

Also note that it is necessary for the class to have a proper 'extends' definition in the Model file.
I still wonder why it worked in v6 at all - but well, nevermind.


text:
Q: Recharts Tooltip displays same value I have an issue where the tooltip is displaying the same value for different series. So whenever I hover on the popover, I get the following:

Here's my implementation:
  <LineChart margin={{ top: 15, right: 5, bottom: 5, left: 10 }}>
    <XAxis
      type='number'
      dataKey='timestamp'
      padding={{ left: 30, right: 30 }}
      domain={['dataMin', 'dataMax']}
      height={90}
      tickFormatter={(unixTime) => dayjs(unixTime).format('MM/DD h:mm A')}
      tickMargin={30}
    />

    <YAxis
      dataKey='Demand'
      tickFormatter={(val, _axis) => numeral(val).format('0,0') + ' kW'}
    />

    {chartData && this.renderLines(chartData, theme)}

    <CartesianGrid strokeDasharray='3 3' />
    <Legend />
    <Tooltip
      content={<LiveDailyDemandTooltip
        format={{
        Demand: '0.0'
          }} />}
    />
  </LineChart>

Where the data looks like:
{
  "dataID-1": [
    {Demand: 4237, timestamp: 1564977600000}
    ...
  ],
  "dataID-2": [
    {Demand: 112, timestamp: 1564977600000}
    ...
  ]
}

A: As mentioned here: https://github.com/recharts/recharts/issues/1625
You should set allowDuplicatedCategory to false in XAxis:
<XAxis allowDuplicatedCategory={false}/>

This will resolve the problem of duplicate value in tooltip.

A: I was able to resolve this by providing the data in a different format. It seems that Recharts needs to have data grouped by their X-Axis value:
[
  { timestamp: 1564977600000, Demand1: 4237, Demand2: 112 },
  ...
]


text:
Q: How do I use numpy to form a 2D array from another array's columns(dimension is 2*4) given an array of indices of column number efficiently I'm trying to make an array of 2 by n using numpy, elements inside come from specific columns selected by an array of column numbers.
For example if I have something like this
[[1, 2, 3],
 [2, 3, 4]]

as my input array, and i want to have columns
[2,3,1,2,3],
i will get
 [[2, 3, 1, 2, 3],
  [3, 4, 2, 3, 4]]

as my output array

A: You want to slice along the second dimension.  However, keep in mind that numpy uses zero based indexing.  You'll need [1, 2, 0, 1, 2] instead of [2, 3, 1, 2, 3]
a = np.array([
    [1, 2, 3],
    [2, 3, 4]])

a[:, [1, 2, 0, 1, 2]]

array([[2, 3, 1, 2, 3],
       [3, 4, 2, 3, 4]])


text:
Q: AS3 - Using struct information to decompress a format I'm wondering, is it possible to use this sort of information in AS3 to decompress a format? I've seen people use C++ to decompress similar formats, but since I'm fluent in AS3 I'd like to know if I can use my ActionScript knowledge to do the same.
It might be obvious but I haven't worked much with ByteArrays and am pretty inexperienced with manipulating bytes. I'm willing to learn though.

A: This is pretty straightforward using IDataInput methods--you can read from a FileStream or Socket directly, or you can process a ByteArray.  Adobe has an example for ZIP files, which is essentially the same as your use case.  You do need to know how many bytes each member of the struct takes up (i.e., DWORD is usually 32 bits unsigned).
For your example:
struct BLBHeader                    class Header
{                                   {
    char    szID[4];                    public var szID:ByteArray;
    BYTE    bID;                        public var bID:uint;
    BYTE    bUnknown;                   public var bUnknwon:uint;
    WORD    wDataSize;                  public var wDataSize:uint;
    DWORD dwFileSize;                   public var dwFileSize:uint;
    DWORD dwNumber;                     public var dwNumber:uint;
};                                  }

function readHeader(input:IDataInput):Header {
    var header:Header = new Header();

    // ByteArrays have to be pre-allocated
    header.szID      = new ByteArray();
    input.readBytes(header.szID, 0, 4);

    // primitives just get read in
    header.bID       = input.readUnsignedByte();  // 8 bits
    header.bUnknown  = input.readUnsignedByte();
    header.wDataSize = input.readUnsignedShort(); // 16 bits
    DWORD dwFileSize = input.readUnsignedInt();   // 32 bits
    DWORD dwNumber   = input.readUnsignedInt();
};

If you wanted szID to be a String instead, you could use
header.szID = input.readMultiByte(4, 'us-ascii'); // one byte per char

To use:
var header:Header = readHeader(input);
var fileIDs:Array = [];
for (var i:int = 0; i < header.dwNumber; ++i) {
    fileIDs.push( readFileID(input) );
}
... // continue with readDirEntry(input), readDataSection(input), ...


text:
Q: Vimeo API - Is there a way to disable the keyboard shortcuts of the embedded vimeo video? I often embed the vimeo video via iframe into my website for video conferencing.
I can easily hide the control bar by query string like below.
https://player.vimeo.com/video/12345678?controls=0
However, this method only hides the control bar but doesn't disable the shortcuts.
Is there a way to disable the keyboard shortcuts of the embedded Vimeo video?
Thanks

A: at the moment the only way to disable shortcuts is to make video as background.
Use this querystring: ?background=1&muted=0&loop=0&responsive=1
Best regards
Stefano

A: Use keyboard=0 param to disable keyboard input:

Allows for keyboard input to trigger player events. If false, will ignore keyboard input. Tabbing will still be supported in either mode.

Source: https://github.com/vimeo/player.js#embed-options


text:
Q: SQLITE.ALL Prepare 1 In my NativeScript with Angular project, I'm trying to use SQLite to create my database. Whenever I try to run it though, I keep getting an error on my create table statements that says SQLITE.ALL - Prepare Error 1. I've tried looking the problem up but can't really find anything on it.
Here's my database.service.ts file:
var Sqlite = require("nativescript-sqlite");

@Injectable()
export class DatabaseService {

    private createDB() {
        return new Promise((resolve, reject) => {
            return (new Sqlite("imtracker.db")).then(db => {
            db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, password TEXT, firstName TEXT, lastName TEXT, gender TEXT, permissions TEXT, year INTEGER, basketball NUMERIC, dodgeball NUMERIC, football NUMERIC, soccer NUMERIC, softball NUMERIC, volleyball NUMERIC, teamID INTEGER)").then(id => {
                resolve(db);
            }, error => {
                console.log("CREATE USESRS TABLE ERROR: ", error);
                reject(error);
            });
            db.execSQL("CREATE TABLE IF NOT EXISTS leagues (id INTEGER PRIMARY KEY AUTO INCREMENT, teamSize INTEGER, sportID INTEGER)").then(id => {
                resolve(db);
            }, error => {
                console.log("CREATE LEAGUES TABLE ERROR: ", error);
                reject(error);
            });
        }, error => {
            reject(error);
        })
    })
}

public insertUser(user: User) {
    return new Promise((resolve, reject) => {
        this.createDB().then((res: any) => {
            res.execSQL("INSERT INTO users (id,password,firstName,lastName,gender,permissions,year,basketball,dodgeball,football,soccer,softball,volleyball,teamID) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", [user.id, user.password, user.firstName, user.lastName, user.gender, user.permissions, user.year, user.basketball, user.dodgeball, user.football, user.soccer, user.softball, user.volleyball, user.teamID]).then(id => {
                console.log("INSERT RESULT: ", id);
                resolve(true);
            }, error => {
                console.log("INSERT USERS FAILED: ", error);
                reject(false);
            })
        })
    })
}

public insertLeague(league: Leagues) {
    return new Promise((resolve, reject) => {
        this.createDB().then((res: any) => {
            res.execSQL("INSERT INTO leagues (id,teamSize,sportID) VALUES (?,?,?)", [league.id, league.teamSize, league.sportID]).then(id => {
                console.log("INSERT RESULT: ", id);
                resolve(true);
            }, error => {
                console.log("INSERT LEAGUES FAILED: ", error);
                reject(false);
            })
        })
    })
}

public selectAllUsers() {
    return new Promise((resolve, reject) => {
        this.createDB().then((res: any) => {
            return res.all("SELECT * FROM user").then(rows => {
                let result: User[] = [];
                for (let row in rows) {
                    result.push({
                        "id": rows[row][1],
                        "password": rows[row][2],
                        "firstName": rows[row][3],
                        "lastName": rows[row][4],
                        "gender": rows[row][5],
                        "permissions": rows[row][6],
                        "year": rows[row][7],
                        "basketball": rows[row][8],
                        "dodgeball": rows[row][9],
                        "football": rows[row][10],
                        "soccer": rows[row][11],
                        "softball": rows[row][12],
                        "volleyball": rows[row][13],
                        "teamID": rows[row][14]
                    });
                }
                resolve(result);
            }, error => {
                console.log("SELECT USERS ERROR: ", error);
                reject(error);
            })
        })
    })
}

public selectAllLeagues() {
    return new Promise((resolve, reject) => {
        this.createDB().then((res: any) => {
            return res.all("SELECT * FROM leagues").then(rows => {
                let result: Leagues[] = [];
                for (let row in rows) {
                    result.push({
                        "id": rows[row][1],
                        "teamSize": rows[row][2],
                        "sportID": rows[row][3]
                    });
                }
                resolve(result);
            }, error => {
                console.log("SELECT LEAGUES ERROR: ", error);
                reject(error);
            })
        })
    })
  }
}

and then here are my models:
leagues.model.ts:
export interface Leagues {
    id: number,
    teamSize: number,
    sportID: number
}

user.model.ts:
export interface User {
    id: number,
    password: string,
    firstName: string,
    lastName: string,
    gender: string,
    permissions: string,
    year: number,
    basketball: boolean,
    dodgeball: boolean,
    football: boolean,
    soccer: boolean,
    softball: boolean,
    volleyball: boolean,
    teamID: number
}

and then here's where I call it in my component:
constructor(private router: Router, private databaseService: DatabaseService) {

    this.databaseService.selectAllUsers().then((res: any) => {
        this.usersList = res;
    })
}

Any help would be greatly appreciated as I'm pretty confused right now. Thanks!

A: I suspect you are accessing the tables in your select query too early, even before it's created. You will have to update your createDB method to something like below,
private createDB() {
        return (new Sqlite("imtracker.db")).then(db => {
            return Promise.all([
                db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, password TEXT, firstName TEXT, lastName TEXT, gender TEXT, permissions TEXT, year INTEGER, basketball NUMERIC, dodgeball NUMERIC, football NUMERIC, soccer NUMERIC, softball NUMERIC, volleyball NUMERIC, teamID INTEGER)")
                    .catch(error => {
                        console.log("CREATE USESRS TABLE ERROR: ", error);
                        throw error;
                    }),
                db.execSQL("CREATE TABLE IF NOT EXISTS leagues (id INTEGER PRIMARY KEY AUTO INCREMENT, teamSize INTEGER, sportID INTEGER)")
                    .catch(error => {
                        console.log("CREATE LEAGUES TABLE ERROR: ", error);
                        throw error;
                    })
            ]).then(() => db);
        });
    }


text:
Q: bypass cloudflare protection with casperjs or phantomjs while using tor proxy I use tor to access casperjs via this socks proxy
my OS windows 10 x64
my test.js
var casper = require('casper').create({
verbose: true,
logLevel: 'error',
pageSettings: {
    loadImages: false, // The WebPage instance used by Casper will
    loadPlugins: false, // use these settings
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
    }
});
var caturl = ('http://www.test.com');
casper.start(caturl, function() {
    this.echo(this.getTitle());
});
casper.run();

result from my local machine
casperjs test.js
This Is Page Title

when open tor, and I'm sure its working fine also the socks proxy is working tested it before
casperjs  --proxy=127.0.0.1:9150 --proxy-type=socks5 test.js
Attention Required! | Cloudflare

the result as I see, that its want to solve recaptcha to open this site from cloudflare
BUT
when I open the tor browser, and open the link tested in casperjs, its open normally without any asking for recaptcha
WHY
 when open the link with casperjs ask for recaptcha , and when open the link with tor browser (same proxy IP used) it doesn't ask for recaptcha ?
is this related with useragent or what ?


text:
Q: Set specific classes to Material UI component I have a Link component from Material-UI.
I make a list of these Link components and want to set a very specific class to them, but they always seem to add some extra ones as well
import React from "react";
import { Link as RouterLink } from "react-router-dom";
import { Link } from "@material-ui/core";

interface Props {
  to: string;
  children: React.ReactNode | string;
}

const LocalLink: React.FC<Props> = ({ to, children}) => (
  <Link to={to} component={RouterLink} className="MuiButtonBase-root MuiListItem-root MuiListItem-gutters MuiListItem-button"}>
    {children}
  </Link>
);

export default LocalLink;

However, the resulting anchor element has these classes
<a class="MuiTypography-root MuiLink-root MuiLink-underlineHover MuiButtonBase-root MuiListItem-root MuiListItem-gutters MuiListItem-button MuiTypography-colorPrimary" href="/">

So you see the extra "MuiTypography-root", "MuiLink-root", "MuiLink-underlineHover" and "MuiTypography-colorPrimary".
I guess that Link component adds these, but how can I prevent this?
Also, the class names that I set are passed to the first child of the anchor element.

A: This worked for me when made a component to handle internal and external links.
// import both Link components

import { Link } from "@material-ui/core";
import { Link as RouterLink } from "react-router-dom";

Then inside your component, this is the code I use to render the Link component from react-router-dom
// wrap RouterLink with Material UI link and add Mui classes to className

  <Link >
    <RouterLink className="MuiTypography-root MuiLink-root MuiLink-underlineHover  MuiListItem-root MuiListItem-gutters MuiTypography-colorPrimary" to={to}>{value}</RouterLink>
  </Link>


text:
Q: Spring Boot: Saving a one to many json request, foreign key is not saved automatically I have 2 entities, Role and Resource. A role can have many resources.
@Entity
public class Resource {

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

@Column(name="firstname")
private String firstName;

@Column(name="lastname")
private String lastName;

private String email;

@ManyToOne
@JoinColumn(name="roleId", nullable = false)
private Role role;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Role getRole() {
    return role;
}

public void setRole(Role role) {
    this.role = role;
}

}

@Entity
public class Role {

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

@Column(name = "rolename")
private String roleName;

@OneToMany(mappedBy = "role", cascade = CascadeType.ALL)
private List<Resource> resources;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

public String getRoleName() {
    return roleName;
}
public void setRoleName(String roleName) {
    this.roleName = roleName;
}
public List<Resource> getResources() {
    return resources;
}
public void setResources(List<Resource> resources) {
    this.resources = resources;
}

}

I'm trying to save a Role object that has a resource in it. This is the body of my json in postman.
{
"roleName" : "Business Analyst",
"resources" : [{
    "firstName" : "John",
    "lastName" : "Doe",
    "email" : "John@Doe.com"
}]
}

http post call in postman:
http://localhost:8080/app/admin/roles/role

Role Controller
@RestController
@RequestMapping(value="/admin/roles")
public class RoleController {
@Autowired
private RoleService roleService;

private static final Logger log = LoggerFactory.getLogger(RoleController.class);

@RequestMapping(value="/role", method = RequestMethod.POST)
public ResponseEntity<?> addRole(@RequestBody Role role, UriComponentsBuilder ucBuilder){
    log.info("Adding Role {}" + role);
    log.info("Adding Rolename:" + role.getRoleName());

    roleService.addRole(role);
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/admin/roles/role/{id}").buildAndExpand(role.getId()).toUri());
    return new ResponseEntity<String> (headers,HttpStatus.CREATED);
}

@RequestMapping(value="role", method = RequestMethod.GET)
public ResponseEntity<List<Role>> listAllRoles(){
    List<Role> roles = roleService.getAllRoles();
    return new ResponseEntity<List<Role>>(roles, HttpStatus.OK);
}

}

RoleRepository
public interface RoleRepository extends CrudRepository<Role, Integer> {

}

RoleService
public interface RoleService {

public void addRole(Role role);

}

RoleServiceImpl
@Service
public class RoleServiceImpl implements RoleService {

@Autowired
private RoleRepository roleRepository;

@Override
public void addRole(Role role) {
    roleRepository.save(role);
}
}

Whats happening is, the role Business Analyst gets save in the roleName field of Role table. The id of the said row is auto generated. At the same time, the resource with firstName = John, lastName = Doe and email = John@Doe.com gets save in the Resource table.
However, the role_id is not being saved automatically in the Resource table so now it is null ( the table Resource has the role_id set to nullable ). I was expecting that when I do the json post, the data will be automatically saved in the Role table and also the Resource table. Both of these are happening except that the role_id is not being saved. What did I miss?

A: Change addRole like below :
public void addRole(Role role) {

    for(Resource resource: role.getResources()){
        resource.setRole(role);
    }

    roleRepository.save(role);
}


text:
Q: How to convert decimal codepoint to UTF-16 Hex (java Syntax)? I have keycode = 57430
<Key android:codes="57430" android:keyIcon="@drawable/e056" />

How to convert decimal into UTF-16 Hex 0xE056
link
Share your code

A: When you say "into UTF-16 Hex 0xE056", it's unclear whether you mean the string 0xE056 or the char character with that value.
To convert a string 57430 to an integer:
int value = Integer.parseInt("57430");

To convert to hex string:
String hex = Integer.toHexString(value); // e056

String hex = Integer.toHexString(value).toUpperCase(); // E056

String hex = String.format("0x%04x", value); // 0xe056

String hex = String.format("0x%04X", value); // 0xE056

To convert to char:
char ch = (char)value; // Only for 0-65535

char[] ch = Character.toChars(value); // For any codepoint

To convert to String:
String symbol = new String(Character.toChars(value)); // For any codepoint


text:
Q: hg: unknown command 'extdiff'' I can't figure out why my extdiff extension is not working for Mercurial (on a Mac).
this is what my .hgrc file looks like:
[extensions]
fetch=
hgext.extdiff =

[extdiff]
cmd.kdiff3 =

[ui]
merge=kdiff3

[merge-tools]
kdiff3.executable=/Applications/kdiff3.app/Contents/MacOS/kdiff3
kdiff3.args = $base $local $other -o $output

and yet kdiff3 is recognized as a merge tool.. and can be run from the cmd line like "kdiff3". but what i'd like to do is use kdiff3 as a gui tool for comparing diff files.
like this:
    hg extdiff -p kdiff3
this seems like the best way of using kdiff3 as a popup gui when using Mercurial.
I am new to this and am not sure if I am doing it right.
Thanks...!
By the way, when I try to run 'hg extdiff'
I get:
 hg: unknown command 'extdiff'
'extdiff' is provided by the following extension:
extdiff  command to allow external programs to compare revisions
use "hg help extensions" for information on enabling extensions

(even though it is in .hgrc)

A: Please note that merge-tool and external diff are different tools for different tasks.
For example you can use fmdiff script to use FileMerge for diff and k3diff for merge-tool:
Your .hgrc should be:
[extensions]
# enable external diff program
extdiff =

[extdiff]
cmd.opendiff = fmdiff
opts.opendiff =

[merge-tools]
# Override stock tool location
kdiff3.executable = /Applications/kdiff3.app/Contents/MacOS/kdiff3
# Specify command line
kdiff3.args = $base $local $other -o $output
# Give higher priority
kdiff3.priority = 1

Now you can use
hg opendiff myfile.ext

Please note that 'opendiff' is a custom wrapper name, so you can change it to your likes but it cannot be one of already reserver names.


text:
Q: Capistrano Rubber Phusion Passenger Enterprise Config I am having a little trouble editing the Capistrano Rubber recipes to include the Phusion Passenger Enterprise edition instead of the open-source module.
The problem starts with the fact that the enterprise version of passenger is not available for download from any repositories. Thus, I downloaded the gem manually and have it stored in a .tar.gz file on my local machine. One thing I did notice though is that the stock Capistrano rubber recipe expects to find the gem in a repository, not a local file. And so, I assume that I need to edit the following config file, although I am not quite sure how.
Edit #1: config/rubber/rubber-passenger_nginx.yml
passenger_version: 3.0.11
nginx_version: 1.0.11
passenger_root: "#{`bash -l -c 'find #{ruby_path} -name passenger-#{passenger_version}'`.strip}"
passenger_ruby: "#{ruby_path}/bin/ruby"
passenger_lib: "#{passenger_root}/ext/nginx"
passenger_listen_port: 7000
passenger_listen_ssl_port: 7001
max_app_connections: 20

use_ssl_key: false
#if you use an ssl key, put your cert and key
# in
# #{Rubber.root}/config/#{rubber_env.domain} .crt and .key
#otherwise defaults to key included with linux z

roles:
  passenger_nginx:
    packages: [libcurl4-openssl-dev, libpcre3-dev]
    gems: [[passenger, "#{passenger_version}"]]

I also feel like I should be editing the installation routine so that I specify the location of the manually downloaded gem and point the nginx install process to it.
If anyone could offer any advice I would be very appreciative.
Thanks

A: Perhaps you can use Rubber in combination with a shell script that runs plain old 'gem install local-file.gem'.
The Enterprise gems and tarballs can be downloaded non-interactively. In the Customer Area, right click on a gem or tarball and copy its URL. You can then use curl or another similar tool to download that URL. You just need to pass HTTP Basic Authentication credentials too. The username is your order reference, the password is the one you received by email.


text:
Q: Unique file identifier in Dropbox I would like to know whether there's any unique id with which we can distinguish files in Dropbox. Because when we copy/move a file in dropbox,it is detected as a new change by delta api. And it would be good if we can distinguish files in dropbox with a unique id. I've done some research and didn't find anything. So any help would be appreciated.

A: Yes, Dropbox API v2 does now offer file IDs that persist across moves/renames. You can find more information under "Path formats" in the documentation.
The file ID is available as the id field on the FileMetadata object, e.g., as returned by /files/get_metadata.


text:
Q: Why does the order of a nonterminal's "or" clauses are in effect the behavior of the postprocessor in nearly? In the Nearley Parser Playground, if I type:
excludebrackets-> null | [^\\[\]]:+ {%(d) => { return "myReturn"}%}

The parser returns "MyReturn" as expected.  However, if
excludebrackets-> [^\\[\]]:+ | null {%(d) => { return "myReturn"}%}

Nearley seems to totally ignore the postprocessor, returning [Array[n]] as it would by default.  (However, some legitimate attempts at accessing the array in the postprocessor throw errors.)
Man, this caused some weird bugs.
Can anyone explain why it would behave this way?


text:
Q: Capitalization of "neo-scholasticism" Is the word 'neo-scholasticism' capitalized in academic writing, or not?
It is lowercase in the Merriam Webster dictionary, but capitalized in the Collins English dictionary. So in a thesis, which would be correct:
Option A: neo-scholasticism
Option B: Neo-Scholasticism

A: Academic writing is usually in compliance with the relevant institution or publisher's style guide. As you see here, they differ sometimes:

Penn State University
Capitalize names of cultural movements and styles if they are derived
from proper nouns; otherwise they should be lowercased: Cynicism,
Doric, Gothic, Neoplatonism, Pre-Raphaelite, Romanesque; but baroque,
classical, cubism, Dadaism, modernism, neoclassicism,
postmodernism, romanticism.

Capitalization (Penn State)
However...

Association of Art Editors:
In general, sharply delimited period titles are capitalized, whereas
broad periods and terms applicable to several periods are not:
Archaic period Baroque Early Renaissance High Renaissance Early
Christian Gothic Greek Classicism of the fifth century (otherwise,
classicism) Imperial Impressionism Islamic Mannerist Middle Ages
Neoclassicism (for the late-18th-century movement; otherwise, neoclassicism) Post-Impressionism Pre-Columbian, Precolumbian Rococo
Roman Romanesque Romantic period
antique, antiquity classicism (see above) medieval modern, modernism
neoclassicism (see above) postmodern prehistoric quattrocento

Association of Art Editors Style Guide
Some sources advise neo-Scholasticism and Merriam Webster has neo-scholasticism.


text:
Q: Create Web Service in ZK I want to create an web service, I am quiet familiar with zk. Can I create web service in ZK?
My web service should be able to send response in the form of XML/JSON objects

A: ZK framework basically concentrates on UI. I donnot think it can be used to implement web services even if u can it won't be a good Idea to when u have other good frameowrks like Play!.


text:
Q: How to create Ichimoku "3 lines" signal? Hi I try to wrote a simple strategy that is based on Ichimoku Cloud.
The strongest and most profitable Ichimoku signal - described by creator of the system Mr.Hosoda - is so called "3 lines signal"
The signal has few conditions:
1. Crossover of conversionLine over baseLine
2. Price close above conversionLine
3. ConversionLine is above baseLine
4. BaseLine above Cloud /leadLine1 and leadLine2/
5. Displacement line above price
Problem:
When I put all those conditions together I get "no data".
It works but only with fist 3 conditions /crossover and close>conversionline and close>baseline)
When I add conditions 4. and 5. strategy shows "No data". /for example: baseline>leadline1 and baseline>leadline2 and close>displacement/
Works only with condition 1,2,3.
So there is some problem with cloud and displacement, but I cannot find a solution
Please help :)
Thank You
code /only for long entries/:
//@version=4
strategy(title="Ichimoku Cloud", shorttitle="Ichimoku", overlay=true)

conversionPeriods = input(9, minval=1, title="Conversion Line Periods"),
basePeriods = input(26, minval=1, title="Base Line Periods")
laggingSpan2Periods = input(52, minval=1, title="Lagging Span 2 Periods"),
displacement = input(26, minval=1, title="Displacement")
profit = input(100, minval=1, title="Profit")
loss = input(100, minval=1, title="Loss")

donchian(len) => avg(lowest(len), highest(len))

conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)

plot(conversionLine, color=#0496ff, title="Conversion Line")
plot(baseLine, color=#991515, title="Base Line")
plot(close, offset = -displacement + 1, color=#459915, title="Lagging Span")

p1 = plot(leadLine1, offset = displacement - 1, color=color.green,
 title="Lead 1")
p2 = plot(leadLine2, offset = displacement - 1, color=color.red,
 title="Lead 2")
fill(p1, p2, color = leadLine1 > leadLine2 ? color.green : color.red)

entry()=> crossover (conversionLine, baseLine) and close>baseLine and close>conversionLine

strategy.entry (id="Long entry", long=true, when=entry())
strategy.exit (id="Long exit", profit=200, loss=200)

Conditions in visual:
enter image description here

A: The reason condition number 4 which is baseline>leadline1 and baseline>leadline2 is not working is because

*

*Leadline1 and LeadLine2 both is plotted 26 periods in the future

If you will look at the clouds formed by lead1 and lead2 you must find there are two types of cloud , cloud which is plotted in the future and cloud which is plotted in the same timeframe as baseLine and conversionLine
you have to modify your code in such a way that you are satisfying following two conditions

*

*Both base and conversion line is above the cloud(cloud that is in the same timeframe as base and conversion line)
a = conversionLine > leadLine1[26]
b = conversionLine > leadLine2[26]
c = baseLine > leadLine1[26]
d = baseLine > leadLine2[26]
e = leadLine1[26] > leadLine2[26]

*Cloud 26 period in the future is greenish
f = leadLine1 > leadLine2


text:
Q: URLs requested via Http on the server must be absolute. URL: ./assets/i18n/en.json I am new to Angular 2 and I have the following issue in the ngx-translate component (URLs requested via Http on the server must be absolute. URL: ./assets/i18n/en.json). I am sure that this en.json file is there as I make http request to it and the request succeeds
Here is my app.module.server.ts file:
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { sharedConfig } from './app.module.shared';
import { HttpModule, Http } from '@angular/http';
import {
    TranslateModule,
    TranslateLoader,
    MissingTranslationHandler,
    MissingTranslationHandlerParams
} from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function createTranslateLoader(http: Http) {
    return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

export class MyMissingTranslationHandler implements MissingTranslationHandler {
    handle(params: MissingTranslationHandlerParams) {
        return '[' + params.key + ']';
    }
}

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        ServerModule,
        HttpModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [Http]
            }
        }),
        ...sharedConfig.imports
    ]
})
export class AppModule {
}

and here is my app.module.cleint.ts  file:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule,Http } from '@angular/http';
import { sharedConfig } from './app.module.shared';
import {
    TranslateModule,
    TranslateLoader,
    MissingTranslationHandler,
    MissingTranslationHandlerParams
} from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
export function createTranslateLoader(http: Http) {
    return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

export class MyMissingTranslationHandler implements MissingTranslationHandler {
    handle(params: MissingTranslationHandlerParams) {
        return '[' + params.key + ']';
    }
}

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [Http]
            }
        }),
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin },
        {
            provide: MissingTranslationHandler,
            useClass: MyMissingTranslationHandler
        }
    ]
})
export class AppModule {
}

and here is my app.module.shared.ts file:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpModule, Http } from "@angular/http";
import { BrowserModule } from "@angular/platform-browser";

import { TranslateModule} from '@ngx-translate/core';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { EmployeesListComponent } from './components/employees/EmployeesList.component';
import { CounterComponent } from './components/counter/counter.component';

export const sharedConfig: NgModule = {
    bootstrap: [AppComponent],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        EmployeesListComponent,
        HomeComponent
    ],
    imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'employees-list', component: EmployeesListComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        BrowserModule,
        HttpModule,TranslateModule
    ]
    , exports: [
        TranslateModule
    ]
};

A: Well the issue is just this. ./assets/i18n/en.json is not an absolute url like :  http://foo.com/assets/i18n/en.json. I know that there are usually ways to indicate that you are serving from the same server as the client side code.  Might it not be
export function createTranslateLoader(http: Http) {
    return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
}

But when I poke around in the angular docs repos: I see this: https://github.com/angular/angular/issues/15349. So maybe the angular http service doesn't support calling the host on which the document was served. That is sort of really surprising, but you can get that in javascript using:
window.location.origin

So just prepend that to /assets/i18n/ when you set up the call.


text:
Q: SonataAdmin hooks are not firing I have Symfony 2.8. I use SonataAdminBundle v2.3 + a2lix/TranslationFormBundle v2.1 + SonataMediaBundle v2.3. I have NewsAdmin class:
class NewsAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('translations', 'a2lix_translations', ['fields' => [
                'content' => [
                    'field_type' => 'ckeditor',
                ]
            ]])
            ->add('excerptImage', 'sonata_type_model_list', [], [
                'link_parameters' => ['context' => 'default'],
                'require' => false
            ])
            ->add('excerptImageSide')
            ->add('category', 'sonata_type_model', [
                'class' => 'AppBundle\Entity\NewsCategory',
                'property' => 'shortName'
            ])
        ;
    }

    // configureDatagridFilters(), configureListFields() ...

    // Does not firing!
    public function postUpdate($news)
    {
        dump('preUpdate');
    }

    // Does not firing!
    public function prePersist($news)
    {
        dump('prePersist');
    }
}

The problem is that nor postUpdate, nor prePersist methods are not firing, so I don't see in web profiler string 'preUpdate' or 'prePersist'. Why that happens? And how to fix that?
P.S. Please, let me know if you need more information.

A: Just add a die and you'll see your dump.
public function prePersist($news)
{
    dump('prePersist');
    die;
}

EDIT
That's because the dump is not called directly from the controller action that renders the view, nor from a method called by the action, but in an EventListener that is totally standalone.


text:
Q: How to test a socketConnection under Windows? I have implemented the client protocol for BaseX (an open source XML-database) in a R-package (RBaseX). The people from CRAN asked me to add testthat-tests to the sources, and thanks to those tests I discovered (and fixed) some bugs.
The package has been developed on a linux-client. BaseX was also installed on the client.
When no basexserver is running, all tests should fail. Therefore every test_that-section starts with a call to the following function which tests if a socketConnection can be created:
skip_unless_socket_available <- function() {
    tryCatch({
    sock <- base::socketConnection(
      host = "localhost", 1984,
      open = "w+b", server = FALSE, blocking = TRUE, encoding = "utf-8")
    close(sock)
    TRUE
  }, error = function(e) {
    skip(paste0("basexserver not available:\n'", conditionMessage(e), "'"))
  })
}

On a linux- or a Windows client, with a running basexserver available, test_check("RBaseX") terminates without errors. When no basexserver is available, on a linux-client test_check("RBaseX") also terminates without errors.
But a Windows-client hangs without returning errors or warnings.
What is the correct way to test in Windows if a socketConnection can be created that connects to a server?
Ben

A: Windows and linux behave different when there is no response from the resource at all.  When using linux and when calling 'socketConnection' without an explicit timeout-setting, the call is terminated immediately.
In Windows, it is necessary to provide a timeout-value. 'timeout = 1' solved my problem.
Ben


text:
Q: If $G$ is a simple group, with $\chi \in{\rm Irr}(G)$, such that $\chi(1) = p$, for some prime $p$, then $G$ has a Sylow $p$-subgroup of order $p$. I am currently reading "Character Theory of Finite Groups". If the Sylow $p$-subgroup $P$ is abelian, then by Theorem $3.13, p$ is the exact power of $p$ diving $|G: Z(G)| = |G|$ since $G$ is simple.
I don't know how to prove the hint.
If $\chi$ restricted to $P$ is irreducible, then corollary $2.28$ proves the hint, but I don't know how to prove $\chi$ is irreducible when restricted to $P$, or if that's the right idea? I know since $Z(P)$ is not trivial, if $Z(P) \leq Z(\chi)$, then since $G$ is simple, we would have $G = Z(\chi)$, but not sure how that helps?

A: Any reference here is to Isaac's book Character Theory of Finite Groups. Some preparatory remarks. Let $P \in Syl_p(G)$ ($P$ exists and is non-trivial, since $\chi(1)=p \mid |G|$). Now $\chi_P=\sum a_{\theta}\theta$ for integers $a_{\theta} \gt 0$ and $\theta \in Irr(P)$. Since $\theta(1) \mid |P|$, each $\theta(1)$ is a power of $p$. Clearly, $\chi_P(1)=\chi(1)=p=\sum a_{\theta}\theta(1) \geq \theta(1)$ for each of these irreducible constituents $\theta$ of $\chi_P$. Hence, $\theta(1) \in \{1,p\}$. Further, observe that $\chi$ is non-linear, so $G$ cannot be abelian. Since $G$ is simple, $Z(G)=1$, and the non-linearity of $\chi$ gives $Z(\chi) \lt G$, whence $Z(\chi)=1$ and so is $ker(\chi)=1$ ($\chi$ is faithful). Now we have two cases.
(1) If $\theta(1)=p$ for some $\theta$, then $\chi_P=\theta$ (of course, the corresponding $a_{\theta}=1$). Hence $\chi_P$ is irreducible.  But then $ker(\chi_P)=P \cap ker(\chi)=1$, so (Lemma 2.27(f)) $Z(P)\subseteq Z(\chi_P)=P \cap Z(\chi)=1$, contradicting $P$ being a non-trivial $p$-group. Hence:
(2) $\theta(1)=1$ for all irreducible constituents $\theta$ of $\chi_P$, that is, $\chi_P$ is the sum of some linear characters. But then, (Lemma (2.21) and (2.23)(a)), $1=ker(\chi_P)=\bigcap_{\theta} ker(\theta) \supseteq P'$. We conclude that $P$ is abelian.
Note that we have proved sofar that if $G$ is a simple group having an irreducible character of degree $p$, then a $p$-subgroup must be abelian! The proof can now be finished by applying Theorem(3.13) and it is here that we are using that $P$ is a Sylow $p$-subgroup.
Note A similar line of reasoning as above gives the following. Let $G$ be a simple group and suppose $\chi\in Irr(G)$ with $\chi(1)=p$ a prime. Let $q$ be another prime, with $q \mid |G|$ and $q \gt p$. Then a $q$-subgroup of $G$ is abelian. In particular a Sylow $q$-subgroup is abelian.