text:
Q: Как на сервере FLASK прочитать отправленный с GET'ом JSON? Здравствйуте!
На клиенте следующий код, для отправки
    function test(){
    $.ajax({
        url:'/article',
        method:'GET',
        dataType:'json',
        data:JSON.stringify({'article':13}),
        contentType : "application/json",
        success: function(response){
            console.log("Success")
        },
        error: function(e) {
            console.log("Erroe")
        }
    })}

На сервере:
@app.route('/article')
def func():
    request.get_json()

Как получить значение

A: request.get_json берет json из запросов, у которых есть тело.
У GET тела не бывает.
Соответственно можно посмотреть в браузере/инструментах-разработчика/сеть как посылается data:
Request URL:http://127.0.0.7/article?{%22article%22:%22%D0%BF%D0%BE%D0%BB%D0%BD%D0%B0%D1%8F%20%D0%B5%D1%80%D1%83%D0%BD%D0%B4%D0%B0%22}
Потом посмотреть в документации flask API, что часть после ? попадает в request.query_string
Но она закодирована как URL. parse_qsl декодирует пару (имитируемую "="+). Берем value с пары и парсим json.
from urllib.parse import parse_qsl
from json import loads

def json_from_query_string(s):
    return loads(parse_qsl("="+s.decode())[0][1])

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def hello_world():
    return 'Hello, World!'

@app.route('/article', methods=['GET'])
def article():
    parsed = json_from_query_string(request.query_string)
    return parsed['article']


text:
Q: Punteros .next y new node en C++ Tengo el siguiente algoritmo:
#include <iostream>
using namespace std;

class node{
    public:
        int info;
        node *next;
};

node *p, *q;
int *e, i, **f;

int main(){
    p = new node;
    e = new int;

    *e = 0;
    f = &e;

    (*p).next = new node;
    q = &(*p);

    p = (*p).next;

    return 0; }

No entiendo que sucede al realizar (*p).next = new node, no se si ahora lo apuntado por p, ahora apunta a un nuevo nodo. Y cuando hace p = (*p).next en realidad le asigna a la variable new node.

A: Las siguientes dos líneas son equivalentes:
(*p).next = new node;
p->next = new node;

y lo único que hacen es crear un nuevo nodo y apuntar su dirección de memoria en p->next. Es decir, esta línea no modifica p, que sigue apuntando al mismo nodo que antes de ejecutar esta instrucción.
En cambio, esta otra línea:
p = (*p).next;

Sí que modifica p. En este caso hace que p apunte al nodo apuntado por p->next. Dicho en cristiano, el puntero avanza una posición en la lista.
Antes de ejecutar esa línea:
nodo0 -> nodo1 -> nodo2 -> nodo3
^        ^
p        p->next

Después de ejecutar esa instrucción:
nodo0 -> nodo1 -> nodo2 -> nodo3
         ^        ^
         p        p->next

Date cuenta que al avanzar en la lista es irrelevante si el nodo ha sido creado con new o no. Lo único importante en este punto es cómo te mueves a lo largo de una lista enlazada.

redpajama_set_name: RedPajamaStackExchange


text:
Q: user defined function doesn't work vba i have this udf and basically what I want to get is the latest date from a vector (column) that match with other data in other column, here's the code:
Option Explicit
Public Function GetLastDate(Carrier As String, CarrierVector As Range, DateVector As Range) As Variant
    Dim TempRange(1 To 10) As Variant
    Dim i, j As Integer
    For i = 1 To DateVector.Rows.Count
        With Application.WorksheetFunction
            If .Text(CarrierVector.Item(i), "#") = Carrier And .IsError(.VLookup(DateVector.Item(i), TempRange, 1, False)) Then
                j = j + 1
                TempRange(j) = DateVector.Item(i)
            End If
        End With
    Next i
    GetLastDate = Application.WorksheetFunction.Max(TempRange)
End Function

in this case, if the Carrier variable is found on CarrierVector, the Date corresponding to that carrier will be storage on TempRange array, (this if it's not repeated) and at the end, it will return the lattest Date, but this doesn't work, it just return an error on the cell from where the function is called, could you please help me?

A: The problem seems to be with the VLookUp call. I don't know why it fails, but I also think it is not recommendable to use worksheet functions inside VBA, unless there is no good alternative.
But in this case, you could use a Collection to keep track of a unique set of dates you already had:
Public Function GetLastDate(Carrier As String, CarrierVector As Range,
                            DateVector As Range) As Variant
    Dim TempRange As New Collection
    Dim i As Integer
    Dim found As Boolean
    Dim max As Date
    For i = 1 To DateVector.Rows.Count
        With Application.WorksheetFunction
            If .Text(CarrierVector.Item(i), "#") = Carrier Then
                On Error Resume Next
                    found = TempRange.Item(DateVector.Item(i) & "")
                On Error GoTo 0
                If Not found Then
                    TempRange.Add DateVector.Item(i), DateVector.Item(i) & ""
                    If DateVector.Item(i) > max Then max = DateVector.Item(i)
                End If
            End If
        End With
    Next i
    GetLastDate = max
End Function

Still, I am not sure why you need to use this TempRange at all, since you are not using it for anything else. You might as well completely drop it:
Public Function GetLastDate(Carrier As String, CarrierVector As Range,
                            DateVector As Range) As Variant
    Dim i As Integer
    Dim found As Boolean
    Dim max As Date
    For i = 1 To DateVector.Rows.Count
        With Application.WorksheetFunction
            If .Text(CarrierVector.Item(i), "#") = Carrier Then
                If DateVector.Item(i) > max Then max = DateVector.Item(i)
            End If
        End With
    Next i
    GetLastDate = max
End Function


text:
Q: Как получить опции ip пакета в php/С++ Интересует опция временных меток, отправляемая в ip пакете. Можно ли каким то образом получить эти метки средствами php ? Попробовал curl_getinfo($ch) но не один из 26 параметров не похож на timespan временной метки т.к. они представляют собой  количество миллисекунд от полуночи по UTC. Ничего подобного в возвращаемой информации нет, если есть ткните.
Информация нужна для анализа загруженности сети, в идеале хорошо бы увидеть время в миллисекундах когда пакет был отправлен от сервера к клиенту. Если есть другие способы подобное реализовать, то прошу ткнуть в мануал.
UPD Добавил С++ т.к. интерпретатор php написан на плюсах. Может есть способ получить опции пакета при помощи программы C++.

A: Прямо из cURL такие данные посмотреть нельзя, но можно посмотреть со стороны с помощью обычных программ для просмотра трафика. Например, tshark, который, как и PHP, написан на C, если это почему-то важно. Если нужно чтобы программа была строго на C++, то такие тоже можно поискать. Будут ли они решать задачу также ясно и просто - вопрос открытый.
Запускаете прямо из PHP с помощью exec или proc_open, но лучше сначала потренироваться в консоли:
tshark -p -c 10 -e tcp.options.timestamp.tsval -e tcp.options.timestamp.tsecr -Tjson -Y 'tcp.option_kind == 8'

Получаете из стандартного выхода красивый JSON со всеми нужными значениями:
[
  {
    "_index": "packets-01001",
    "_type": "pcap_file",
    "_score": null,
    "_source": {
      "layers": {
        "tcp.options.timestamp.tsval": ["2386387284"],
        "tcp.options.timestamp.tsecr": ["1871759056"]
      }
    }
  }

  ,
  { ....

Если нужна временная метка, можно добавить -e frame.time. Если нужно отобрать только входящие пакеты, только с определёнными свойствами, то фильтр легко составить по образцам пакетов в GUI Wireshark.
Наверное снимать такие метрики лучше в фоне, из crontab - сама процедура может занимать ощутимое время. Например, можно запускать саму команду выше с записью в файл, и через минуту запускать скрипт который этот файл будет читать и разбирать.
Чтобы использовать tshark без прав root кроме обычного шага при установке нужно добавить себя в группу wireshark. В общем случае для запуска этих команд не нужно sudo.
Прямо из cURL такие данные посмотреть нельзя.


text:
Q: First course: Do I need to download bootstrap? And where do I download it? I'm completeing the first course "First landing page" and I can't figure out how or if I need to download bootstrap. Is there some link in the tutorial?

A: You probably do. I am unfamiliar with that course. When I use bootstrap with just html I have to download it. This is a good place to start:
https://getbootstrap.com/docs/4.3/getting-started/download/
They have some snippets on using it and if you look around getbootstrap.com there is plenty of help in the form of Getting Started, Examples and Documentation sections

A: Its on you if you want to download it you can download it or you can simply include the online source file link into your file.
You can include link like this in your html file.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

Or you can download the file from here


text:
Q: How to plot dataframe in the current state/sequence? I'm trying to reconfigure a pandas dataframe, which currently looks like this:
   No. Val
0  7   1
1  9   2
2  1   3
3  4   4

The df has been sorted according to 'val' in ascending order. How can I go on to plot the df in the sequence of 'No.' column? (i.e first plot (7,1), then plot (9,2) etc)

A: You can use matplotlib as
plt.plot( df['No.'].tolist() , df['Val'].tolist() , color ='blue' )
plt.show()

or seaborn as
sns.scatterplot(x = 'No.' , y = 'Val' , data = df)


text:
Q: How to precisely control axis scale function in matplotlib I want to plot points on the interval x in [0, 4]. My function performs something interesting for very small values, so I would like to create a non-linear scale that would use more space for smaller values of x. Logarithmic scale would be a great solution, but the problem is that my x-axis must include 0, which is not part of logarithmic axis.
So I considered using a power scale. After some googling I came across the following solution.
def stratify(ax, power=2):
    f     = lambda x: (x + 1)**(1 / power)
    f_inv = lambda y: y**power - 1
    ax.set_xscale('function', functions=(f, f_inv))

x = np.linspace(0, 4, 100)
y = np.sqrt(x)

fig, ax = plt.subplots()
ax.plot(x, y)
stratify(ax, 2)

plt.show()

The function stratify changes the x-scale of the plot to the square root function. This looks kind of correct. Below is a minimal example plot corresponding to the above code (not actual data).

I would like to have control over the nonlinearity in the x-scale, that is why I have introduced the power parameter. However, when I change the power parameter to value different from 2, the plot does not change at all. This is very surprising for me. I would appreciate if somebody could advise me how I can control the extent of non-linearity in x-axis. If possible, I would like it even more non-linear, making the interval [0, 0.5] take half of the plot.
EDIT While the current solution by @Thomas works as intended, the plotting routine throws a lot of errors when one attempts to do anything with it. For example, I would like to insert extra ticks, as the original only has integer ticks for whatever reason. Inserting extra ticks via ax.set_xticks(ax.get_xticks() + [0.5]) results in an error posx and posy should be finite values. What is this error, and how can it be bypassed?

A: For me, there's a change when switching from power=2 to power=10. Just be careful to edit it at the right position, i.e. when calling stratify=X.
Here's power=2:

Here's power=10:

However, here's another suggestion that is slightly more aggressive:
import numpy as np
import matplotlib.pyplot as plt

def stratify(ax, scale=1):
    f = lambda x: np.log(x / scale + 1)
    f_inv = lambda y: scale * (np.exp(y) - 1)
    ax.set_xscale('function', functions=(f, f_inv))

x = np.linspace(0, 4, 100)
y = np.sqrt(x)

fig, axs = plt.subplots(1, 3)
for i, scale in enumerate([10,1,0.1]):
    ax = axs[i]
    ax.set_title(f'Scale={scale}')
    ax.plot(x, y)
    stratify(ax, scale=scale)

plt.show()

Resulting in

Another option are zoom regions.


text:
Q: editText "cannot resolve symbol" I'm trying to do something when "enter" is pressed in the "textEdit". I'm using onkeylistener, but it is showing error in the textedit part. My code is
editText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View view, int keyCode, KeyEvent keyevent) {
                        //When "Enter" or "Search" Pressed)
                        if ((keyevent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                EditText editText = (EditText)findViewById(R.id.editText);

                                WebView mw = (WebView) findViewById(R.id.webView2);
                                mw.setWebViewClient(new WebViewClient());
                                mw.getSettings().setJavaScriptEnabled(true);
                                mw.loadUrl("http://i.word.com/idictionary/" + editText.getText());
                return true;
            }
            return false;
        }
    });
}

Could you please help me?

A: In your code "editText" variable is declared and initialized inside "if" clause.
The following code should work properly:
EditText editText = (EditText)findViewById(R.id.editText);
editText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View view, int keyCode, KeyEvent keyevent) {
                        //When "Enter" or "Search" Pressed)
                        if ((keyevent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                WebView mw = (WebView) findViewById(R.id.webView2);
                                mw.setWebViewClient(new WebViewClient());
                                mw.getSettings().setJavaScriptEnabled(true);
                                mw.loadUrl("http://i.word.com/idictionary/" + editText.getText());
                return true;
            }
            return false;
        }
    });
}


text:
Q: Need to get the time difference between the two dates in hh:mm format I need to get the time difference between to different dates in HH:MM format.Suppose I had two dates like this

02/26/2014 09:00:00 and  02/26/2014 19:30:00

I need to get the difference in hh:mm like 09:30.
I googled and tried to find solution for this but they are giving the individual hours and minutes.
I am not allowed to use Third party libraries like Joda for this. Can anyone please point me in the right direction?

UPDATE

I tried the following code
public class DateDifferentExample {

/**
 * @param args
 */
public static void main(String[] args) {

    String dateStart = "02/26/2014 09:00:00";
    String dateStop = "02/26/2014 19:05:00";

    //HH converts hour in 24 hours format (0-23), day calculation
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    Date d1 = null;
    Date d2 = null;

    try {
        d1 = format.parse(dateStart);
        d2 = format.parse(dateStop);

        //in milliseconds
        long diff = d2.getTime() - d1.getTime();

        System.out.println("Time difference-->"+diff);

        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);
        int diffInDays = (int) (d2.getTime() - d1.getTime());

        System.out.println("Difference--> "+diffInDays);
       String difft=diffHours+":"+diffMinutes;
        System.out.println("Duration Time:"+difft);

        /*System.out.print(diffDays + " days, ");
        System.out.print(diffHours + " hours, ");
        System.out.print(diffMinutes + " minutes, ");
        System.out.print(diffSeconds + " seconds.");*/

        //System.out.println("Getting date diff from the other method--->"+calculateDays(d1, d2));

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

}

/*public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
    long diffInMillies = date2.getTime() - date1.getTime();
    return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}*/

public static long calculateDays(Date dateEarly, Date dateLater) {
       return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
    }

}

A: try this
    SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date d1 = df.parse("02/26/2014 09:00:00");
    Date d2 = df.parse("02/26/2014 19:30:00");
    long d = d2.getTime() - d1.getTime();
    long hh = d / (3600 * 1000);
    long mm = (d - hh * 3600 * 1000) / (60 * 1000);
    System.out.printf("%02d:%02d", hh, mm);

prints
10:30

A: *

*Parse the timestamps into a Date using SimpleDateFormat.

*Calculate the difference between dateOne.getTime() and dateTwo.getTime().  The result will be the difference in milliseconds.

*Use the TimeUnit instances to convert the milliseconds to hours and minutes.

A: My solution:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeDiff {

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

        // Setup
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "MM/dd/yyyy HH:mm:ss");
        long second = 1000l;
        long minute = 60l * second;
        long hour = 60l * minute;

        // parsing input
        Date date1 = dateFormat.parse("02/26/2014 09:00:00");
        Date date2 = dateFormat.parse("02/26/2014 19:30:00");

        // calculation
        long diff = date2.getTime() - date1.getTime();

        // printing output
        System.out.print(String.format("%02d", diff / hour));
        System.out.print(":");
        System.out.print(String.format("%02d", (diff % hour) / minute));
        System.out.print(":");
        System.out.print(String.format("%02d", (diff % minute) / second));
    }

}

Keep in mind, that dates are not as easy as you could expect. There are leap seconds and all kind of weird stuff.


text:
Q: number of rows in big table SELECT COUNT(*) FROM BigTable_1

Which way I should to use to get number of rows in table if I have more than 1 billion of rows?
UPDATE: For example, if we have 'a timeout problem' with the query above is there any way to optimize it?  How to do it quicker?

A: If you need an exact count, you have to use COUNT (*)
If you are OK with a rough count, you can use a sum of rows in the partitions
SELECT SUM (Rows)
FROM sys.partitions
WHERE 1=1
And index_id IN (0, 1)
And OBJECT_ID = OBJECT_ID('Database.schema.Table');

If you want to be funny with your COUNT, you can do the following
select COUNT (1/0) from BigTable_1

A: A very fast ESTIMATE:
select count(*) from table
But don't execute!  Highlight the code, press ctl-l to bring up the query plan.  Then hover over the leftmost arrow.  A yellow box appears with the estimated number of rows.
You can query system tables to get the same data, but that is harder to remember.  This way is much more impressive to onlookers.
:)

A: You can use sys.dm_db_partition_stats.
select sum(row_count)
from sys.dm_db_partition_stats
where object_id = object_id('TableName') and  index_id < 2

A: Depending on your concurrency, speed, and accuracy requirements, you can get an approximate answer with triggers. Create a table
CREATE TABLE TABLE_COUNTS(TABLE_NAME VARCHAR, R_COUNT BIGINT DEFAULT 0);
INSERT INTO TABLE_COUNTS('BigTable_1', 0);

(I'm going to leave out adding a key, etc., for brevity.)
Now set up triggers.
CREATE TRIGGER bt1count_1 AFTER INSERT ON BigTable_1 FOR EACH ROW
BEGIN
UPDATE TABLE_COUNTS SET R_COUNT=R_COUNT+1 WHERE TABLE_NAME='BigTable_1';
END;

A corresponding decrement trigger goes on DELETEs. Now instead of a COUNT, you query the TABLE_COUNT table. Your result will be a little off in the case of pending transactions, but you may be able to live with that. And the cost is amortized over all of the INSERT and DELETE operations; getting the row count when you need it is fast.

A: Try this:
select sum(P.rows) from sys.partitions P with (nolock)
join sys.tables T with (nolock) on P.object_id = T.object_id
where T.Name = 'Table_1' and index_id = 1

it should be a lot faster. Got it from here: SELECT COUNT(*) FOR BIG TABLE

A: Your query will get the number of rows regardless of the quantity.  Try using the query you listed in your question.

A: There's only 1 [accurate] way to count the rows in a table: count(*). sp_spaceused or looking at the statistics won't necessarily give you the [a?] correct answer.

A: if you've got a primary key you should be able to do this:
select count(PrimaryKey) from table_1


text:
Q: How to import csv to firebase using PHP? I want to import data from a csv file to Firebase using PHP but all I am seeing in the web is for MySQL.
I am trying to do a grading system where I insert a csv file containing the grades and determine whether if it passed or failed without showing the csv contents.


text:
Q: Excel Formula lookup to another excel document saved in Sharepoint not working for another user I have 2 excel documents (excel1 and excel2) saved on Sharepoint.
On excel1 - I have a lookup from excel2. The formula works 100% for me.
I have shared and given access to a secondary user. When they open excel1 and select Update (which happens as soon as you add a new row), all the formulas give errors. When the second user opens up excel2 then the formulas start working.
How do I get it so that the second user does not have to open up excel2 to get the formulas to work immediately in excel1?
Such a simple one but I am struggling.


text:
Q: Python - как загрузить куки из файла в session? Подскажите как загрузить куки из файла в session = requests.Session()
Куки в таком формате приложил в фото. Или может как то нужно конвертировать в стиль requests?


text:
Q: KeyError when trying to access request.meta's key in Scrapy Here is the code of a simple spider:
# -*- coding: utf-8 -*-

import os
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.http import Request

class AzS(CrawlSpider):

    name = 'azs'
    allowed_domains = ["******"]
    start_urls = [
        "*********"
    ]

    rules = (
        Rule(LinkExtractor(restrict_xpaths = ("""//*[@id="yearList"]""")), callback = 'year', follow = True), # years at start url
        Rule(LinkExtractor(restrict_xpaths = ("""/html/body/div[3]/div/div[1]/div/div[2]/ul""")), callback = 'model', follow = True), # model
    )

    # start url with years list
    def year(self, response):
        yr = response.url.split('=')[-1][2:4]
        request = Request(response.url,
                          callback = self.model)
        request.meta['yr'] = yr
        return request

    # the page of the year with models list
    def model(self, response):
        print response.meta['yr']

and when executed, this code produces this error:
File "xxxxxxxxxx.py", line 33, in model
            print response.meta['yr']
        exceptions.KeyError: 'yr'

I'm not able to figure out what causes this error, so any help is appreciated. Thank you in advance.

A: Since you have two rules and whenver the second rule become true obviously some requests will be triggered and from there the response is getting at model, in that case you are not setting any meta data with key 'yr'. This might be the root cause of your error.
Either you can use some try - except or try to access the key using get(), ie, response.meta.get('yr', 'your_value'). If that key is not found it will take your_value as the value.


text:
Q: Regex to validate letters numbers and specific special characters I have unsuccessfully be looking around the web for such a simple regex and can't seem to put it together.
I need a regex which allows any letter, numbers, whitespace and particular special characters only (@ # $ & ( ) - _ /)
"Test #123 @Sample/test"  is valid
"Test ^ £300"             is not valid

A: Simply you could try the below regex,
^[\w\s@#$&()\/-]+$

DEMO

*

*^ Asserts that we are at the start.

*[\w\s@#$&()\/-]+ Matches one or more characters from the list.

*$ Asserts that we are at the end.


text:
Q: How to prove that no hamiltonian cycle exists in the graph ** Show that the graph below has a hamiltonian path but no hamiltonian cycle.

You can find more than one hamiltonian path such as $(b,a,c,f,e,g,d)$.
Actually, I tried many times to find a hamiltonian cycle, but I couldn't find a cycle. The problem is how to prove that no hamiltonian cycle exists. I need a logical proof. I can't say "I tried many times but I couldn't find a hamiltonian cycle" because it's not reasonable answer.

A: Notice that if you delete the edge joining $g$ and $f$, then you get the complete bipartite graph $K_{3,4}$ with sides $\{g,a,f\}$ and $\{b,d,c,e\}$.
It may help now to redraw the graph in the usual way $K_{3,4}$ is drawn. In any case, now you need prove that there is no Hamilton cycle in $K_{3,4}$ and no Hamilton path from $g$ to $f$. Use the fact that the two sides have different number of vertices.


text:
Q: Sphinx not working - Status active (exited) Sphinx installed and it was working. Suddenly it stopped and following error appearing
Sphinx error: connection to unix:///path/runtime/sphinx/var/sphinx.socket failed (errno=111, msg=Connection refused)

● sphinxsearch.service - LSB: Fast standalone full-text SQL search
  engine    Loaded: loaded (/etc/init.d/sphinxsearch)    Active: active
  (exited) since Wed 2019-05-08 17:24:31 EDT; 3s ago   Process: 2039
  ExecStop=/etc/init.d/sphinxsearch stop (code=exited, status=0/SUCCESS)
  Process: 2052 ExecStart=/etc/init.d/sphinxsearch start (code=exited,
  status=0/SUCCESS)
May 08 17:24:31 bureaubureau systemd[1]: Starting LSB: Fast standalone
  full-text SQL search engine... May 08 17:24:31 bureaubureau
  systemd[1]: Started LSB: Fast standalone full-text SQL search engine.


text:
Q: How to write a method trailing with a keyword I have a situation where i need to call something like this :
class Office
   attr_accessor :workers, :id

   def initialize
      @workers = []
   end

   def workers<<(worker)
      type = worker.type
      resp = Organiation::Worker.post("/office/#{@id}/workers.json", :worker => {:type => type})
   end
end

this is where i need to call
office = Office.new()

new_worker = Worker.new()

office.workers << new_worker

how should i modify the above workers method in order to implement above code.

A: New answer for this (based on updated question):
class WorkersClient
  attr_accessor :office_id

  def <<(worker)
    type = worker.type
    resp = Organiation::Worker.post("/office/#{@office_id}/workers.json", :worker => {:type => type})
  end
end

class Office
  attr_accessor :workers, :id

  def initialize
    @workers = WorkersClient.new
    @workers.office_id = @id
  end
end

I'm assuming that the Worker class is defined somewhere, something like:
def Worker
  attr_accessor :type
  ...
end

The WorkersClient class is just a proxy to handle the collection (like ActiveRecord 3 does with associations). You can develop it further to store a local cache of workers, and so on.
I would recommend looking at how Rails' ActiveResource is implemented, as it does something VERY similar.

A: try this office.build_worker

A: If those objects are actually ActiveRecord objects (which it sort of sounds like), you're probably looking at
office.workers << new_worker

Note the plural form.
If those objects are your own creations, you probably want Office#workers to return an Array'ish object, so something like
class Office
  def workers
    @workers ||= []
  end
end

Add sanity checks and whatnot as you see fit.

A: There's not much to add to what's already been said, but one thing to think about is hiding the implementation of workers. Sure, it starts out with an array, but that may change. By implementing your own << method you can hide implementation details from the user.
class Office
  attr_accessor :workers

  def initialize
    @workers = []
  end

  def <<(other)
    self.workers << other
  end
end

I tend to use getter/setters inside my classes as that's something I learned from Smalltalk books, but of course you could just do @workers << other.


text:
Q: iPhone 5S wallpaper zooming when set through MDM despite being correct resolution I have some devices managed through MDM (JAMF) and a 640 x 1136 wallpaper that I want to set through the MDM interface as the home/lock screen background. Unfortunately, pretty much every time I set it it comes out zoomed in.
I have set up the restrictions on the configuration such that the user cannot change the wallpapers.
This may be relevant: https://jamfnation.jamfsoftware.com/featureRequest.html?id=3232
Doesn't seem to be a way to turn it off properly, but perhaps if I set the resolution of the wallpaper image to something bigger than my target, it will show up properly. Rather than figure this out by trial and error, perhaps someone will know an appropriate resolution to use?

A: I have used an mdm like JAMF and facing same issue like you, i have use this link : http://iosres.com to find my resolution.
You will find all right resolution for all iOS devices.
Hope it will help you.
Br


text:
Q: Replace string with str_replace - wordpress wp_get_archives counter

    May 2015 (10)

I try to make it in standar way:
$variable = wp_get_archives( array( 'type' => 'monthly','show_post_count' => 'true') );

$variable = str_replace( '(', '', $variable);
$variable = str_replace( ')', '', $variable);
echo $variable;

But this doesn't work.
Also read about unicode:
$variable = preg_replace('/\p{Zs}/u', '_', $variable);

But also nothing... What I miss?
ANSWER :
Typical for wordpress:
$variable = wp_get_archives( array( 'type' => 'monthly','show_post_count' => 'true', 'echo' => 0) );

This what a problem. Default is echo => 1, so variable was blank.
'echo' => 0

THANKS FOR HELP

A: Problem was resolved.
$variable = wp_get_archives( array( 'type' => 'monthly','show_post_count' => 'true') );

$variable = str_replace( '(', '', $variable);
$variable = str_replace( ')', '', $variable);
echo $variable;

By default wordpress wp_get_archives is setted as "echo". Solution for this was to set "echo" to false:
$variable = wp_get_archives( array( 'type' => 'monthly','show_post_count' => 'true', 'echo' => 0) )

and now $variable is not blank.


text:
Q: using a meathod to find the average value of an array I'm writing a program that displays the Maximum, Minimum, and average of an array
So far I have methods for the max and min but not for the average.
My code:
class Test
{
    public static void main(String[] args)
    {
        int[] arr = {5,12,-3,7,3,22,31,2,16,56};
        System.out.println(minValue(arr));
    System.out.println(maxValue(arr));
    System.out.println(avgValue(arr));

    }// end of Main

  // Array Methods
    public static int minValue(int[] nums)
    {
         int minValue = nums[0];
    for(int i=1;i < nums.length; i++){
      if( nums[i] < minValue){
        minValue = nums[i];
      }
    }
    return minValue;
  }

  public static int maxValue(int[] nums)
    {
         int maxValue =nums[0];
    for(int i=1;i < nums.length ;i++){
      if( nums[i] > maxValue){
         maxValue = nums[i];
      }
    }
    return maxValue;
    }

   public static int avgValue(int[] nums)
    {
    int temp = 4;

    return temp;
    }

}// end fo class

Right now the method to find the average is filled with a  placeholder integer that always returns "4"
How would I write a message to find the average of my array?

A: An easy way would be:
  public static double avgValue(int[] nums) {
    int total = 0;

    for(int i = 0; i < nums.length; i++) {
      total = total + arr[i];
    }

    double average = total / (double) nums.length;
    return average;
  }

A: This is the proper way:
public static float avgValue(int[] nums)
{
    float sum = 0.0f;
    float avg = 0.0f;
    for(int i=0; i < nums.length;i++){
        sum += nums[i];
    }
    avg = sum/nums.length;
    return avg;
}

A: Using Java Streams
int[] data = {1,5,4,9,2,1,4,7,8};

IntSummaryStatistics s = Arrays.stream(data).summaryStatistics();
System.out.println("Average: " + s.getAverage());
System.out.println("Count: " + s.getCount());
System.out.println("Min: " + s.getMin());
System.out.println("Max: " + s.getMax());
System.out.println("Sum: " + s.getSum());

Output
Average: 4.555555555555555
Count: 9
Min: 1
Max: 9
Sum: 41


text:
Q: What are best practices for `unsafe` functions in which only a small part of the code is actually doing `unsafe` things? In the crate I'm developing I have several unsafe functions, which are marked as such because of reasons explained in this answer. In unsafe functions, I can perform unsafe operations as if the full function body was wrapped in an unsafe { } block.
The problem is that, in bigger functions, only a small part of the function body is actually performing unsafe operations, while the rest is doing perfectly safe stuff. Often, this safe stuff is even pretty independent of the unsafe code. In these larger functions, I would like to narrow the scope of unsafe operations. The reason should be fairly understandable: I also don't wrap my complete codebase in an unsafe { } block just because I can.
Unfortunately, there isn't a safe { } block to "invert" the behavior of unsafe functions. If there were I would use it like that:
unsafe fn my_function() {
    safe {
        // ... doing safe stuff ...

        unsafe {
            // ... doing `unsafe` stuff ...
        }

        // ... doing safe stuff ...
    }
}

But as this is not possible: what are best practices in these situations to narrow the scope of unsafe operations? Are there established tricks to deal with this?
Just to be clear: this question is not about discussing whether or not narrowing the unsafe scope is good or bad. I stated that I want to do it: this question is about how to do it and what solutions (if any) are most commonly used in practice. (And if you don't understand why I would like to do it, this RFC is very related.)

A: If you want to use the unsafe keyword as a way to catalogue all unsafe operations, you can construct more accurate boundaries by splitting your code into safe private functions. I'm not sure if it exactly meets your requirement of "best practice" since I don't know of any large projects using the technique, but it will work:
// Document the assumptions of this unsafe function here
pub unsafe fn my_function() {
    my_internal_function()
}

// private
fn my_internal_function() {
    // ... doing safe stuff ...
    unsafe {
        // Document the assumptions of this unsafe block here
        // ... doing `unsafe` stuff ...
    }
    // ... doing safe stuff ...
}

If you are concerned about the existence of a "safe" function that is actually unsafe to use, introducing a risk of accidentally being used incorrectly, you can nest those private functions so they are not callable outside the main unsafe function:
pub unsafe fn my_function() {
    fn my_internal_function() {
        // ... doing safe stuff ...
        unsafe {
            // Document the assumptions of this unsafe block here
            // ... doing `unsafe` stuff ...
        }
        // ... doing safe stuff ...
    }

    my_internal_function();
}

After all of this, properly documenting the assumptions of unsafe code with comments is the most important part to get right. This sort of trick will only help if you are concerned about metrics for the number of unsafe lines.


text:
Q: Firestore get all Documents between two dates query(meetingsCollection, where("start", "in", today), orderBy("start", "asc")

I'd like a Firestore query, so that I can fetch all documents between 02/12/2022 - 00:00:00.000 && 03/12/2022 00:00:00.000, ordered by the Date property start, so that I can bucketsize my firestore data request and limit overreads, then use said documents to visually filter accordingly via the front-end.
Can you assist me with this?

A: How to get start and end of day in Javascript?
const start = new Date();
start.setUTCHours(0,0,0,0);

const end = new Date();
end.setUTCHours(23,59,59,999);

Firestore query by date range
query(
  meetingsCollection,
  where("start", ">=", start),
  where("start", "<=", end)
  orderBy("start", "asc")
)

A:   db.collection("collection_name")
  .where("start", ">=", "02/12/2022 00:00:00.000")
  .where("start", "<=", "03/12/2022 00:00:00.000")
  .orderBy("start")
  .get()
  .then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      // doc.data() contains the data for the document
    });
  });

A: For anyone looking for the actual solution =>>
const now = new Date();

const getDateFormatted = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const startNow = new Date(`${getDateFormatted(now)}T00:00:00.000z`); //2021-09-01T00:00:00.000Z
const endNow = new Date(`${getDateFormatted(now)}T23:59:59.000z`);

const nowEvents = ref([]);

const getNowEvents = async () => {
  onSnapshot(myEvents(startNow, endNow), (querySnapshot) => {
    let tmpEvents = [];
    querySnapshot.forEach((doc) => {
        let event = {
          id: doc.id,
          ...doc.data(),
        };
        tmpEvents.push(event);
    });
    nowEvents.value = tmpEvents;
  });
}


text:
Q: How to make sure CSS/JS files are not cached on browser? How do i make sure that for particular ASP.NET page CSS/JS file will not be cached on browser side (each time its loaded from server)?
Anything that can be done using the server side code?

A: We can use cliend side version no
 www.yourwebsite.com/global.js?v=1

you can keep change the version no whenever there is change in the javascript file
so the request always gets the new file from the webserver


text:
Q: How does angulars $watch function work with slider everyone. I am new to Web Development and I encountered a problem. I finally managed to create a fiddle of my problem to get more specific.
My Problem is that I have 2 Slider. One Slider is responsible for a value and another one for weight. Those sliders are repeated with the ng-repeat function n times. In the fiddle only two times, for demonstration purposes.
I would like to calculate an index which consists of the following formula:
Value1*Weight1+Value2*Weight2

The index is calculated with the reduce function. The Problem is: The index value is not updating when the value change due to the slider changes
I am pretty certain it should work with the $watch function, but I have unfortunately no clue how to manage this.
If someone could be so kind and provide me some help.
The js fiddle is linked below.
https://jsfiddle.net/dkyun/dfx0grdr/

A: If you want to update the index property on your scope based on changes to the alerts, you should do a deep watch on alerts:
$scope.$watch('alerts', function() {
    var index = $scope.alerts.reduce(function(prev, next) {
      return prev + (next.value*next.weight);
    }, 0);

    $scope.index = index;
    console.log(index);
}, true);

A: You could refactor your code with something like this:
  $scope.index = 0;

  $scope.calcIndex = function(){
    return $scope.alerts.reduce(function(prev, next) {
      return prev + (next.value*next.weight);
    }, 0);
  };

  $scope.$watch(function(){
    return $scope.calcIndex();
  }, function(newValue){
    $scope.index = newValue;
  });

CHECK THE DEMO FIDDLE


text:
Q: image is not saving in folder i am using below code to upload an image through php form in fresh file, its working fine.
<!DOCTYPE html>

    <meta charset="UTF-8">

<?php
if (isset($_FILES["photo"]["error"])) {
    if ($_FILES["photo"]["error"] > 0) {
        echo "Error: " . $_FILES["photo"]["error"] . "
";
    } else {
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];

// Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if (!array_key_exists($ext, $allowed))
            die("Error: Please select a valid file format.");

// Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if ($filesize > $maxsize)
            die("Error: File size is larger than the allowed limit.");

// Verify MYME type of the file
        if (in_array($filetype, $allowed)) {
// Check whether file exists before uploading it
            if (file_exists("upload/" . $_FILES["photo"]["name"])) {
                echo $_FILES["photo"]["name"] . " is already exists.";
            } else {
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);

                echo "Your file was uploaded successfully.";
            }
        } else {

            echo "Error: There was a problem uploading your file - please try again.";
        }
    }
} else {
    echo "Error: Invalid parameters - please contact your server administrator.";
}
?>

but when i used same code in already existed form page as below code [ name, email....etc ], its not saving in folder path , looks like part of code is conflicting, i am really just started to learn php, so please kindly help me.
<?php
include 'home.php';

$userID = ""; //Initialization value; Examples
//"" When you want to append stuff later
//0  When you want to add numbers later
//isset()
$userID = isset($_POST['userID']) ? $_POST['userID'] : '';

//empty()
$userID = !empty($_POST['userID']) ? $_POST['userID'] : '';

// session_start();
require_once 'class.user.php';
$user_home = new USER();

if (!$user_home->is_logged_in()) {
    header("Location: index.php");
    die();
}

$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<?php
/* php codde */
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
    // new data
    $uname = $_POST['txtuname'];
    $email = $_POST['txtemail'];
    $phone = $_POST['phone'];
    $street_address = $_POST['street_address'];
    $street_address_2 = trim($_POST['street_address_2']);
    $city = trim($_POST['city']);
    $state = trim($_POST['state']);
    $zip_code = trim($_POST['zip_code']);
    $country = trim($_POST['country']);
    $sold_by = trim($_POST['sold_by']);
    $portfolio = trim($_POST['portfolio']);
    $paypal_email_id = trim($_POST['paypal_email_id']);
    $account_holder_name = trim($_POST['account_holder_name']);
    $account_number = trim($_POST['account_number']);
    $branch_name = trim($_POST['branch_name']);
    $bank_name = trim($_POST['bank_name']);
    $ifsc_code = trim($_POST['ifsc_code']);
    $uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);

    // query
    if ($user_home->update($uname, $email, $phone, $street_address, $street_address_2, $city, $state, $zip_code, $country, $sold_by, $portfolio, $paypal_email_id, $account_holder_name, $account_number, $branch_name, $bank_name, $ifsc_code, $uid))
        ; {
        header("Location: profile.php");
        die();
    }
}

/* php codde end */
?>

<!DOCTYPE html>

 Welcome to profile page

        <title><?php echo $row['userEmail']; ?></title>
    <a href="user.php?<?php print($userRow['user_name']); ?>">  <title><?php echo $row['userEmail']; ?></title>

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
    <link href="assets/styles.css" rel="stylesheet" media="screen">

    <form action="profile1.php" method="POST" enctype="multipart/form-data">

Personal details

        Name :
        <input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" />

        Email :
        <input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" />

        Sold_by :
        <input type="text" name="sold_by" value="<?php echo $row['sold_by'] ?>" />

        Portfolio :
        <input type="text" name="portfolio" value="<?php echo $row['portfolio'] ?>" />

ADDRESS

        Phone :
        <input type="text" name="phone" value="<?php echo $row['phone'] ?>" />

        street address :
        <input type="text" name="street_address" value="<?php echo $row['street_address'] ?>" />

        street address 2 :
        <input type="text" name="street_address_2" value="<?php echo $row['street_address_2'] ?>" />

        city :
        <input type="text" name="city" value="<?php echo $row['city'] ?>" />

        state :
        <input type="text" name="state" value="<?php echo $row['state'] ?>" />

        country :
        <input type="text" name="country" value="<?php echo $row['country'] ?>" />

        zip :
        <input type="text" name="zip_code" value="<?php echo $row['zip_code'] ?>" />

Payment details

        <input type="text" name="paypal_email_id" value="<?php echo $row['paypal_email_id'] ?>" />

Wiretransfer

        Account holder name :
        <input type="text" name="account_holder_name" value="<?php echo $row['account_holder_name'] ?>" />

        account number :
        <input type="text" name="account_number" value="<?php echo $row['account_number'] ?>" />

        Branch name :
        <input type="text" name="branch_name" value="<?php echo $row['branch_name'] ?>" />

        Bank name :

        <input type="text" name="bank_name" value="<?php echo $row['bank_name'] ?>" />

        IFSC CODE :
        <input type="text" name="ifsc_code" value="<?php echo $row['ifsc_code'] ?>" />

Other information :

Upload File

        Filename1:
        <input type="file" name="photo" id="fileSelect">

        <input type="submit" name="submit" value="Save" />
    </form>

<!DOCTYPE html>

    <meta charset="UTF-8">

<?php
if (isset($_FILES["photo"]["error"])) {
    if ($_FILES["photo"]["error"] > 0) {
        echo "Error: " . $_FILES["photo"]["error"] . "
";
    } else {
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if (!array_key_exists($ext, $allowed))
            die("Error: Please select a valid file format.");

        // Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if ($filesize > $maxsize)
            die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if (in_array($filetype, $allowed)) {
            // Check whether file exists before uploading it
            if (file_exists("upload/" . $_FILES["photo"]["name"])) {
                echo $_FILES["photo"]["name"] . " is already exists.";
            } else {
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);

                echo "Your file was uploaded successfully.";
            }
        } else {

            echo "Error: There was a problem uploading your file - please try again.";
        }
    }
} else {
    echo "Error: Invalid parameters - please contact your server administrator.";
}
?>

when i remove below code from above page, image is uploading fine, i tried to remove lot of code and make it short, so that its going to be helpfull for readers to solve issue easily, but i end up in getting lot of different kinds of errors, so i posted full code, i am extremely sorry for that....
<?php

/* php codde */
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
    // new data
    $uname = $_POST['txtuname'];
    $email = $_POST['txtemail'];
    $phone = $_POST['phone'];
    $street_address = $_POST['street_address'];
    $street_address_2 = trim($_POST['street_address_2']);
    $city = trim($_POST['city']);
    $state = trim($_POST['state']);
    $zip_code = trim($_POST['zip_code']);
    $country = trim($_POST['country']);
    $sold_by = trim($_POST['sold_by']);
    $portfolio = trim($_POST['portfolio']);
    $paypal_email_id = trim($_POST['paypal_email_id']);
    $account_holder_name = trim($_POST['account_holder_name']);
    $account_number = trim($_POST['account_number']);
    $branch_name = trim($_POST['branch_name']);
    $bank_name = trim($_POST['bank_name']);
    $ifsc_code = trim($_POST['ifsc_code']);
    $uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);

    // query
    if ($user_home->update($uname, $email, $phone, $street_address, $street_address_2, $city, $state, $zip_code, $country, $sold_by, $portfolio, $paypal_email_id, $account_holder_name, $account_number, $branch_name, $bank_name, $ifsc_code, $uid))
        ; {
        header("Location: profile.php");
        die();
    }
}

/* php codde end */
?>

A: This is not going to do what you expect as there is a ; in the wrong place here
// query
if ($user_home->update($uname, $email, $phone, $street_address, $street_address_2, $city, $state, $zip_code, $country, $sold_by, $portfolio, $paypal_email_id, $account_holder_name, $account_number, $branch_name, $bank_name, $ifsc_code, $uid))

    ; // <-- remove this

{
    header("Location: profile.php");
    die();
}


text:
Q: Unable to load image into imageview from GoogleStorageURI (Google Drive image uri) using Gallery Intent I have downloaded an image from Google Drive storage. I want to set this image to imageview in my app using Gallery Intent.
Uri of image received in onActivityResult: content://com.google.android.apps.docs.storage/document/acc%3D2%3Bdoc%3Dencoded%3DWe%2BdXDcNgTeulVk1Ntu3YfRYkm9wk7uTdTG6LFVyck1BxY4g7xAxyPAgtMtz4A%3D%3S
I am using this code get the real-path from the url:
 if ("com.google.android.apps.docs.storage".equals(uri
                    .getAuthority())) {

    //content://com.google.android.apps.docs.storage/document/acc%3D2%3Bdoc%3Dencoded%3DWe%2BdXDcNbYeulVk1Ntu3YfRYkm9wk7uTdTG6LE6yck1BxY4g7xAxyPAgtMtz4A%3D%3D

 final String docId = DocumentsContract.getDocumentId(uri);
                    final String id = docId.split(";")[1];
                    final String[] selectionArgs = new String[]{id};
                    //String[] column = {MediaStore.Images.Media.DATA};

                    // where id is equal to
                    String selection = MediaStore.Images.Media._ID + "=?";
                    Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

                    //..
                    Cursor cursor = null;
                    String filePath = null;
                    try {
                        String[] column = {MediaStore.Images.Media.DATA};

                        cursor = context.getContentResolver().query(contentUri,
                                column, selection, selectionArgs, null);
                        if (cursor != null && cursor.moveToFirst()) {
                            int columnIndex = cursor.getColumnIndex(column[0]);
                            filePath = cursor.getString(columnIndex);
                        }
                    } finally {
                        if (cursor != null)
                            cursor.close();

                        return filePath;

 }
            }

.....
But I am getting NULL cursor. Thus, filepath is always empty/null.
Anyone, could please suggest what I am doing wrong?

A:
I am using this code get the real-path from the url

Delete it.

Anyone, could please suggest what I am doing wrong?

You are using that code.
Pass the Uri to your favorite image-loading library (Glide, Picasso, etc.). It will do all the work for you, populating your ImageView, in just a few lines of code.
Or, if you insist on doing it yourself:

*

*Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri

*Use BitmapFactory.decodeStream() to get a Bitmap based on that InputStream

*Do those two steps on a background thread, as you should not do disk I/O and image decoding on the main application thread

*On the main application thread, put the Bitmap in your ImageView,


text:
Q: Programming only an app for iPhone Android Hi I have to develop an app for Android and iPhone.
I know the language to develop for Android and to develop for iPhone, but if I want to create only one app for all platform, how can I use?
I have to create a simple app with some news taken from a server, this app can be downloaded from iTunes and from PlayStore but is the same app.
I know that there is PhoneGap, but I don't know if it can be done what I want.
Another way I thinked to use jQuery Mobile, but when I finish to develop how can I create an app? because I have ever use jQuery Mobile like a site on my server for mobile and not to create an app.
I suppose to create  a jQueryMobile app and when is finished to compile it with some program to create my App. I'm a  little bit confused, which is the best way and program to optimize develop time and to create only one multiplatform app?

A: You cannot write one app natively for both platforms. Either you develop natively, but for each platform separately, or you use a framework like Phonegap. Then you write your code in HTML5 and JavaScript. You will still have to set up a project for each platform, but you can use the same HTML/JS files for both projects and simply drop them in. The only exception is: Any native code you write needs to be written for both platforms again (for example, all the standard phonegap plugins are written for each platform separately, but they already exist so you don't need to write them).
jQuery Mobile is something else, it's a framework for web development. You can use jQuery Mobile to develop the app you use in a Phonegap application (it's what I do).

A: Take a look at my 3 previous answers on this question:

*

*Frameworks and little something about them: https://stackoverflow.com/a/14166593/1848600

*Native apps vs Hybrid apps: https://stackoverflow.com/a/14069937/1848600

*Phonegap + jQuery Mobile tutorials: https://stackoverflow.com/a/14375842/1848600
I hope you will find your answer there.

A: Another framework option is the Apache Flex framework. You can use it to create native application for both Android and iOS. It is certainly capable of creating a simple new reader application.
Apache Flex has just become a top level Apache project and has just released version 4.9.0.
For more info see:
http://flex.apache.org (or http://flex.apache.org/v2)
If you do go down the framework path, and no matter which one you pick, it's likely you will still have to do some optimisation for each platform. Users expect different UI conventions on each platform. eg iPhone navigation is generally at the bottom, Android navigation is generally at the top.


text:
Q: How to put a "V" flag in a PowerBI dynamic filter? "V" flag as example
I have to put a "V" flag like the one showed in the picturein one bookmark in PowerBi, now when you select the filter there is not a "v" flag but only black. Can you please help me?

A: welcome to stackoverflow
I think what you are wanting to show are the check-marks (or chevron mark) next to the selected item in a filter list.
Normally by default, the option for Multi-select is ON, if you turn it OFF then it will allow you to select one item from the list, putting the "V" next to it.
If you want the "V" to be color or any other symbol, you will have to make you own list and add special characters as I did in my KPI column. See picture
The circle Character I used in a calculated Measure was :  UNICHAR(11044) which can change color...
So to select your chevron mark "V" display follow these steps:

*

*Select your Filter

*Open the Format pane (the one with the paint roller)

*Open your V-Selection controls

*Change Multi-select with CRTL position to OFF

*Test your filter again

Please see images below:
Changing Multi-Select to display check mark symbol on dropdown filters
Multi-select causes the box to show all Black, as you indicated.
Black box on selected items -
Color symbols on Grid Lists - picture:
Symbols with color added to grids
Hope this helps,
in bocca al lupo,
Andres
Other symbols you can use :
https://www.alt-codes.net/root-symbols


text:
Q: Amazon EC2: Can we use our own license for Suse Linux?
Possible Duplicate:
Can you help me with my software licensing question?

We have an existing SUSE Linux server with license we want to move to Amazon EC2. I want to know if we can pay the standard Linux prices if using our own license, or if we have to pay the more expensive SUSE price schedule.
The server will be always on (running a website) so we will be using a reserved instance. However I don't want to buy a reserved Linux instance and then find that the SUSE ami doesn't work with that and will only run in a reserved SUSE instance. So does anyone know if the SUSE ami will run in a reserved Linux instance?
The ami we'd like to use is ami-eea35787 (provided by SUSE).

A: The Amazon EC2 Running IBM page, specifically the "Bring Your Own IBM Software and License (BYOSL)" section indicates that so long as you you have acquired software entitlements under IBM's International Passport Advantage or Passport Advantage Express Agreements (collectively PA or PA Program), you should only have the pay the normal Amazon EC2 prices and nothing extra.


text:
Q: Как отобразить содержимое .msg файла? Есть .msg файл, который находится в папке assets. Как отобразить его содержимое на активности?

A: Я открываю таким образом:
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
String type = "application/msword";
intent.setDataAndType(Uri.fromFile(new File(path)), type);
    try {
       startActivity(intent);
    } catch (ActivityNotFoundException e) {
       showShortMessage(getString(R.string.need_doc_reader));
    }

Но, разумеется, должен стоять MS office на девайсе, чтобы сработало.


text:
Q: Converter um ficheiro de texto para PDF sem gravar em um local físico Bom eu fiz um método para converter um ficheiro texto em PDF, porém ele salva o PDF na maquina. Queria que que o método retorna-se um array sem ter de gravar o PDF na maquina nem ter de ler o ficheiro novamente.
public byte[] Converte(string path)
{
    FileInfo fl = new FileInfo(path);
    fl.GetAccessControl(); //Dando acesso total ao fileinfo.
    DirectoryInfo pir = new DirectoryInfo(fl.FullName.ToString());
    string[] lines = System.IO.File.ReadAllLines(path);  // Ler todas linhas do documento
    Document doc = new Document(PageSize.A4);//criando e estipulando o tipo da folha usada
    doc.SetMargins(40, 40, 40, 80);//estibulando o espaçamento das margens que queremos
    doc.AddCreationDate();//adicionando as configuracoes
    string caminho = fl.FullName.Replace(".txt", ".pdf"); // dando replace na extensão
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create));
    doc.Open(); //Abrindo documento
    string dados = ""; //Criando string de dados para passar dados.

    foreach (string line in lines)
    {
        Paragraph paragrafo = new Paragraph(dados); // Criando paragrafo para receber os valores das linhas.
        paragrafo.Add(line.ToString()); // Passando valor da linha do txt para pdf
        doc.Add(paragrafo); //Adicionando ao pdf
    }

    doc.Close(); // Fechando e salvando documento

    //Criando um Array de Bytes para o pdf.
    FileStream stream = System.IO.File.OpenRead(caminho);
    byte[] fileBytes = new byte[stream.Length];
    stream.Read(fileBytes, 0, fileBytes.Length);
    stream.Close();

    return fileBytes;
}

A: Substitua o FileStream por um MemoryStream:
using(MemoryStream memStream = new MemoryStream())
{
    PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
    // o seu codigo
    return memStream.ToArray();
}


text:
Q: problem involving fourier cosine series. The first part of the problem is to obtain the fourier cosine series of period $2\pi$ Which represents $f$ on the domain $0\leq x\leq \pi$
where $$f(x)=\pi-2x,0\leq x \leq \frac{\pi}{2}$$ and $$f(x)=0,\frac{\pi}{2}\leq x\leq\pi$$
My attempt:
The Fourier cosine series is given by $$f(x)=\frac{a_0}{2}+\sum_{n=0}^{\infty}a_n\cos(nx)$$ where $$a_0=\frac{1}{2\pi}\int_{0}^{\pi}f(x)dx$$ $$a_n=\frac{1}{\pi}\int_{0}^{\pi}f(x)\cos(nx)dx$$
i calculated that $a_0=0$ and $$a_n=\frac{2}{\pi^2*n}$$ if $n$ is even and $0$ if n is odd. therefore my fourier cosine series was $$f(x)=\sum_{n=0}^{\infty}\frac{2}{\pi^2*n}\cos(nx)$$ is this correct?
Part (b) is that by letting $x=\frac{\pi}{2}$ in the fourier series obtained evaluate the series $$\sum_{n=1}^{\infty}\frac{1}{n^2}(1-\cos(\frac{n\pi}{2}))\cos(\frac{n\pi}{2})=-\frac{2}{2^2}-\frac{2}{6^2}-\frac{2}{10^2}-...$$ but i dont really know what to do, i was thinking that i would just write the series given  equal to the series calculated substituting x in? i ended up getting something like $$\frac{2\cos^{-1}(\frac{-2n}{\pi^2}-1)}{n}=\pi$$ but this cant be right surely.?

A: There are some mistakes in the OP.  First, since $f(x)=0$ for $x\in[\pi/2,\pi]$ the Fourier coefficients are
$$a_n=\begin{cases}\frac2\pi\int_0^{\pi/2}(\pi-2x)\cos(nx)\,dx=\frac{4(1-\cos(n\pi/2))}{n^2\pi}&,n\ne 0\\\\
\frac\pi2&,n=0\tag 1
\end{cases}$$
Then, we have from $(1)$
$$\begin{align}
\pi-2x&= \frac\pi4 +\frac4\pi\sum_{n=1}^\infty \frac{(1-\cos(n\pi/2))}{n^2}\,\cos(nx)\tag 2
\end{align}$$
Letting $x=\pi/2$ in $(2)$ yields
$$0= \frac{\pi}{4}+\frac4\pi \sum_{n=1}^\infty \frac{(1-\cos(n\pi/2))\cos(n\pi/2)}{n^2}$$
from which we deduce that
$$\sum_{n=1}^\infty \frac{(1-\cos(n\pi/2))\cos(n\pi/2)}{n^2}=-\frac{\pi^2}{16}$$


text:
Q: Which is the best way to route paths on AWS? My name is Diego and this is my first question on the site. I'm Argentinian, so, sorry for my bad english.
I was introduced into Amazon Web Services (AWS) four months ago, and I worked with services like EC2, S3, Route53, IAM, etc.
Now, I have the next scenario:

*

*An EC2 (1), with a website based on React (frontend) and Node.js (backend)

*An EC2 (2), with a webapp based on React Native and Express.js

In Route53 I registered the domain.com pointed to the first EC2 (the website, on port 80), and the webapp is running on the second EC2, on port 3000.
After searching and read a lot a few days (I will let the links at the end of the post) I came here to solve the doubt.
The question is the following:
When I go to domain.com, I will come on the website, so, some paths like /home, /services, /ourworks, /team, etc.  will be part of it. But... If the word that comes after the bar isn't it one of this, I need to send the user to the second EC2 on port 3000, that is to say, the webapp. After that, the webapp will know what to do with the route.
So...
What is the best way to route this scenario?
I have read about:
-Use an .htaccess to routing paths and ports. This was fine in the last scenario, when the website was a Wordpress site, but now the website is based on React and Nodejs, so, we not use Apache anymore, so this solution is useless for me.
-Use the routing of the Application Load Balancer (ALB). This is fine, but the price of this service is so expensive, so I can't use this by now.
-Use the routing of the API Gateway service, but after read a lot, I can't find an official documentation of how to route with API Gateway to an EC2 server directly. All of the documentation speak about APIs REST or APIs with WebSockets, with DynamoDB or Lambda service. None of that is useful for me. I can't understand how to use API Gateway for my purpouse.
-Use NGINX on the EC2 which domain.com points, and route paths from this point. this's maybe a good solution, but I never worked with this software.
So, i'm so confused right now. Can anybody tell me which is the best solution for my problem, and why? I will really appreciate that.

The links I have read these days:
-Redirecting with htaccess to nodejs app (I don't know if using Apache is a good solution)
-https://www.reddit.com/r/aws/comments/71lz5v/applications_routing_based_on_url/ (This is a good post on Reddit)
-https://aws.amazon.com/es/blogs/aws/new-host-based-routing-support-for-aws-application-load-balancers/ (Use ALB and spend a lot of money, haha)
-AWS Route 53 - Domain name route to different ports of an Application load balancer (More of ALB, but this is so interesting)
-https://forums.aws.amazon.com/thread.jspa?threadID=152643 (This is the scenario most similar to mine, but poor man, never got answer)
Well, thanks to all for read and, if I violated any rule on the forum, please forgive me. Goodbye! :)

A: greetings from Colombia =)
My best advice here is to put Nginx upfront on those EC2 instances and use it as a proxy or load balancer, the best approach would be the one where you could even run multiple processes of your apps in the same EC2 instance providing a better scalability and balance the load using Nginx, here are two articles to accomplish this setup:
https://nodesource.com/blog/running-your-node-js-app-with-systemd-part-1/
https://nodesource.com/blog/running-your-node-js-app-with-systemd-part-2/
There are other options with more complex approaches as the ones you are describing, but I think this one is the simplest and cheapest.


text:
Q: What is the density of $1-X^3$ if $X$ is a Cauchy random variable? What is the density function of $Y=1-X^3$, if $X$ is a Cauchy random variable?
My approach:
$$Pr(Y<y)=Pr(1-X^{3}<y)=Pr(X<(1-y)^{-3})=\int^{y}_{-\infty}\left(1-\frac{1}{\pi(1+t^{2})}\right)^{-3}\:dt$$ - is this ok?
And then the density function would be the derivative of the function above?
EDIT1
$$Pr(Y<y)=Pr(1-X^{3}<y)=Pr(X>(1-y)^{-3})=1-\int^{(1-y)^{-3}}_{-\infty}\left(\frac{1}{\pi(1+t^{2})}\right)\:dt=1-A$$
The CDF for Cauchy distribution, according to Wikipedia Cauchy Distribution - do I use it correctly?
$$A=\frac{1}{\pi}arctan((1-y)^{-3})+\frac{1}{2} - \frac{1}{\pi}arctan(-\infty)-\frac{1}{2}=\frac{1}{\pi}arctan((1-y)^{-3})-\frac{1}{\pi}\frac{-\pi}{2}=\frac{1}{\pi}arctan((1-y)^{-3})+\frac{1}{2}$$
Than the distribution function would be the derivative of 1-A ?
is this correct?

A: Apart from the problem mentioned by @Avitus in a comment, let me mention that the identity
$$
P(X\lt g(x))=\int_{-\infty}^xg(f_X(t))\mathrm dt,
$$
where $f_X$ is the density of $X$, is quite wrong. Please use the correct
$$
P(X\lt g(x))=\int_{-\infty}^{g(x)}f_X(t)\mathrm dt.
$$
When, as in your case, the function $g$ is increasing and differentiable, this is also
$$
P(X\lt g(x))=\int_{-\infty}^{x}g'(s)f_X(g(s))\mathrm ds.
$$
Likewise, if $g$ is decreasing and differentiable and $Y=g^{-1}(X)$, then
$$
P(Y\lt x)=P(X\gt g(x))=\int_{g(x)}^{+\infty}f_X(t)\mathrm dt=\int_{-\infty}^{x}(-g'(s))f_X(g(s))\mathrm ds.
$$


text:
Q: Parse XML with Apex I am having the following XML:
<Fields><orderTAb.SapService>Bhagya/Comp/Comp_Total##FALSE$$FR2:LB9000400008##FR098990</orderTAb.SapService>
</Fields>

I tried:
    //Parsing the OrderInfoTab.dataServicePage field
                 if (xsr.getEventType() == XmlTag.START_ELEMENT && xsr.getLocalName() == 'orderTAb.SapService'){
                     xsr.next();
                     if(xsr.hasText()){
                         string dataService = xsr.getText();
                          if(dataService.indexOf('Bhagya/Comp/Comp_Total') != -1){
                             ServiceCalculationsettingsH = 'Total';
                         }

    //Reading
    if(reader.getEventType() == XmlTag.START_ELEMENT && reader.getLocalName() == 'orderTAb.SapService'){
            reader.next();
            if(reader.hasText()){

            if (reader.getText() == 'Bhagya/Comp/Comp_Total')
            {
            values[10] = '"'+reader.getText()+'"';
            QC.ServiceCal = '"'+reader.getText()+'"';
            System.debug('QC.ServiceCal1--------------------'+QC.ServiceCal);
                }
                 if (reader.getEventType() == XmlTag.END_ELEMENT && reader.getLocalName() =='orderTAb.SapService') {
                temp += string.join(values,',') + '\n';
                lstQuoteContent.add(QC);
                System.debug('CHP-50:   ' +lstQuoteContent );
                break;
            }
            reader.next();

//To display Node(Tag)
if(lstquotecontent.size() > 0){
            for(Integer i = 0 ; i < lstquotecontent.size() ; i++){
             if(lstquotecontent[i].ServiceCal != NULL)
                    quotecontentLineItem.addChildElement('ServiceCal', null, null).addTextNode(lstquotecontent[i].ServiceCal);
                 else
                    quotecontentLineItem.addChildElement('ServiceCal', null, null).addTextNode('');
                }

Node get display properly in XML response but showing null value.

A: Use the Apex DOM parser - it is way easier to get the code right:
String xml = '<Fields><orderTAb.SapService>Bhagya/Comp/Comp_Total##FALSE$$FR2:LB9000400008##FR098990</orderTAb.SapService></Fields>';
Dom.Document doc = new Dom.Document();
doc.load(xml);
System.debug(doc.getRootElement().getChildElement('orderTAb.SapService', null).getText());


text:
Q: How to get data from /wp-json/wp/v2/users/me i was trying to get the user data with JWT auth in wordpress.
i was send in the postman get request to /wp-json/wp/v2/users/me with the token that i get from /wp-json/jwt-auth/v1/token.
but i get this error:
{
    "code": "rest_not_logged_in",
    "message": "you are not logged in",
    "data": {
        "status": 401
    }
}

can someone help please

A: I was just doing this earlier, if you are trying to simply get user data from your wordpress website with Postman just simply do a request to:
/wp-json/wp/v2/users/
or directly to your user number:
/wp-json/wp/v2/users/User Number here
(you will need ACF to REST API plugin ) so you can see the endpoint acf field below author and template. If you use ACF
It seems that you are trying to get data securely or post data then I would recommend the following:
install: JWT Authentication for WP-API plugin
then edit your
.htaccess and add:
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

and also add the following to your wp-config.php
define('JWT_AUTH_SECRET_KEY', 'any-secret-code-you-want');
define('JWT_AUTH_CORS_ENABLE', true);

And finally you will need to send a POST request in Postman to:
/wp-json/jwt-auth/v1/token with the Header:
Content-Type
application/json

and the body:
{
    "username": "WordPressUserName",
    "password": "WordPressPassword"
}

Now Copy the Token in your results and create a new POST in Postman
and in the Headers add:
Authorization
Bearer **InsertYourToken**

And now you should have access to easly GET and POST data from your wordpress website.
you can also follow the video tutorial if you still get stuck, starting form this time:
https://youtu.be/fFNXWinbgro?t=300


text:
Q: grunt uglify usermin i am new to grunt ,i was watching this video..
https://www.youtube.com/watch?v=gIbfDxF69c8
original html(app/index.html)
<!-- build:js scripts/app.js -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<!-- endbuild -->

minified html(build/index.html)
<script src="scripts/libmin.js"></script>

i need
<script src="http://www.cdn.cdn/cdnfoler/libmin.js"></script>

my grunt code:
  grunt.registerTask('bobthebuilder',[
  'copy:task0',
  'useminPrepare',
  'concat',
  'cssmin',
  'uglify',
  'usemin'
  ]);

How can i replace the minified code folder to cdn url.
as i am plamning to upload this minified code to cdn.

A: I think you are looking for a function out of the box, but maybe should be a good idea to integrate cdnify grunt task to your workflow to do that
Take a look:  https://github.com/callumlocke/grunt-cdnify
you can make something like
dist: {
    html: ['<%=dist %>/*.html']
  }


text:
Q: Sine wave with different slope on each side Upfront note that English is not my first language, and my mathematical terminology might not translate very well (although google has helped).

(TL;DR at the bottom)

I want to describe the animation of a computer model using a mathematical formula. I need a function $F(x)$ that outputs a value (which will be used as a scale factor) in the range of $[0, 1]$, and takes the current animation progress (also in the range of $[0,1]$) as input $x$.
The goal of the animation is to provide a "fading" effect, with the object growing slowly at first but increasingly faster until the maximum size ($F(x) = 1$) has been reached. Previously I used a quadratic formula, but now I want to add a 'fading-out' animation (gradually shrinking the object back to $F(x) = 0$ after some time).
I'm looking for a type of curve that looks a bit like this (not enough reputation to post an image unfortunately). There's 3 segments in this curve:

*

*The first part is the 'fade-in' period. I did this with a simple quadratic formula at first.

*The middle part is the part where $F(x) > 1$. I'm not interested in it because I set the value back to $1$ in code. Whatever happens here doesn't matter, as long as $F\ge1$.

*The third and final segment is the 'fading-out' period. It should behave like a reverse-quadratic curve, shrinking fast at first but decreasing speed with increasing $x$'s.

I could use two separate formulas for this, one for fading-in and one for fading-out, but I'm interested in if this is possible using only a single formula. I want to be able to tweak the following points (annotated in the image linked above) to change the properties of the animation:

*

*$x_s$: The point in time where the objects starts with growing. $F(x)$ where $x$ is in $[0, x_s]$ should always be $\le0$. Values below zero will be be set back to zero in code.

*$x_t$: The point where the object is fully grown (finishing point of the fade-in animation) → $F(x_t) = 1$.

*$x_d$: The point where the size of the object starts to decrease again → $F(x_d) = 1$ (again).

*$x_f$: The point where the animation has finished → $F(x)$ where $x \ge x_f$ should be $\le0$ again.

(As per the definition of $x_t$ and $x_d$: $F(x) \ge 1$ if $x$ is in $[x_t, x_d]$.)
My current guess is that I should do this with a sinusoid. This poses the challenge of creating a sine-wave that's asymmetrical (because the duration of the fade- in and out animations are not the same). During my research I found this question, but I have not been able to use something like $F(x) = sin(x + a*sin(x))$ to work as I want it to. Maybe it's not the right solution for this problem, or maybe I'm too stupid to realize.
I'm not looking for a copy-pasteable formula, any help will be greatly appreciated. If there's a better way to do this than with a sine-wave I'd also like to know of course.
TL;DR/summary: I need a formula that creates a curve like this for an animation. I want to be able to tweak the points $x_s$, $x_t$, $x_d$, $x_f$ to change the duration and position of the fade-in and -out periods.


text:
Q: Are the definitions of addition of natural numbers as cardinals ($|A| + |B| =|A \cup B|$) and by recursion ($a+S(b) = S(a+b)$) related? In Peterson, Theory of Arithmetic ( available at Archive.org)  addition of whole numbers is defined in the following way.

If $A$ and $B$ are disjoint sets, and if $a$ is the cardinal number of $A$ and $b$ is the cardinal number of $B$, then $a + b$ is the cardinal number of $A\cup B$.

In set theory, addition of natural numbers is defined in the following way:

*

*$a+0=a$

*$a+S(b) = S(a+b)$.

How do these two definitions relate to one another? Should one consider that two different operations are defined? Or are we dealing here with two different ways to define the same operation?

A: In set theory the natural numbers play two different roles:

*

*Cardinals.

*Ordinals.

This is because of the peculiar property: there is essentially a unique way to well-order (or indeed linearly order) a finite set. And this becomes flagrantly false for infinite sets (at least those which can be well-ordered).
The arithmetic of cardinals is very incompatible with the arithmetic of ordinals, except for the finite case. For example, ordinal arithmetic is not commutative whereas cardinal arithmetic is.
This means that we can define the arithmetic of the natural numbers in two ways: treat them as cardinals, that is the first way you present; or treat them as ordinals, that is the second way you present.
Both methods are equivalent, and we can prove that assuming one of them holds, that the second holds as well. So this is really about what is convenient to you at the moment. It makes conceptual sense, especially if you are to talk about induction, to define the addition in the ordinal sense. But at the same time, you might want to have a definition which is induction free.
Of course, once you move away from set theory, the natural numbers tend to not be sets anymore, and then going through cardinal arithmetic becomes very convoluted and unnecessary (not to mention that in some of these contexts addition is already given). And on the other hand, the well-foundedness of the natural numbers (or equivalently: the susceptibility of the natural numbers to induction-based arguments) is an essential property of them, making the ordinal definition far easier to implement.

A: One wants cardinality to be a measure on sets and, for finite sets, the result of the measurement to be a natural number. For that, we can either define the measure of the disjoint union to obey the rules of addition of natural numbers, or define addition of natural numbers to obey the rules that make cardinality a measure.


text:
Q: Removing string characters form mysqli database and utilize two variables derived from database Good Day
Can anyone please just help me in the right direction with PhP and mysqli function ?
I have the following in a field called 'speed' in my database: 10240k/10240k.The first 10240k is the Upload speed and the second 10240k is the Download speed. Now I need to remove the 'k' the '/' and the last 'k'. then I need to devide the first by 1024 to get Mb and the same with the second.
Please help me in the right direction to achieve this.

A: You can first explode on the basis of "/" then you can substr(string,0,-1) to remove the last character from the string. After getting both upload speed and download speed you can convert them into Mb. I didn't convert it into Mb because you did not mention it is Kb or GB?
    <?php
$str = "10240k/10240k";
$str = explode("/",$str);
$UploadSpeed = substr($str[0], 0, -1);
$DownloadSpeed = substr($str[1], 0, -1);

?>


text:
Q: jupyter dropdown widget trigger action I have a seemingly simple intention, just have a dropdown widget in jupyter notebook to trigger some simple action. It sort of works, but following script actually seems to trigger the event three times, what am I doing wrong?
import ipywidgets as widgets
from IPython.display import display, clear_output
vardict = ["var1","var2"]
select_variable = widgets.Dropdown(
    options=vardict,
    value=vardict[0],
    description='Select variable:',
    disabled=False,
    button_style=''
)
def get_and_plot(b):
    clear_output
    print(select_variable.value)

display(select_variable)
select_variable.observe(get_and_plot)

And the output when I select item from dropdown is something like
var1
var2
var2

and getting longer with each selection.
What I want to get is a way to trigger action (print or something else) only once per selection, how do I achieve this?

A: You need to specify which trait you are listening to. Right now you are listening to all the traits.
When select an item on the dropdown, some private traits are being changed under the hood, which trigger the callback.
To avoid this, specify the trait you want to listen to with the names kwarg (can be either a trait name or a list of trait names)
select_variable.observe(get_and_plot, names='value')


text:
Q: Search and Replace Script Loader in Head Only Works in Footer I've got a function that uses script_loader_tag filter to search and replace adding asynch="asynch" attribute. It works.
I don't want this doing anything in the footer, but rather the header alone. The following code is working but inverse and I'm stumped. It's only adding the attribute to scripts in the footer...
function async_js_mssa(){
    //function to add async to all scripts
    function js_async_attr($tag){

    // Add async to all remaining scripts
    return str_replace( ' src', ' async="async" src', $tag );
    }
    add_filter( 'script_loader_tag', 'js_async_attr', 10 );
    }
add_filter('wp_head', 'async_js_mssa');

What am I missing? Thanks!

A: Can you try this, it was what I tried to explain in my comment. Again, this is just a guess.
function js_async_attr($tag){
   // Add async to all remaining scripts
   return str_replace( ' src', ' async="async" src', $tag );
}

add_filter( 'script_loader_tag', 'js_async_attr');

function remove_js_async_head(){
    // function to add async to all scripts
    remove_filter( 'script_loader_tag', 'js_async_attr');
}
add_action( 'wp_head', 'remove_js_async_head', 100);


text:
Q: Python raw_input for file writing I have the following code:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open('targetfile' , 'w')
print "What do we write in this file?"
targetfilefound.write("hello this is working!")
targetfilefound.close()

The script I'm creating should be able to write to a file that the user defines via raw_input. The above could be faulty at core, open to suggestions.

A: As pointed out by others, remove the quotes from target file as you have assigned it already to a variable.
But actually instead of writing as code you can use the with open as given below
with open('somefile.txt', 'a') as the_file:
    the_file.write('hello this is working!\n')

In the above case, you don't need to do any exception handling while processing the file. When-ever an error occurs the file cursor object is automatically closed and we dont need to explicitly close it. Even it writing to file it success, it will automatically close the file pointer reference.
Explanation of efficient use of with from Pershing Programming blog

A: Judging by the stuff the script is printing you probably want the user to input what should be printed to the file so:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()

Note: This method will create the new file if it does not exist. If you want to check whether the file exists you can use the os module, something like this:
import os

print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
if os.path.isfile(targetfile) == True:
    targetfilefound = open(targetfile , 'w')
    print "What do we write in this file?"
    targetfilefound.write(raw_input())
    targetfilefound.close()
else:
    print "File does not exist, do you want to create it? (Y/n)"
    action = raw_input('> ')
    if action == 'Y' or action == 'y':
        targetfilefound = open(targetfile , 'w')
        print "What do we write in this file?"
        targetfilefound.write(raw_input())
        targetfilefound.close()
    else:
        print "No action taken"


text:
Q: SIMPLE: Adding in Xcode? Here's some of my code.
When I try to echo i, the app crashes.
What's the problem with the code?
int i=0;

for (NSDictionary *rowthree in resultsthree) {
i++;
testLabel.text = i;

}

Thanks.

A: The code sample is pretty minimal, but at a guess: You can't directly set testLabel.text = i, since text is an instance of NSString, not an integer. You probably meant:
testLabel.text = [NSString stringWithFormat:@"%d", i];


text:
Q: Strtok realization on C I am making my own version of Strtok on C.
I almost completed, however, the last part I needed I found on the internet and I don't really understand what it does. Eventually I actually got what it does but still don't understand why it works. I am lacking of theory ;(
char* strtok_sad(char* str, const char* delim) {
    static char* next = 0;
    if (str) {
      next = str;
    }

    if (*next == 0) {
      return NULL;
    }

    char* c = next;
    while(strchr(delim,*c)) {
      ++c;
    }

    if (*c == 0) {
      return NULL;
    }

    char* word = c;
    while(strchr(delim,*c)==0) {
      ++c;
    }

    if (*c == 0) {
      next = c;
      return word;
    }

    *c = 0;
    next = c+1;
    return word;
}

Can somebody explain this part or at least send me an article where it is explained:
    *c = 0;
    next = c+1;

Thanks!

A: I will answer the non-offtopic version/part of the asked question.
*c = 0; sets to 0 whatever c points to. next = c+1; makes next to point one behind c. I assume that you can spot the similarity of that rephrasing and the specification of strtok().


text:
Q: Why do I have 40000 packages in my Angular 7 project ? How to remove unused dependencies? When launching npm audit in my console, I have the following output :
[...]
found 0 vulnerabilities in 40256 scanned packages
Why do I have 40000+ packages in my project ? This amount of packages seems insane to me, as I don't use this much libraries.
I've tried the following :

*

*Removing unused packages (Jasmine, Karma, ...).

*Using npm prune.

I found out that it's mainly due to Angular7's dependencies :

*

*When downgrading to Angular 5, I "only" have ~7000 packages.

*My package.lock.json file is almost 10000 lines long, and a lot of these are dependencies.

It bothers me because of these reasons :

*

*Having this much packages can bring frequent security issues.

*Launching npm install needs more resources and time, and I would like to optimise it more.

*I have a lot of unused packages that have nothing to do here (e.g I don't need some polyfills that are present, like Babel, as I don't want to develop a cross-browser solution).

Is it a bad idea to remove these unused packages ?
Why is there so many packages in a freshly created Angular 7 project ?
How do I remove unused Angular's dependencies ?

A: You can definitely remove the packages but a good idea would be to keep it.
Reason: We won't be knowing what package is using what other dependent package. So it is better not to remove it.
But don't worry. Before deploying, once you run ng build it will automatically remove the unused packages.


text:
Q: Task Scheduler .bat file run prompt Currently I continue my work on my ICT (Information Collector Tool) which is just taking note of the Hardware Specs, Serial Number, Programs, etc. of a PC to monitor it's health in case RAM breaks or in case the users start installing Software we aren't aware of. Of course they normally don't have Admin rights to install anything but non the less I would prefer to have a list ready in case we see something suspicious going on.
So I finally got to a stage where I try to work out a way to run the file so the user doesn't have to do anything nor got to see that it is running. This is just to avoid "stupid" questions. Ideally I would run a hidden instance of this but the Task Scheduler doesn't seem to accept the hidden attribute of Windows 10s Task Scheduler.
This is the line the task is running: cmd.exe /c start /min /D "\\<IP>\<PATH>\ICT" ICT.bat
Anyway. The work around is to start the window minimized which is absolutely fine by me. My current issue is the following, the Task Scheduler successfully start the bat file, however it still prompts me to click on a Run button as shown on Picture 1

Does anyone know of a way to solve this issue? Do I have to add the PC or script somewhere in the Internet option > Security tab? If possible I would like to only use the Task scheduler & the bat file that should run. I saw about some Powershell or vbs scripts but I don't really want to turn this into an inception of scripts where Script A start Script B to Start Script C. And who can guarantee me that the middle man script also gets a prompt. ;)
Every help is very much appreciated.

A: *

*Press Windows Key + S and enter Internet options. Select Internet
Options from the list of results.

*When the Internet Properties window opens, go to the Security tab
and click on the Custom Level button.

*A list of settings will appear. Locate "Launching applications and
unsafe files" and select Enable. Now click OK to save changes.

Got it from here.
Disabling UAC prompt maybe helps too. Unfortunately, you will have to make all of these changes on each computer or make an .reg key. Good luck! Works on pretty much all Windows versions.
Hope this helps,
K.


text:
Q: How to use group by with inner join in LINQ I'm trying to write a LINQ for the below query,
Select DIS.iDataItemID, DIS.iDataItemCurrentStatusID, DI.iDataTypeID,
DI.iEmployeeID, DI.iEmployerID, DI.iLinkID, DI.iSystemID, DI.sData,
DI.sEmployerCode, DI.sRecieptID, COunt(*)
from DataItem DI
INNER JOIN DataItemStatus DIS ON DIS.iDataItemID =
DI.iDataItemID
INNER JOIN RefDataItemStatus ON DIS.iDataItemCurrentStatusID
= RefDataItemStatus.iDataItemStatusID
AND DIS.iDataItemCurrentStatusID = 1 AND DI.iDataTypeID = 8
GROUP BY DIS.iDataItemID, DIS.iDataItemCurrentStatusID, DI.iDataTypeID,
DI.iEmployeeID, DI.iEmployerID, DI.iLinkID, DI.iSystemID, DI.sData,
DI.sEmployerCode, DI.sRecieptID

I have written the LINQ as below, Need to know how to use Group by on this,
from dataItem in msaDBContext.DataItem
                                 join dataItemStatus in msaDBContext.DataItemStatus on dataItem.iDataItemID equals dataItemStatus.iDataItemID
                                 join refDataItemStatus in msaDBContext.RefDataItemStatus on dataItemStatus.iDataItemCurrentStatusID equals refDataItemStatus.iDataItemStatusID
                                 where dataItemStatus.iDataItemCurrentStatusID == _processingStatus.iDataItemStatusID && dataItem.iDataTypeID == _dataType.iDataTypeID
                                 select new
                                 {
                                     iDataItemID = dataItem.iDataItemID,
                                     iDataItemCurrentStatusID = dataItemStatus.iDataItemCurrentStatusID,
                                     iDataTypeID = dataItem.iDataTypeID,
                                     iLinkID = dataItem.iLinkID,
                                     biRowVersion = dataItem.biRowVersion,
                                     sData = dataItem.sData,
                                     iEmployeeID = dataItem.iEmployeeID,
                                     iEmployerID = dataItem.iEmployerID,
                                     sEmployerCode = dataItem.sEmployerCode,
                                     iSystemID = dataItem.iSystemID,
                                     sReceiptID = dataItem.sRecieptID
                                 };


text:
Q: How to install zend framework on ubuntu 14.04 I have install zend framework using skeleton application on my machine ie ubuntu 14.04 LTS.
I follow following steps.

*

*create application base folder and run the following commands.

*cd/myproject/dir

*git clone git://github.com/zendframework/zendSkeletonApplication.git

*cd ZendskeletonApplication

*php composer.phar self-update

*php composer.phar install

*using the apache web server set virtual host
<VirtualHost *:80>
     ServerName zf2-tut.localhost
     DocumentRoot /var/www/html/zf2-tut/ZendSkeletonApplication/public
     SetEnv APPLICATION_ENV "development"
     <Directory /var/www/html/zf2-tut/ZendSkeletonApplication/public>
         DirectoryIndex index.php
         AllowOverride All
         Order allow,deny
         Allow from all
     </Directory>
 </VirtualHost>

*after i edit hosts page from etc folder and add there
127.0.0.1       zf2-tut.localhost localhost this line.

*at last run application as http://zf2-tut/localhost
but it shows uable to connect server.

Tell me Where it go wrong.
Help

A: It' not ZF-related problem.
You have added zf2-tut.localhost to the hosts file, but you are trying to access it with http://zf2-tut/localhost instead of  http://zf2-tut.localhost.
Can you make sure that the domain is consistent - including webserver's vhost.


text:
Q: How to use a colormap from pyplot.jl as a function in julia-lang What would be the way to get in Julia-lang, something similar to
import numpy as np
import matplotlib.pyplot as plt
i = 0, f = 255, N = 100
colors = [ plt.cm.viridis(x) for x in np.linspace(i, f, N) ]

in Python? Generally speaking, I am looking for a way to get the RGB list from a colormap using Pyplot.jl in Julia-lang with a desired number of colors (N).

A: This is easiest using PlotUtils (which is re-exported on using Plots):
julia> using PlotUtils

julia> cm = cgrad(:viridis);

julia> colors = [cm[i] for i in linspace(0,1,10)]
10-element Array{ColorTypes.RGBA{Float64},1}:
 RGBA{Float64}(0.267004,0.004874,0.329415,1.0)
 RGBA{Float64}(0.280935,0.155726,0.468508,1.0)
 RGBA{Float64}(0.242949,0.291862,0.537908,1.0)
 RGBA{Float64}(0.190784,0.406937,0.555933,1.0)
 RGBA{Float64}(0.147463,0.512137,0.556955,1.0)
 RGBA{Float64}(0.120243,0.618071,0.536316,1.0)
 RGBA{Float64}(0.209417,0.718547,0.472197,1.0)
 RGBA{Float64}(0.422721,0.805438,0.351155,1.0)
 RGBA{Float64}(0.710003,0.8685,0.169494,1.0)
 RGBA{Float64}(0.993248,0.906157,0.143936,1.0)


text:
Q: GPX file validation I am trying to make sure that an uploaded file is a valid gpx file and tried two different checks (for xml) as GPX is xml (kind of).
The first check rejects a valid file with the message no DTD found.
$dom = new DOMDocument;
$dom->Load($_FILES["gps"]["tmp_name"]);
if ($dom->validate()) {

}
else {
    echo '<script>alert("Not a valid GPS file!");</script>';
    exit();
}

The second check does NOT reject invalid files like jpg or pdf.
$xmlcontents = XMLReader::open($_FILES["gps"]["tmp_name"]);

$xmlcontents->setParserProperty(XMLReader::VALIDATE, true);

if($xmlcontents->isValid()) {
}
else {
    echo '<script>alert("Not a valid GPS file!");</script>';
    exit();
}

What am I doing wrong?!

A: Found a solution!
 $xml=simplexml_load_file($_FILES["gps"]["tmp_name"]);
if($xml ===  FALSE)
{
    echo '<script>alert("Not a valid GPS file!");</script>';
    exit();
}

This returns false for jpg, pdf and so on but accepts GPX.


text:
Q: Help required regarding Cypress 4200 coding I am a newbie when it comes to Cypress chips. I am developing a capsense keypad.
I recently started with CY8kit049. I can code into the chip on board. How can I code other PSOC 4200 chips too using it? The bootloader accepts bootloadable programs directly. But when the chips will be new, they won't have any bootloader loaded in them.
Any kind of help would be highly appreciated.


text:
Q: Invalid use of group function but there is no GROUP BY I am trying to run this query:
UPDATE `ps_category_lang` cl
  LEFT JOIN ps_product_shop p
    ON cl.id_category=p.id_category_default
     AND cl.id_shop=p.id_shop
     AND p.available_for_order =1
     AND p.visibility != 'none'
  LEFT JOIN ps_specific_price sp
    ON p.id_product=sp.id_product
    AND ((sp.`from` = '0000-00-00 00:00:00' OR NOW() >= sp.`from`)
    AND (sp.`to` = '0000-00-00 00:00:00' OR NOW() <= sp.`to`))
    AND (sp.id_shop=0 OR sp.id_shop=p.id_shop)
  SET cl.meta_title=CONCAT(
    SUBSTRING_INDEX(
      TRIM(cl.`meta_title`),
      'från',
      1
    ),
    'från ',
    FORMAT(
      ROUND(
        min(p.price-IF(sp.reduction>0,sp.reduction, 0)
      ) *
      (SELECT conversion_rate
         FROM ps_currency
         WHERE iso_code='SEK'
           AND deleted=0
      )
    ),
    0,
   'sv_SE'),
   ' kr.',
   SUBSTRING_INDEX(cl.`meta_title`, ' kr.', -1)
   )
   WHERE cl.`id_lang` = 7
     AND cl.meta_title LIKE '% från%'
     AND cl.meta_title LIKE '% kr.%'
     AND p.available_for_order= 1

but it gives the error ' #1111 - Invalid use of group function ', although there is no group by. Why is it giving this error?

A: You can't use aggregate functions directly in an UPDATE query - and any query that uses an aggregate function (such as min, in yours) gets an implicit group by added.

If you use a group function in a statement containing no GROUP BY
  clause, it is equivalent to grouping on all rows

manual ref
And to pare it down to  simple example:
update the_table set value = min(value)
will generate your `ERROR 1111 (HY000): Invalid use of group function.
To accomplish the intent of that query, you would need to do it this way:
update the_table set value = (select min(value) from the_table)
This means that the source of your error is this particular part of the query, min(p.price-IF(sp.reduction>0,sp.reduction, 0), and that in order to fix it, you would need to convert that to a subquery that calculates the value for you.

A: Solved it by using temp tables like this:
CREATE TEMPORARY TABLE tmp SELECT id_category_default, MIN(p.price-IF(sp.reduction>0,sp.reduction, 0)) AS minprice FROM ps_product_shop p LEFT JOIN ps_specific_price sp ON p.id_product=sp.id_product AND ((sp.`from` = '0000-00-00 00:00:00' OR NOW() >= sp.`from`) AND (sp.`to` = '0000-00-00 00:00:00' OR NOW() <= sp.`to`)) AND (sp.id_shop=0 OR sp.id_shop=p.id_shop) WHERE p.available_for_order= 1 GROUP BY p.id_category_default;
UPDATE `ps_category_lang` cl LEFT JOIN ps_product_shop p ON cl.id_category=p.id_category_default AND cl.id_shop=p.id_shop AND p.available_for_order =1 AND p.visibility != 'none' LEFT JOIN ps_specific_price sp ON p.id_product=sp.id_product AND ((sp.`from` = '0000-00-00 00:00:00' OR NOW() >= sp.`from`) AND (sp.`to` = '0000-00-00 00:00:00' OR NOW() <= sp.`to`)) AND (sp.id_shop=0 OR sp.id_shop=p.id_shop) LEFT JOIN tmp t on t.id_category_default=p.id_category_default AND t.minprice is not null
SET cl.meta_title=CONCAT(SUBSTRING_INDEX(TRIM(cl.`meta_title`),'från', 1), 'från ',FORMAT(ROUND(t.minprice)*(SELECT conversion_rate FROM ps_currency WHERE iso_code='SEK' AND deleted=0),0, 'sv_SE'),' kr.',SUBSTRING_INDEX(cl.`meta_title`, ' kr.', -1))
WHERE cl.`id_lang` = 7 AND cl.meta_title LIKE '% från%' AND cl.meta_title LIKE '% kr.%' AND p.available_for_order= 1 ;
DROP TEMPORARY TABLE tmp