text:
Q: expected value of sum of weights in a random directed graph Assuming we have a random directed weighted graph with $n$ nodes. Furthermore let us assume the nodes are divided into two categories:

*

*A node $i$ is of category C if there are only outgoing edges or only ingoing edges from/to $i$

*Otherwise a node $i$ is of category D
Let the number of nodes in category C be $c$,then the number of nodes in category D is simply $n-c$.
Let $p_1$ be the probability that there is an edge between two nodes of category $C$ (and we pick each direction with $p_1/2$) and let $p_2$ be the probability of an edge between two nodes $i$ and $j$ for all other cases (again picking each direction with probability $p_2/2$). We denote the weight going from a node $i$ to a node $j$ by $e_{ij}$, where the $e_{ij}$'s follow three different distributions (with means $\mu_1, \mu_2, \mu_3$ respectively) depending on following cases:

*

*$(i,j)\in D\times D$

*$(i,j)\in D\times C$ or $(i,j)\in C\times D$

*$(i,j)\in C\times C$
I am interested in calculating the expected value of $\sum_{j=1}^{n-1} e_{ij}-e_{ji}$.  For the cases where $i$, $j$ are both in the same category, the values will simply be zero by symmetry. But how can I calculate the other cases?
My idea was to first calculate the expected value of $\sum_{j=1}^{n-1} e_{ij}$ for the two cases of $i$:
i.e. if $i \in C$, then $$\sum_{j=1}^{n-1} e_{ij}=\sum_{j\in C} e_{ij} +\sum_{j\in D} e_{ij}=\frac{ \mu_3(c-1)p_1}{2} +\frac{ \mu_2(n-c)p_2}{2}$$
And if if $i \in D$, then $$\sum_{j=1}^{n-1} e_{ij}=\sum_{j\in C} e_{ij} +\sum_{j\in D} e_{ij}=\frac{ \mu_2 c p_2}{2} +\frac{ \mu_1(n-c-1)p_2}{2}$$
Then since if a node $i$ is in C it only has arrows in one direction, the expected 'net position' would be $\frac{ \mu_3(c-1)p_1}{2} +\frac{ \mu_2(n-c)p_2}{2}$
And for the other case, if $i$ is in D the expected 'net position' would be simply $0$ by symmetry.
Is this correct until now or am I missing something?
Thanks for any help!

A: Approved by my supervisor all calculations are correct and this is the solution to the expected net-positions:

*

*if $i \in C$: $\quad \pm (\mu_3 (c-1)p_1/2 + \mu_2 (n-c) p_2/2)$

*if $i \in D$: $\quad 0$


text:
Q: Sinatra: Specify order in which routes are searched when using multiple apps? I have a classic style Sinatra app, and I am adding a modular app to it with use MyModularApp.
This works fine, and routes from both the classic and modular apps are available when I run the classic app.  The problem is that it seems the routes from the modular apps are searched first and only then the are the apps from the classic app searched.  I would like the reverse behavior.  How can I achieve it?

A: Sinatra applications can be used as Rack middleware as well as an application in their own right. With use MyModularApp you're adding the module into the middleware stack, so it will see the request before the main application; this will happen wherever you have the use method in your source file.
When acting as middleware, Sinatra apps will forward the request down the stack if no route matches in the current app, and so this is why you see the current behaviour.
One way of getting it to work as you want would be to set up a custome not_found handler that calls your modular app:
not_found do
  MyModularApp.call(env)
end

Now if your main app doesn't have a route that matches the request the modular app will be called.

A: According to the Sinatra documentation:

Routes are matched in the order they are defined. The first route that matches the request is invoked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are there any tactics to work with preconditions with "and"? My goal is like below. Are there any tactics to solve these trivial goals?
Goal forall A (x : A) P Q,
  (forall y, P y /\ Q y) ->
  Q x.
Proof.
  intros. intuition. auto.
Abort.

(* a more complex version *)
Goal forall A (x : A) P Q R,
  (forall y, R -> P y /\ Q y) ->
  R ->
  Q x.
Proof.
  intros. intuition. auto.
Abort.

A: The tactic intuition does not work because that tactic is designed for propositional logic (i.e. it dos not the quantifier in forall y, R -> ...  There is another tactic for this, it is called firstorder.  Try it!


text:
Q: SQL query with parameters I use SQLite to merge two dataframes I have parameters in. Some work, others don't.
This works:
    s = path_autre_qdv+'\\' + fichier_in
    DATA = p.read_csv(s)
    con = sql.connect('test_db.sqlite')
    con.create_function('POWER', 2, sqlite_power)
    c = con.cursor()
    COM_DETAIL.to_sql('COM_DETAIL_SQL', con, if_exists='replace', index = False)
    DATA.to_sql('DATA_SQL', con, if_exists='replace', index = False)

    sq = """
            SELECT
                c.COM_CODE
                ,c.COM_NAME
                ,c.COM_LONG
                ,c.COM_LAT
                ,d.*
            FROM
                COM_DETAIL_SQL c
            INNER JOIN
                DATA_SQL d
                ON POWER((c.COM_LONG - d.longitude)/ ? ,2) + POWER((c.COM_LAT - d.latitude)/ ? ,2) <= 1;
            """
    par = (0.5, 0.5,)
    RES = read_query(con,sq,par)

This doesn't:
s = path_autre_qdv+'\\' + fichier_in
DATA = p.read_csv(s)
con = sql.connect('test_db.sqlite')
con.create_function('POWER', 2, sqlite_power)
c = con.cursor()
COM_DETAIL.to_sql('COM_DETAIL_SQL', con, if_exists='replace', index = False)
DATA.to_sql('DATA_SQL', con, if_exists='replace', index = False)

sq = """
        SELECT
            c.COM_CODE
            ,c.COM_NAME
            ,c.COM_LONG
            ,c.COM_LAT
            ,d.*
        FROM
            COM_DETAIL_SQL c
        INNER JOIN
            DATA_SQL d
            ON POWER((c.COM_LONG - d.longitude)/ ? ,2) + POWER((c.COM_LAT - d.latitude)/ ? ,2) <= 1
            AND d.? IS NOT NULL AND d.? IS NOT NULL AND d.? IS NOT NULL;
        """
par = (0.5, 0.5,cinqv,meanv,nonentecinqv,)
RES = read_query(con,sq,par)

Difference is last filter, with three new parameters: cinqv, meanv and nonentecinqv given in input of the function, and are columns of DATA dataframe.
The error :
OperationalError: near "?": syntax error


text:
Q: FIDO2 - Get Authenticator Info issue I am developing Android authenticator.I am getting {-125,0,1,4} byte array from webauthn client after pairing. When I decoding this array
-125 (0x83) -  MSG
1 (0x01) - length of the data
4 (0x04) - AuthenticatorGetInfo
I am not sure about 0 in this array. Please let me know is there any meaning for this 0.
For this request, I am sending response as CBOR data.
00a60182684649444f5f325f30665532465f563202816b686d61632d73656372657403506435323965353235383533343133663304a462726bf5627570f564706c6174f469636c69656e7450696ef505190400069f01ff
I am notifying above data by using Fido Status as follows.
for (byte[] frame : response.toFrames(mMTU)) {
    getFidoStatus().setValue(frame);
    mGattServer.notifyCharacteristicChanged(device, getFidoStatus(), true);
}

After that I am not getting any request/response from webauthn client. I am sending KEEPALIVE(0x82) command with value PROCESSING(0x01) for every kKeepAliveMillis(500ms). Is there any issue with my implementation?
Please help me to proceed this. Thanks in advance.

A: This speciciation fully explains for you
https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#ble-framing-fragmentation

CMD is 0x83 (MSG)
Length of DATA is 2 bytes: HLEN byte and LLEN byte.
In your case, length of DATA is 0x0001 (= 1). The DATA is 0x04


text:
Q: Java Thread.sleep(delay) not working Hi I'm trying to execute task every X seconds and I have problem with it:
Thread joinThread = new Thread(() -> {
    for (int i = 0; i < amount; i++) {
        Player player = new Player(user, RandomUtils.randomString(10), host, p, event.getSession());
        player.join();
    }

    try {
        Thread.sleep(delay);
    } catch (InterruptedException ignored) {
        ignored.printStackTrace();
    }
});

joinThread.start();

It looks like Thread.sleep(delay) is ignored because my thread is executing itself every ms instead of delay
Here's my join method:
public void join(){
    GameProfile profile = session.getFlag("profile");
    Client c = new Client(host, port, new MinecraftProtocol(name), new TcpSessionFactory(proxy));
    c.getSession().addListener(new SessionAdapter() {
        @Override
        public void packetReceived(PacketReceivedEvent event) {
            if (event.getPacket() instanceof ServerJoinGamePacket) {
                user.setBotAmount(u.getBotAmount()+1);
                user.addBot(event.getSession());
                System.out.println("Player bot joined");
            }
        }

        @Override
        public void disconnected(final DisconnectedEvent event) {
            if(event.getCause() != null) event.getCause().printStackTrace();
            user.setBotAmount(u.getBotAmount() -1);
        }
    });
    c.getSession().connect();
}

If remove player.join();, it's working like a charm.
Any advice? I don't see what I'm doing wrong.

A: First off, the body of a thread (the body of the run method) executes once.
You are trying to make a delay for each player. Then you need to put the Thread.sleep(delay) inside the loop after the player.join():
for (int i = 0; i < amount; i++) {
    Player player = ...;
    player.join();

    try {
        Thread.sleep(delay);
    } catch (InterruptedException reallyIgnored) {}
}

Otherwise, you are going to make a delay after all the players are already processed which makes no sense.
Make sure that the delay variable is set correctly. The Thread.sleep takes time in milliseconds. To feel the difference, the value is supposed to be >1000.


text:
Q: File Can Not Be Moved. ERROR: File not moved correctly from to ../productimage/Large/ $fileName = $_FILES["product-image"]["name"];
$pathAndName = "../productimage/Large/".$fileName;
$moveResult = move_uploaded_file($_FILES["product-image"]["tmp_name"] , $pathAndName);

if ($moveResult) {
  echo "File has been moved from " . $_FILES["product-image"]["tmp_name"] . " to " . $pathAndName;
  exit();
} else {
  echo "ERROR: File not moved correctly from" . $_FILES["product-image"]["tmp_name"] . " to " . $pathAndName;
  exit();
}

A: Can you confirm that the destination folder(../productimage/Large/) has correct write permissions (777) ?
I am afraid that the destination folder hasn't correct permissions.

A: try this code :
$fileName = $_FILES["product-image"]["name"];
$pathName = "../productimage/Large/";
$moveResult = move_uploaded_file($fileName , $pathName/$fileName);
if(is_writable($pathName)){ ///// verify directory chmod 777
if ($moveResult) {
echo "File has been moved from " . $fileName . " to " . $pathName; exit();
 }else {
 echo "ERROR: File not moved correctly from" . $fileName . " to " . $pathName; exit();
 }
}else{
exit("Failed to write to directory $save_directory");
}


text:
Q: No sound in Call of Duty over HDMI when used with an Asus monitor I connected a PS3 to an Asus 24" Monitor (Asus PB248Q) via HDMI. The monitor does not have internal speakers but has a jack for headphones.
If I connect a headset to the headphones jack I can hear the audio in the main PS3 menu (for example, the clicks that sound when you are selecting a user).
However, if I load Call of Duty, there is no sound coming out of the headset. The volume is fully turned up (both in the monitor's OSD and in PS3). Sound stops in the switch to CoD.
I notice that when Call of Duty loads, "HDMI" appears a couple times on the monitor so I assume that Call of Duty is doing some kind of HDMI initialization that ends up turning off sound.
By comparison, if the HDMI connection is made to a Sony Bravia TV, then is sound is fine for Call of Duty so it seems an issue specific to this monitor that does not have built-in speakers. I wonder if Call of Duty does some kind of handshake at load-time with the monitor and then turns off sound if it does not detect built-in speakers
Is there any setting I can configure to solve this issue?

A: I would guess that game is using output format not supported by monitor. Select 2 channel HDMI and disable all audio output formats in options except for Linear PCM 44.1 and 48 kHz. See if that helps.


text:
Q: Android: Pressing a button to reset the activity at a fast rate crashes the program I have a button set to reset the activity. When I press it too fast too many times, it not only queues up the activity (as in when I press back, there is another instance of the activity) and can crash. Is there anything I can do to prevent these things from happening?
The code I'm using in the onClick method:
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);

A: Try This
btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                                btn.setEnabled(false);
                Intent intent = getIntent();
                                startActivity(intent);
                                finish();

            }
        });

A: or just simply use
btn.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v) {
        btn.setEnabled(false);
        //your code here
        btn.setEnabled(true);
    }
}

A: you can use try/catch to be sure any crash does not happen and also you can use recreate() method to restart your activity:
   try{
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               button.setEnabled(false);

                recreate();

               button.setEnabled(true);
            }
        });
    }catch (Exception e ){
        Log.e("TAG",e.getMessage());
    }


text:
Q: Python TypeError when import "mlab" module in Abaqus PDE Windows Machine, Python 2.7 64 bit, Abaqus 6.14
I tried to call matlab function in Python scripts var "mlab" module. It ran well in the Python IDEL. But when importing "mlab" in ABAQUS PDE, I got an Python Error. TypeError coercing to Unicode:need string or buffer, list found. and ABAQUS was broken done, "ipc_CONNECTION_BROKEN","UnException TypeError:"'NoneType' object is not callable" in ignored.
Any help in this regard would be appreciated. Thanks!
enter image description here


text:
Q: Inserting images in ShareLaTeX I have no idea how to correctly define my graphics path on ShareLaTeX. In a Linux terminal my folder location would look like: \home\Libraries\Documents\paperimages
I'm sorry if this is asked on the usual, but I cannot find any real substantial help online.

A: For images in folder images, you use
\graphicspath{{images/}}

More folders require separate braced groups like above.

A: Here's the official guide on inserting images in ShareLaTeX: https://www.sharelatex.com/learn/Inserting_Images
In particular, this is how you set the path:
%Path in Windows format:
\graphicspath{ {c:/user/images/} }

%Path in Unix-like (Linux, OsX) format
\graphicspath{ {/home/user/images/} }


text:
Q: Increment Version Number in C# Code I am maintaining document version in database. lets say i want to update or increment the version number. i have tried this but it shows me the properties are read only?
string _versionDB = "1.0.0.0"

var version = new Version(_versionDB);
version.MajorRevision = version.Minor + 1; //error it says read only

Please can anyone elaborate me the proper way of increment version number?

A: You could create an extension method to perform the addition for you.  Still requires custom code; but if you're doing this in a lot of places having such a helper method is likely useful.  Below are a few such functions which may help.
public static class VersionExtension {

    public static Version IncrementRevision(this Version version) {
        return AddVersion(version, 0, 0, 0, 1);
    }
    public static Version IncrementBuild(this Version version) {
        return IncrementBuild(version, true);
    }
    public static Version IncrementBuild(this Version version, bool resetLowerNumbers) {
        return AddVersion(version, 0, 0, 1, resetLowerNumbers ? -version.Revision : 0);
    }
    public static Version IncrementMinor(this Version version) {
        return IncrementMinor(version, true);
    }
    public static Version IncrementMinor(this Version version, bool resetLowerNumbers) {
        return AddVersion(version, 0, 1, resetLowerNumbers ? -version.Build : 0, resetLowerNumbers ? -version.Revision : 0);
    }
    public static Version IncrementMajor(this Version version) {
        return IncrementMajor(version, true);
    }
    public static Version IncrementMajor(this Version version, bool resetLowerNumbers) {
        return AddVersion(version, 1, resetLowerNumbers ? -version.Minor : 0, resetLowerNumbers ? -version.Build : 0, resetLowerNumbers ? -version.Revision : 0);
    }

    public static Version AddVersion(this Version version, string addVersion) {
        return AddVersion(version, new Version(addVersion));
    }
    public static Version AddVersion(this Version version, Version addVersion) {
        return AddVersion(version, addVersion.Major, addVersion.Minor, addVersion.Build, addVersion.Revision);
    }
    public static Version AddVersion(this Version version, int major, int minor, int build, int revision) {
        return SetVersion(version, version.Major + major, version.Minor + minor, version.Build + build, version.Revision + revision);
    }
    public static Version SetVersion(this Version version, int major, int minor, int build, int revision) {
        return new Version(major, minor, build, revision);
    }

    /*
    //one day we may even be able to do something like this...
    //https://github.com/dotnet/csharplang/issues/192
    public static Version operator +(Version version, int revision) {
        return AddVersion(version, 0, 0, 0, revision);
    }
    public static Version operator ++(Version version) {
        return IncrementVersion(version);
    }
    */

}

Example Usage
void Main()
{
    Version myVersion = new Version ("1.2.3.4");
    myVersion = myVersion.IncrementRevision();
    Console.WriteLine(myVersion); //1.2.3.5
    myVersion = myVersion.IncrementMinor();
    Console.WriteLine(myVersion); //1.3.0.0
}

A: I know this is a bit old, but for anyone looking for how to do this, this may help:
string _versionDB = "1.0.0.0"

var version = new Version(_versionDB);

// Increment Major version
var newMajorVersion = new Version(version.Major+1,version.Minor,version.Build,version.Revision);
// Increment Minor version
var newMinorVersion = new Version(version.Major,version.Minor+1,version.Build,version.Revision);
// Increment Build version
var newBuildVersion = new Version(version.Major,version.Minor,version.Build+1,version.Revision);
// Increment Revision
var newRevisionVersion = new Version(version.Major,version.Minor,version.Build,version.Revision+1);

To return the string to save back to the database (an assumption based on your variable name):
_versionDB = newMajorVersion.ToString();


text:
Q: How do I change JSP and HTML indentation style in Eclipse? When I apply the automatic indentation in Eclipse IDE, on HTML or JSP files, I have that:
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Test</title>

Test.

But I would like to have that :
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Test</title>

Ceci est une page générée depuis une JSP.

So I dont know how to add a tab after head and html ?


text:
Q: Determining charging voltage under load I'm building a backup system for some computer hardware which is roughly a constant 20W of power at ~48V. I've built a 13S5P Li-Ion pack from the following cells. I'm experimenting with different charging voltages at the moment but I'm having a hard time charging the batteries under load.
I've set the charger to float at 4.2V/cell with the load connected. After fully charging, I'll disconnect the Power Supply, and the voltage drops immediately to ~3.2V/cell.
However, If I disconnect the load while charging, the batteries will stay at 4.2V/cell when disconnecting the Power Supply.
Do I need to charge the batteries at a higher voltage than 4.2V/cell? Do I need a better charger or power supply? I'm just not sure what I should be looking up to understand my problem better.
Thanks!


text:
Q: Unix date JavaScript: moment with timezone give wrong result I am trying to get date string from unix timestamp with timezone
let moment = require('moment-timezone');
    let date = moment.unix(1516812300).tz('Asia/Kolkata').format('YYYY-M-DD-H-mm-s');

The correct date is 2018/01/24 16:45:00 with timezone Asia/Kolkata but  the above code return this 2018-1-24-22-15-0

A: Unixtime do not have 'timezones'. You can recognize that it is always in UCT. And same unixtime will always produce different 'human' time in different timezones. 1516812300 is in fact Wednesday January 24, 2018 22:15:00 (pm) in time zone Asia/Kolkata (IST). Because unixtime is same in same moment in any place of universe, on Moon, Kolkata or in London. So, when you have a day, in Kolkata may be night, while unixtime is absolutely same. So, your 2018/01/24 16:45:00 UCT is relay to 22:15:00 in Kolkata.


text:
Q: Drawer layout над action bar Как сделать чтобы drawerlayout  был поверх экшнбар. Сейчас код такой
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_awesome_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        theme="@style/ThemeOverlay.AppCompat.ActionBar" />
    <android.support.v4.widget.DrawerLayout

        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <ListView
            android:id="@+id/lv_navigation_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@android:color/white" />

    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

Ставил внутрь и под дроуер не получается.
A: 1) Главным элементом сделайте DrawerLayout.
2) Дайте ему параметр
android:fitsSystemWindows="true"

3) Toolbar поместите внутрь FrameLayout, коий внутри DrawerLayout.
4) ???
5) Profit!


text:
Q: Как убрать кавычки в JSON? У меня есть БД из нее получаю JSON следующим способом
    String DB_PATH = "/data/data/com.example.apps/databases/";
    String myPath = DB_PATH + DBHelper.DATABASE_NAME;// Set path to your database
    String myTable = DBHelper.TABLE_CONTACT;//Set name of your table
    SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    String searchQuery = "SELECT  * FROM " + myTable;
    Cursor cursor = myDataBase.rawQuery(searchQuery, null );

    JSONArray json = new JSONArray();
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        int totalColumn = cursor.getColumnCount();
        JSONObject rowObject = new JSONObject();

        for(int i=0 ;  i< totalColumn ; i++) {
            if(cursor.getColumnName(i) != null) {
                try {
                    if(cursor.getString(i) != null) {
                        Log.d("TAG_NAME", cursor.getString(i));
                        rowObject.put(cursor.getColumnName(i), cursor.getString(i));
                    } else {
                        rowObject.put(cursor.getColumnName(i), "");
                    }
                }
                catch(Exception e) {
                    Log.d("TAG_NAME", e.getMessage());
                }
            }
        }
        json.put(rowObject);
        cursor.moveToNext();
    }
    cursor.close();
    Log.d("TAG_NAME_ALL", json.toString());
    return json.toString();

JSON получается какой необходим, за исключением одного значения latlng.
Я получаю - "latlng":"[54.601530521,55.918132215051]"
Нужно получить - "latlng":[54.601530521,55.918132215051]
Как избавиться от кавычек?

A: из комментарий и оригинал из stackoverflow.com

Если вам нужно быстро перевести строку на double, хоть и с грязным кодом, тогда вы можете сделать так:
String s = "[12.3456789,98.7654321]";
String trimmed = s.substring(1, s.length()-1);
String[] parts = trimmed.split(",");
double lat = Double.parseDouble(parts[0]);
double lng = Double.parseDouble(parts[1]);
Log.d("latlng", "lat="+lat+"  lng="+lng);

Это не красиво, но работает.


text:
Q: How to run at the same time tkinter app and thread? I need to run tkinter applications(init_main() function) and at the same time an additional thread (translate function()) that could perform some actions. As I did, it only started the application.
import threading
import tkinter as tk
from tkinter import ttk

WIDTH = "300"
HEIGHT = "150"
LANGUAGES = ("ru", "en")

def init_main(root):
    entry_text_box = tk.Text(root)
    entry_text_box.place(width=110, height=120, x=10, y=10)

    translate_text_box = tk.Text(root)
    translate_text_box.place(width=110, height=120, x=130, y=10)

    root.mainloop()

def translate(state):
    print("Translate function run")
    while state:
        pass

if __name__=="__main__":
    root = tk.Tk()
    root.title("Translator")
    root.geometry(WIDTH + "x" + HEIGHT)
    root.resizable(False, False)

    t1 = threading.Thread(target=init_main(root))
    t2 = threading.Thread(target=translate(1))
    t1.start()
    t2.start()

A: You don't have to thread tkinter's mainloop. Also the correct syntax of Thread should be Thread(target=function,args=(arg1,arg2,...))
import threading
import tkinter as tk
import time

WIDTH = "300"
HEIGHT = "150"
LANGUAGES = ("ru", "en")

def translate(state):
    while 1:
        print("Translate function run")
        time.sleep(1)

if __name__=="__main__":
    root = tk.Tk()
    root.title("Translator")
    root.geometry(WIDTH + "x" + HEIGHT)
    root.resizable(False, False)

    t = threading.Thread(target=translate,args=(1,))
    t.start()

    entry_text_box = tk.Text(root)
    entry_text_box.place(width=110, height=120, x=10, y=10)

    translate_text_box = tk.Text(root)
    translate_text_box.place(width=110, height=120, x=130, y=10)

    root.mainloop()

A: I'm pretty sure they haven't fixed multithreading in python... what you are looking for is the after method. The tkinter after method.
You can simply tell the application to run a function after a set amount of milliseconds.
root.after(10000, root.destroy)

or
root.after(1, translate)

multithreading can work, but it does not work well. It definitely doesn't scale. I know this doesn't allow you to pass your variable, but you will have to get creative with that.


text:
Q: Issue with training single class for Unet++ model.train()
for epoch in range(3):

  running_loss = 0.0
  for i,data in enumerate(train_loader,0):
    inputs,labels,_ = data
    inputs = inputs[:,None,:]
    #labels = labels[:,None,:]
    print(inputs.shape)
    inputs = inputs.to(device=device)
    labels = labels.to(device=device)

    optimizer.zero_grad()
    #print("Input: ", inputs.shape)
    #print("Labels: ",labels.shape)
    outputs = model(inputs)
    #thresh_output = threshold(outputs,0.5)
    loss = criterion(outputs,labels)
    #dice_score = dice_loss(thresh_output,labels).item()
    loss.backward()
    optimizer.step()
    #wandb.log({"Train_Loss":loss})
    if(i%500 == 0):
      scheduler.step()
    running_loss += loss.item()
    # if(i == 1000):
    #   break
    print("Epoch : {}, iteration : {} and Loss : {}".format(epoch+1,i+1,loss.item()))

The code is given above. I get the following error when I try to run it:
torch.Size([1, 1, 256, 256]) /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:1944: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. warnings.warn("nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.")
AttributeError Traceback (most recent call last) in () 16 outputs = model(inputs) 17 #thresh_output = threshold(outputs,0.5) ---> 18 loss = criterion(outputs,labels) 19 #dice_score = dice_loss(thresh_output,labels).item() 20 loss.backward()

2 frames /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in binary_cross_entropy(input, target, weight, size_average, reduce, reduction) 3053 else: 3054 reduction_enum = _Reduction.get_enum(reduction) -> 3055 if target.size() != input.size(): 3056 raise ValueError( 3057 "Using a target size ({}) that is different to the input size ({}) is deprecated. "

AttributeError: 'tuple' object has no attribute 'size'


text:
Q: extract a column from many files and paste together in a single file I have a number of files (between 250-20000) which each include two columns with  header file.
I want to extract the second column from these files and paste them all together in a single file so I can analyze it.
#Frame      Dih_00000
       1     -92.6371
       2     -97.9913
       3     -91.1572
       4     -89.9374
       5     -91.8934
       6     -93.1060
       7     -93.4912

files look like this.
would you please help me how can I do this using awk or a python script.

A: cat file.in | awk {'print $2'} > file.out

get the second column and save it in the file.out

A: You can do.
awk '$0=$2' files* > new_file

A: awk '{print $2}' dihed_*.dat > file.new

OR just use cut command
cut -d" " -f2 dihed_*.dat > file.new

EDIT
not know is it elegant solution or not but it fulfill your requirement.
tail -q -n +2  dihed_*.dat | awk '{print $2}' > file.new

And
tail -q -n +2  dihed_*.dat | cut -d" " -f2 > file.new

A: awk '{ a[FNR] = (FNR in a ? a[FNR] OFS : "") $2 } END{ for (i=1;i<=FNR;i++) print a[i] }' file1 file2 ...

The above assumes all of your files have the same number of lines. If that is not the case, tell us about it and update your question to post some more representative sample input (e.g. 3 small files of different lengths) and expected output.


text:
Q: RoR wrong number of arguments (0 for 1) form Hi I'm trying to create a form, that at the same time, creates a list and associates products to it.
The problem is that the form keeps raising
wrong number of arguments (0 for 1)
Extracted source (around line #10):
     7:     <%= f.text_area :description, placeholder:
     8:     "Compose a description for it ..." %>
     9:

     10: <%= l.fields_for :products do |builder| %>
     11: <%= render 'shared/product_form', :l => builder %>
     12: <% end %>
     13: <%= l.submit "Create", class: "btn btn-large btn-primary" %>

App Trace is
    app/views/shared/_list_form.html.erb:10:in `block in        _app_views_shared__list_form_html_erb__184644094_33330696'
    app/views/shared/_list_form.html.erb:1:in `_app_views_shared__list_form_html_erb__184644094_33330696'
    app/views/lists/new.html.erb:7:in `_app_views_lists_new_html_erb__973495114_33282228'

The code is as follows:
---view----
--list_form--
    <%= form_for(@list) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_field :name, placeholder:
              "Come up with a name for your list" %>

    <%= f.text_area :description, placeholder:
              "Compose a description for it ..." %>

        <%= f.fields_for :products do |builder| %>
        <%= render 'shared/product_form', :f => builder %>
        <% end %>
        <%= f.submit "Create", class: "btn btn-large btn-primary" %>
        <% end %>

--product_form--
     <%= f.text_field :name, "Name:" %>
     <%= f.text_area :description, :rows => 3 %>

---model---
--list--
      class List < ActiveRecord::Base
         attr_accessible :description, :name
         belongs_to :user
         has_many :products, :dependent => :destroy
         accepts_nested_attributes_for :products,  :reject_if => lambda { |a|                                 a[:name].blank? }, :allow_destroy => true

         has_many :list_categorization
         has_many :category, :through => :list_categorization

         validates :user_id, presence: true
         validates :name, presence: true, length: {maximum: 10}
         validates :description, length: {maximum: 140}

         default_scope order: 'lists.created_at DESC'

         def categorize!(category_id)
             list_categorization.create!(category_id: category_id)
         end
      end

--product--
    class Product < ActiveRecord::Base
         attr_accessible :description, :donated, :name
         validates :list_id, presence: true
         belongs_to :list
    end

---controllers---
--list_controller--
   def new
       @list = List.new
       @products = @list.products.build
   end

   def create
       @list = current_user.lists.build(params[:list]) if signed_in?
       if @list.save
       flash[:success] ="List " + @list.name + "created!"
       render 'new'
   end

--product_controller--
  def new
      @product = Product.new
  end

  def create
      @product = @product.build(params[:product]) if signed_in?
      if @product.save
      flash[:success] ="Product " + @product.name + "created!"
  end

You were right, I actually realized it after posting this, but now while trying to submit the form this happens:
The form contains 1 error.
* Name can't be blank
event tough I filled it correctly, this is what is getting passed
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
utf8: ✓
authenticity_token: 38CXjVORlj2RBgoTetIMoHomcVgOIlBU5rW3NTgkRkU=
list: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  name: list
  description: this is a list
  products_attributes: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
    '0': !ruby/hash:ActiveSupport::HashWithIndifferentAccess
      name: p1
      description: this is a product
commit: Create
action: create
controller: lists

A: Where did that l come from? I'm pretty sure you need to change it to f:
<%= form_for(@list) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_field :name, placeholder: "Come up with a name for your list" %>
    <%= f.text_area :description, placeholder: "Compose a description for it ..." %>

  <%= f.fields_for :products do |builder| %>
    <%= render 'shared/product_form', :l => builder %>
  <% end %>
  <%= f.submit "Create", class: "btn btn-large btn-primary" %>
<% end %>

Update
There are a few problems with your code. First of all when you call @list = current_user.lists.build(params[:list]) if signed_in? it means that if there is no user signed in that object won't be created at all. The proper way to do something like this would be with a before_filter in your controller.
Secondly @product = @product.build(params[:product]) won't work. You haven't initialized a Product object yet, and you haven't assigned it to @product yet. Also build is used for associations. You need to change this to @product = Product.new(params[:product]).
Lists controller:
before_filter :user_signed_in? # add to products controller as well
# if you need this filter only on certain actions then do:
# before_filter :user_signed_in?, only: [:new, :create]

def new
  @list = current_user.lists.build
  @products = @list.products.build
end

def create
  @list = current_user.lists.build(params[:list])
  if @list.save
    flash[:success] = "List " + @list.name + " created!"
    redirect_to lists_path # this part was missing!
  else # this was also missing
    render 'new'
  end # you had an 'if' with no 'end'
end

private

# add the following to Products controller as well, or if you
# use it a lot then place it in your application controller
def user_signed_in?
  unless signed_in?
    flash[:notice] = "You must first sign in"
    redirect_to sign_in_path
  end
end

Products controller:
def new
  @product = Product.new
end

def create
  @product = Product.new(params[:product]
  if @product.save
    flash[:success] = "Product " + @product.name + " created!"
    redirect_to @product
  else
    render 'new'
  end
end

As far as I remember however, the products#create action won't be used when saving a product through a nested form, the lists#create action will be used for both.
To learn more about nested forms have a look at these railscasts.
Once you've updated your code and gone through those videos, if you're still getting errors I would recommend to create a new question since this one is getting long and messy already :)

A: you forgot to do this:
rails generate migration add_remember_token_to_users


text:
Q: Jupyterlab can't map shortcuts: [additional property error] I am using Jupyterlab, 1.2.4. I tried the configuration below, but it gives an error. Any idea why?
Jupyter lab shortcuts

{
  "notebook:collapse-selected-outputs": {
    "command": "notebook:hide-cell-outputs",
    "keys": [
      "O"
    ],
    "selector": ".jp-Notebook:focus"
  },

  "notebook:expand-selected-outputs": {
    "command": "notebook:show-cell-outputs",
    "keys": [
      "O",
      "O"
    ],
    "selector": ".jp-Notebook:focus"
  },

  "notebook:clear-all-outputs": {
    "command": "notebook:hide-all-cell-outputs",
    "keys": [
      "Ctrl L"
    ],
    "selector": ".jp-Notebook:focus"
  },

  "notebook:collapse-all-code": {
    "command": "notebook:hide-all-cell-code",
    "keys": [
      "Shift O"
    ],
    "selector": ".jp-Notebook:focus"
  }
}

A: I just copied the same JSON format that's used in the System Defaults section and everything works. Copy this to the User Preferences section.
{
  "shortcuts": [
    {
      "command": "notebook:hide-cell-outputs",
      "keys": ["O"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:show-cell-outputs",
      "keys": ["O", "O"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:hide-all-cell-outputs",
      "keys": ["Ctrl L"],
      "selector": ".jp-Notebook:focus"
    },
    {
      "command": "notebook:hide-all-cell-code",
      "keys": ["Shift O"],
      "selector": ".jp-Notebook:focus"
    }
  ]
}

Tested on JupyterLab 1.2.6.


text:
Q: Ребята не могу разобраться в конфигурационном файле gulp для запуска проекта, выходит ошибка AssertionError [ERR_ASSERTION]: Task function must be specified
at Gulp.set [as _setTask] (C:\OpenServer\domains\opencart.loc\node_modules\undertaker\lib\set-task.js:10:3)
at Gulp.task (C:\OpenServer\domains\opencart.loc\node_modules\undertaker\lib\task.js:13:8)
at Object. (C:\OpenServer\domains\opencart.loc\gulpfile.js:32:6)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at requireOrImport (C:\Users\ignat\AppData\Roaming\npm\node_modules\gulp\node_modules\gulp-cli\lib\shared\require-or-import.js:19:11) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}
Вот сам код
// Подключаем Gulp и все необходимые библиотеки
var gulp           = require('gulp'),
        gutil          = require('gulp-util' ),
        sass           = require('gulp-sass'),
        browserSync    = require('browser-sync'),
        cleanCSS       = require('gulp-clean-css'),
        autoprefixer   = require('gulp-autoprefixer'),
        bourbon        = require('node-bourbon'),
        ftp            = require('vinyl-ftp');

// Обновление страниц сайта на локальном сервере
gulp.task('browser-sync', function() {
    browserSync({
        proxy: "opencart.loc",
        notify: false
    });
});

// Компиляция stylesheet.css
gulp.task('sass', function() {
    return gulp.src('catalog/view/theme/apple/stylesheet/stylesheet.sass')
        .pipe(sass({
            includePaths: bourbon.includePaths
        }).on('error', sass.logError))
        .pipe(autoprefixer(['last 15 versions']))
        .pipe(cleanCSS())
        .pipe(gulp.dest('catalog/view/theme/apple/stylesheet/'))
        .pipe(browserSync.reload({stream: true}))
});

// Наблюдение за файлами
gulp.task('watch', ['sass', 'browser-sync'], function() {
    gulp.watch('catalog/view/theme/apple/stylesheet/stylesheet.sass', ['sass']);
    gulp.watch('catalog/view/theme/apple/template/**/*.tpl', browserSync.reload);
    gulp.watch('catalog/view/theme/apple/js/**/*.js', browserSync.reload);
    gulp.watch('catalog/view/theme/apple/libs/**/*', browserSync.reload);
});

// Выгрузка изменений на хостинг
gulp.task('deploy', function() {
    var conn = ftp.create({
        host:      'hostname.com',
        user:      'username',
        password:  'userpassword',
        parallel:  10,
        log: gutil.log
    });
    var globs = [
    'catalog/view/theme/apple/**'
    ];
    return gulp.src(globs, {buffer: false})
    .pipe(conn.dest('/path/to/folder/on/server'));
});

gulp.task('default', ['watch']);

A: В gulp 4 поменялся синтаксис - если раньше можно указать функции для параллельного выполнения в [], то теперь необходимо использовать gulp.parallel
Например:
gulp.task('watch', ['sass', 'browser-sync'], function() {}

Теперь превратится в:
gulp.task('watch', gulp.parallel('sass', 'browser-sync'), function() {...})

https://gulpjs.com/docs/en/getting-started/creating-tasks
https://stackoverflow.com/questions/51098749/everytime-i-run-gulp-anything-i-get-a-assertion-error-task-function-must-be


text:
Q: Angular: pipe that transforms text to create hyperlink elements with stop propagation doesn't work I want to have something that finds URLs in text and make them clickable. So to achive this I have created a custom pipe:
@Pipe({
  name: 'urlify'
})
export class UrlifyPipe implements PipeTransform {
  transform(text: any): any {
    const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z\d+&@#/%?=~_|!:,.;]*[-A-Z\d+&@#/%=~_|])/ig;

    return text.replace(urlRegex, (url) => {
      return '' + url + '';
    });
  }
}

And that works as expected when I use it together with

But the problem is that in some cases wrapping div is clickable so I have to stopPropagation and preventDefault on  element.
So I have created a directive for that:
@Directive({
  selector: '[sfStopPropagation]'
})
export class StopPropagationDirective {
  @HostListener("click", ["$event"])
  public onClick(event: any): void {
    event.preventDefault();
    event.stopPropagation();
  }
}

And than just use this in the pipe return '' + url + '';
The problem is that is not working at all. I even tried to create a method in the pipe file and call it on click for the element but it also doesn't work (the same with ${ }):

And this is an example where I'm using it:

Can someone help me?


text:
Q: How to detect route change from browser router in react router dom 5 and react typescript I have route file like this (roter.tsx):
const Routes: FC<{}> = () => {
  const {state, dispatch} = useContext(AuthContext);
  return (
    <BrowserRouter>
      <Switch>
        {!state.isAuthenticated ? (
          <>
            <Switch>
              <Route component={Login} path="/login" exact />
              <Route component={DisplayTV} path="/display-tv" />
              <Redirect to="/login" />
              {/* <Route component={PageNotFound} /> */}
            </Switch>
          </>
        ) : (
          <>
            <Switch>
              <Route path="/" component={Dashboard} />
              <Route path="/profile" component={Profile} />
            </Switch>
          </>
        )}
      </Switch>
    </BrowserRouter>
  );
};

export default Routes;

and I put it on App.tsx:
import {Router} from "react-router-dom";
import {createBrowserHistory} from "history";
import Routes from "./router/router";
import {AuthProvider} from "./context/AuthContext";
import "./App.css";

function App() {
  const history = createBrowserHistory();
  return (
    <div className="App">
      <AuthProvider>
          <Router history={history}>
            <Routes />
          </Router>
      </AuthProvider>
    </div>
  );
}

export default App;

Is there a way for me to detect route changes every time the route changes? I want to create a logout function when the token expires and that function is executed when triggered by a route change


text:
Q: String SHA1 in Julia I have an ordered set of points (x,y pairs) I would like to use as a key in a dictionary.
My original approach in ruby was to get a string representation of the points and then SHA1 the results.
What would be the best way to accomplish this in Julia?
Edit:
The key that I want to create is the set of points, not the individual points within the set.
I have a process that creates a set of unique integer points and I want to see if I have encountered this particular set of points before.  I also want to store some information about this particular set of points.  For example how many times have I seen this configuration.
The length of the set of points varies between 20 and 180ish.
With a SHA1 hash of the string representation of these points I know that my key is going to be 40 characters long regardless of the length of the points.
In effect I'm using SHA1 to compress my key to keep the size of my dictionary as small as I can.  I would like this dictionary to grow to a fairly large size.

A: You can just use the points them directly as keys of a dictionary, e.g.
points = [(rand(),rand()) for i in 1:100]
a_dict = [p => rand(1:10000) for p in points]
@show points[1]
@show a_dict[points[1]]

produces
points[1] => (0.4374267407775083,0.32232663537074036)
a_dict[points[1]] => 4102

EDIT: The question is asking about lists of points rather than single pairs. Its hard to tell from your question, but if you wanted to throw out the lists of points, then I'd just use the hash function, which is what a dictionary uses:
julia> x = [(rand(),rand()) for i in 1:100];

julia> y = copy(x);

julia> z = [(rand(),rand()) for i in 1:100];

julia> hash(x)
0x2dd258e3af0ec93a

julia> hash(y)
0x2dd258e3af0ec93a

julia> hash(z)
0x6449b750e42e6bc6

julia> some_dict = [hash(x) => 1, hash(z) => 1]
Dict{Uint64,Int64} with 2 entries:
  0x6449b750e42e6bc6 => 1
  0x2dd258e3af0ec93a => 1

julia> if hash(y) in keys(some_dict)
         some_dict[hash(y)] += 1
       else
         some_dict[hash(y)] = 1
       end

julia> some_dict
Dict{Uint64,Int64} with 2 entries:
  0x6449b750e42e6bc6 => 1
  0x2dd258e3af0ec93a => 2

If you actually need to retrieve what the sets of points are though, which seems likely, then you can just use a dictionary directly with the set of points as the key, i.e.
julia> other_dict = [x=>1,z=>1]
Dict{Array{(Float64,Float64),1},Int64} with 2 entries:
  [(0.6453074757765922,0.0958215… => 1
  [(0.5283378708792779,0.8418390… => 1

julia> other_dict[y] += 1
2

julia> other_dict
Dict{Array{(Float64,Float64),1},Int64} with 2 entries:
  [(0.6453074757765922,0.0958215… => 1
  [(0.5283378708792779,0.8418390… => 2

This (using mutable keys) is perfectly fine in Julia (although bad things will happen if you change the keys of dictionary once they've been added, of course).


text:
Q: OpenCL for signal processing I'm looking to write signal processing code that will need the usual parallel primitives (e.g., scan(), reduce(), map(), and sort()) along with efficient routines for FFTs and dense vector/matrix operations to support stuff like principal component analysis, which would include finding eigenvectors & eigenvalues. Plenty of matrix inverses and multiplications as well. Host code will be C++11.
I'd like to use OpenCL to stay platform agnostic, but a few days of experimentation aren't given me confidence in the maturity of the tools. I like Boost.Compute in terms of the programming model and primitives, but am not sure if a LAPACK library like clMAGMA and FFT library FFTcl would play well with it in terms of data types, shared context, and async operations. I'm also seeing that the last update to clMAGMA was two years ago.
ViennaCL covers the FFTs and some matrix operations but doesn't help with LAPACK. VEXcl is only for sparse vectors/matrices.
None of this seems tricky with CUDA—install Nvidia's dev tools and go. All the up-to-date libraries are there, plus there's stuff like NPP to cover other things I may need. I'm not seeing much risk of incompatibilities between the libraries.
I'm curious if anyone else has gone this route with OpenCL. I'd like to do that, but I feel it's higher risk than going with CUDA, which appears to offer much less chance of running into unforeseen snags.


text:
Q: How to display all data in 3 columns from a table where the 4th column contains the same ID as another table? I have a site where I have users register into a database table and upon registering, I have a column that generates an AUTO_INCREMENT value labeled ID that assigns to a user.
**REGISTRATION TABLE**
(User info)  ( ID )

Once logged in to the site, I allow the user to submit a form that has 3 data fields and a 4th field that is hidden where the 4th field is an echo of their user ID to a separate table named PRODUCTS.
**PRODUCTS**

(data 1)  (data 2)  (data 3)  (echo of ID from REGISTRATION table)

I want to be able to give the registered user a confirmation page that displays all the data a user has entered into the PRODUCTS table (the first 3 columns of the PRODUCTS table, not the 4th ID column) so it would like something like this:
"Here are the products you entered:"
(data 1)  (data 2)  (data 3)
(data 1)  (data 2)  (data 3)
(data 1)  (data 2)  (data 3)

where the ID in the PRODUCTS table matches the ID in the REGISTRATION table.
There will be multiple users entering data into the PRODUCTS table where it could look like this:
**PRODUCTS**

(data 1)  (data 2)  (data 3)  ( ID1 )
(data 1)  (data 2)  (data 3)  ( ID2 )
(data 1)  (data 2)  (data 3)  ( ID1 )

I want to display the data entered ONLY by the current logged in user.
So if a user has an ID of 1, I want to display all of the entries that have an ID of 1.
And I want to display the data on a page in either a table or set of DIVs that keep the format of:
(data 1)  (data 2)  (data 3)
(data 1)  (data 2)  (data 3)
(data 1)  (data 2)  (data 3)

A: You can do it using select statement
select * from products where id = < logged user >

Also if u can't send logged user id to this query you can do it using if condition in your html render
but its bad solutions

A: You can use this code
  select id,data1,data2,data3
  from  REGISTRATION
  join Products
  where registraion.id = products.id
  Order by id;


text:
Q: How to display rich:notify notification after clicking a a4j:commandButton? After clicking a a4j:commandButton, i want to display a rich:notify that contain a message from my Model ?
How to trigger this notification just after clicking my commandButton ?
Here is the code that i use :
** DataTable *******
<rich:dataTable id="currencyDataTable"  value="#{s2MCurrencyModel.getAllS2MCurrency()}"
                var="currency" border="1">

                <rich:column>
                    <f:facet name="header">Task ID</f:facet>
                    <h:outputText value="#{currency.taskId}" />
                </rich:column>
........
                <rich:column>
                    <h:form>

                        <a4j:commandButton value="Delete"
                            render="currencyDeleteInfo"
                            oncomplete="#{rich:component('currencyDelete')}.show()"
                            disabled="#{!currency.status.equals('I')}">
                            <f:setPropertyActionListener
                                target="#{s2MCurrencyModel.selectedCurrency}"
                                value="#{currency}" />
                        </a4j:commandButton>
                    </h:form>
                </rich:column>
            </rich:dataTable>

<!-- =============   DELETE BOX  =============== -->
    <rich:popupPanel id="currencyDelete">
        <f:facet name="header">currency delete confirmation</f:facet>
        <f:facet name="controls">
            <h:outputLink value="#"
                onclick="#{rich:component('currencyDelete')}.hide(); return false;">
                X
             </h:outputLink>
        </f:facet>
        <h:form>
            <h:panelGrid id="currencyDeleteInfo">
                Do you want really to delete currency identified by:
                <h:outputText
                    value="#{s2MCurrencyModel.selectedCurrency.currencyCode}" />

                <h:panelGroup>
                <a4j:commandButton value="Delete"
                    oncomplete="#{rich:component('currencyDelete')}.hide();return false"
                    action="#{s2mCurrencyCtrl.deleteCurrency()}"
                    render="currencyDataTable"
                    />
                    **<rich:notify detail="#{s2MCurrencyModel.message}" stayTime="5000" summary="Notification" showShadow="true" />**
                <h:button value="Cancel" onclick="#{rich:component('currencyDelete')}.hide(); return false;"/>
                </h:panelGroup>
            </h:panelGrid>
        </h:form>
    </rich:popupPanel>

                    render="currencyDataTable"
                    />
                    <rich:notify detail="#{myModel.message}" stayTime="5000" />

i set myModel.message in deleteCurrency() method.
Regards,

A: Just add a FacesMessage to the FacesContext in the action of your command button like so:
public void deleteCurrency(){
//your other operations
FacesContext ctx = this.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Detail","Summary"); //FacesMessage has other info levels
ctx.addMessage(null,msg);
}


text:
Q: Read dictionary from `.txt` file into argparse I would like to read in a dictionary from a config .txt file into argparse
Current main.py code:
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('--config_1', action='store_true')
parser.add_argument('--config_2')
args = vars(parser.parse_args())

I can run my script like: python main.py @config.txt
Where config.txt contains --config_1
Specifically, I would like to read in config_2 from config.txt as a dictionary - something like:
--config_1
--config_2 {
    'key1': [],
    'key2': ['value1', 'value2']
}

This is a follow-up question to: Passing configs from `.txt` file into argparse? (Similar to youtube-dl's `--config-location`)

Edit: For clarification, I'm getting an error:
error: unrecognized arguments:  --config_2 { 'key1': [], 'key2': ['value1', 'value2'] }

A: The default reader, as documented should accept
--config_1
--config_2
value

The alternate that's also documented would accept
--config_1
--config_2 value

Both of these are equivalent to the user typing
python main.py --config_1 --config_2 value

This prefix mechanism does not add to the parsing power of argparse, it just provides a way of entering a large number of arguments as an editable file.
 --config_1
 --config_2
 "{'key1': [], 'key2': ['value1', 'value2']}"

may work, resulting a args.config_2 string value as quoted.  Parsing that as a dict is  up to you.
Loading your file as json might be better.
The key point is that the @ file is read right at the start of parsing, and strings inserted into the sys.argv list, just as though the user had typed them.  This is done before any real parsing is done.  The custom file reader, if any, should return a list of strings.
Other posters have asked about entering generic key:value pairs.  argparse does not handle this directly.  The answers to such questions nearly always involve a user provided parser/splitter, either as a custom type, action class, or post parsing action.  You don't get extra points for doing "everything" in `argparse.


text:
Q: Python - Getting text using selenium from text node I'm trying to scrape some information from a website using Selenium and Python and sometimes there's texts like this HZS stonks remaining... that does not have any name or label that I can get the text by:

I can get the mkt-card class element easily and I assume that I can somehow get it from the mkt-card element but I can't figure out how to do it.

A: This is how you can get the text in question:
from bs4 import BeautifulSoup
html = '''

some text

"HZS stonks remaining 0.14"

'''
soup = BeautifulSoup(html, 'html.parser')
stonks_text = soup.select_one('div.error').next_sibling
print(stonks_text)

This returns "HZS stonks remaining 0.14"
Next time do not post screenshots, but actual text.

A: As per the HTML:

the desired element is within a text node and is within it's parent element

Solution
To print the text HZS stonks remaining 0.14 you can use either of the following locator strategies:

*

*Using css_selector`:
print(driver.find_element(By.CSS_SELECTOR, "div.mkt-card").text)

*Using xpath:
print(driver.find_element(By.XPATH, "//div[@class='mkt-card']").text)


text:
Q: LaTeX2rtf with pdftooltip I'm using LaTeX2rtf to convert LaTeX article or report documents into rich text format. I also compile the PDF using pdfLaTeX. In my document, I use the pdfcomment package to create tooltips.
\documentclass{article}
\usepackage{pdfcomment}
\begin{document}
\pdftooltip{$a^2+b^2=c^2$}{An equation}
\end{document}

The tooltips are correctly rendered in the PDF version.
However, when I run
latex2rtf

\pdftooltip[*options*]{*item*}{*tooltip*} is rendered as item and tooltip. If item is a float, or equation, then the float or equation is shown. tooltip is always shown as text.
This is correct as far as LaTeX2rtf is concerned, but I would like to modify this behavior so that I don't have to tidy up my document too much.
Question: How can I force LaTeX2rtf to ignore tooltip and just process the item argument? I am looking for a solution that will work with a document that contains lots of \pdftooltips, so using the \iflatextortf switch doesn't really work (too much added complexity). Ideally I would be able to define something in the preamble or pass an option to LaTeX2rtf.

A: Without modifications to the latex2rtf program code, the only way is conditional processing. Latex2rtf automatically sets the \iflatex2rtf condition true, while for pdflatex it is false by default.
\documentclass{article}
\usepackage{pdfcomment}
\newif\iflatextortf
\begin{document}
\iflatextortf
$a^2+b^2=c^2$
\else
\pdftooltip{$a^2+b^2=c^2$}{An equation}
\fi
\end{document}


text:
Q: Transpose SSIS XML Elements from rows to columns in powershell We have a requirement to pull out the version information for all of our packages per project and cross reference that with the version information in SSISDB. I figured i would extract the .dtproj xml info I need into a table and then do a compare.
As a novice Powershell developer this is as far as I have got. It gives me the exact info I need but the data is per row as it appears in the xml file. I would like the data in a table format as follows

Name
versionMajor
VersionMinor
VersionBuild

PackageName1
1
0
5

PackageName2
1
0
21

here is the xml snippet
<SSIS:PackageMetaData SSIS:Name="SomePackage.dtsx">
              <SSIS:Properties>
                <SSIS:Property SSIS:Name="ID">{C55A0E46-B4E5-4CE5-8387-277E0472906F}</SSIS:Property>
                <SSIS:Property SSIS:Name="Name">SomePackage</SSIS:Property>
                <SSIS:Property SSIS:Name="VersionMajor">1</SSIS:Property>
                <SSIS:Property SSIS:Name="VersionMinor">0</SSIS:Property>
                <SSIS:Property SSIS:Name="VersionBuild">5</SSIS:Property>
                <SSIS:Property SSIS:Name="VersionComments">
                </SSIS:Property>
                <SSIS:Property SSIS:Name="VersionGUID">{9A60744B-6F04-41BF-9F0C-A820BBD3FDCA}</SSIS:Property>
                <SSIS:Property SSIS:Name="PackageFormatVersion">6</SSIS:Property>
                <SSIS:Property SSIS:Name="Description">
                </SSIS:Property>
                <SSIS:Property SSIS:Name="ProtectionLevel">0</SSIS:Property>
              </SSIS:Properties>

this is my code
$namespace = @{SSIS = "www.microsoft.com/SqlServer/SSIS"}
$packageXpath = "//SSIS:PackageMetaData//SSIS:Property"
$packageNodes = Select-Xml -Path $path -XPath $packageXpath -Namespace $namespace | ForEach-Object{$_.Node}
$packageNodes | Format-Table

Looking for the easiest way to do this. I have seen examples using regular expressions to transpose the data from a file and also examples where the element names (not the attributes) are the columns I need using @{Label}.
Thanks in advance.

A: Here, try this:
[xml]$xml=@'
<PackageMetaData>
    <Properties>
        <Property Name="ID">{C55A0E46-B4E5-4CE5-8387-277E0472906F}</Property>
        <Property Name="Name">SomePackage</Property>
        <Property Name="VersionMajor">1</Property>
        <Property Name="VersionMinor">0</Property>
        <Property Name="VersionBuild">5</Property>
        <Property Name="VersionComments"></Property>
        <Property Name="VersionGUID">{9A60744B-6F04-41BF-9F0C-A820BBD3FDCA}</Property>
        <Property Name="PackageFormatVersion">6</Property>
        <Property Name="Description"></Property>
        <Property Name="ProtectionLevel">0</Property>
    </Properties>
</PackageMetaData>
'@

$props=$xml.PackageMetaData.Properties.Property

$hash=@{}

$props|%{
    $hash.Add($_.Name,$_.'#text')
}

[pscustomobject]$hash

Output should look like this:

Which is perfect for exporting to CSV / Xlsx

A: Assuming

*

*your XML indeed has the namespace declaration xmlns:SSIS="www.microsoft.com/SqlServer/SSIS"

*it can have multiple SSIS:PackageMetaData elements

you could use below code to loop through and output what you want from it.
I'm using a Here-String for the xml content, but in real life you would read it from a file using
$xml = New-Object System.XML.XMLDocument
$xml.Load("full path of the XML file")

[xml]$xml = @'
<SSIS:Packages xmlns:SSIS="www.microsoft.com/SqlServer/SSIS">
    <SSIS:PackageMetaData SSIS:Name="SomePackage.dtsx">
        <SSIS:Properties>
            <SSIS:Property SSIS:Name="ID">{C55A0E46-B4E5-4CE5-8387-277E0472906F}</SSIS:Property>
            <SSIS:Property SSIS:Name="Name">SomePackage</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionMajor">1</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionMinor">0</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionBuild">5</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionComments"></SSIS:Property>
            <SSIS:Property SSIS:Name="VersionGUID">{9A60744B-6F04-41BF-9F0C-A820BBD3FDCA}</SSIS:Property>
            <SSIS:Property SSIS:Name="PackageFormatVersion">6</SSIS:Property>
            <SSIS:Property SSIS:Name="Description"></SSIS:Property>
            <SSIS:Property SSIS:Name="ProtectionLevel">0</SSIS:Property>
        </SSIS:Properties>
    </SSIS:PackageMetaData>
    <SSIS:PackageMetaData SSIS:Name="SomeOtherPackage.dtsx">
        <SSIS:Properties>
            <SSIS:Property SSIS:Name="ID">{1234ABCD0E46-777-888-999-AAAABBBBCCCC}</SSIS:Property>
            <SSIS:Property SSIS:Name="Name">SomeOtherPackage</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionMajor">1</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionMinor">0</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionBuild">21</SSIS:Property>
            <SSIS:Property SSIS:Name="VersionComments"></SSIS:Property>
            <SSIS:Property SSIS:Name="VersionGUID">{9A60744B-6F04-41BF-9F0C-A820BBD3FDCA}</SSIS:Property>
            <SSIS:Property SSIS:Name="PackageFormatVersion">6</SSIS:Property>
            <SSIS:Property SSIS:Name="Description"></SSIS:Property>
            <SSIS:Property SSIS:Name="ProtectionLevel">0</SSIS:Property>
        </SSIS:Properties>
    </SSIS:PackageMetaData>
</SSIS:Packages>
'@

$result = $xml.Packages.PackageMetaData| ForEach-Object {
    [PsCustomObject]@{
        Name         = ($_.Properties.Property | Where-Object { $_.Name -eq 'Name' }).'#text'
        VersionMajor = ($_.Properties.Property | Where-Object { $_.Name -eq 'VersionMajor' }).'#text'
        VersionMinor = ($_.Properties.Property | Where-Object { $_.Name -eq 'VersionMinor' }).'#text'
        VersionBuild = ($_.Properties.Property | Where-Object { $_.Name -eq 'VersionBuild' }).'#text'
    }
}

# output on screen
$result | Format-Table

# output to Csv file
$result | Export-Csv -Path 'path to the result.csv' -NoTypeInformation

Output on screen:
Name             VersionMajor VersionMinor VersionBuild
----             ------------ ------------ ------------
SomePackage      1            0            5
SomeOtherPackage 1            0            21


text:
Q: Upload spring-boot jar into GCE Instance using terraform What is the best way copying some-spring-boot.jar into GCE Instance?
I thought this is quite a common task, but after googling found zero documentation about it.
I have already generated service account in GCP and saved all the stuff into gcp-credentials.json :
{
  "type": "service_account",
  "project_id": "some project",
  "private_key_id": "someid",
  "private_key": "some key",
  "client_email": "xxx@developer.gserviceaccount.com",
  "client_id": "xxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxdeveloper.gserviceaccount.com"
}

Here is what I'm doing after googling for hours:
terraform {
    required_providers {
        google = {
            source = "hashicorp/google"
        }
    }
}

provider "google" {
    version = "3.5.0"
    credentials = file("gcp-credentials.json")
    project = "some project"
    zone = "us-central1-a"
}

resource "google_compute_instance" "vm_instance" {
    name = "my-instance"
    machine_type = "e2-medium"
    #metadata_startup_script = file("startup.sh")

    tags = [
        "http-server",
        "https-server"]

    boot_disk {
        initialize_params {
            image = "some image with jdk"
        }
    }

    network_interface {
        network = "default"
        access_config {}
    }

    provisioner "file" {
        source = "../../../target/my-jar-1.0.0.jar"
        destination = "/tmp/my-jar-1.0.0.jar"

        connection {
            type = "ssh"
            user = "root"
            private_key = file("gcp-credentials.json").private_key
            agent = "false"
        }
    }
}

Whenever I run it says
[ERROR] Error: Missing required argument
[ERROR]
[ERROR]   on main.tf line 43, in resource "google_compute_instance" "vm_instance":
[ERROR]   43:         connection {
[ERROR]
[ERROR] The argument "host" is required, but no definition was found.

Any help will be really appreciated

A: Not tested (also I have never used Terraform towards GCP), try:
host = self.network_interface.0.network_ip

Line of thought:

*

*the host indeed seems required (as per docs for connection)

*the same docs hint on the special self variable:

Expressions in connection blocks cannot refer to their parent resource
by name. Instead, they can use the special self object.
The self object represents the connection's parent resource, and has
all of that resource's attributes.

*

*rest is my guess how to get an IP address from a GCP instance


text:
Q: What .NET collection provides the fastest search I have 60k items that need to be checked against a 20k lookup list. Is there a collection object (like List, HashTable) that provides an exceptionly fast Contains() method? Or will I have to write my own? In otherwords, is the default Contains() method just scan each item or does it use a better search algorithm.
foreach (Record item in LargeCollection)
{
    if (LookupCollection.Contains(item.Key))
    {
       // Do something
    }
}

Note. The lookup list is already sorted.

A: If you don't need ordering, try HashSet<Record> (new to .Net 3.5)
If you do, use a List<Record> and call BinarySearch.

A: I've put a test together:

*

*First - 3 chars with all of the possible combinations of A-Z0-9

*Fill each of the collections mentioned here with those strings

*Finally - search and time each collection for a random string (same string for each collection).

This test simulates a lookup when there is guaranteed to be a result.

Then I changed the initial  collection from all possible combinations to only 10,000 random 3 character combinations, this should induce a 1 in 4.6 hit rate of a random 3 char lookup, thus this is a test where there isn't guaranteed to be a result, and ran the test again:

IMHO HashTable, although fastest, isn't always the most convenient; working with objects. But a HashSet is so close behind it's probably the one to recommend.
Just for fun (you know FUN) I ran with 1.68M rows (4 characters):

A: Keep both lists x and y in sorted order.
If x = y, do your action, if x < y, advance x, if y < x, advance y until either list is empty.
The run time of this intersection is proportional to min (size (x), size (y))
Don't run a .Contains () loop, this is proportional to x * y which is much worse.

A: If it's possible to sort your items then there is a much faster way to do this then doing key lookups into a hashtable or b-tree. Though if you're items aren't sortable you can't really put them into a b-tree anyway.
Anyway, if sortable sort both lists then it's just a matter of walking the lookup list in order.
Walk lookup list
   While items in check list <= lookup list item
     if check list item = lookup list item do something
   Move to next lookup list item

A: If you're using .Net 3.5, you can make cleaner code using:
foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
  //dostuff
}

I don't have .Net 3.5 here and so this is untested.  It relies on an extension method.  Not that LookupCollection.Intersect(LargeCollection) is probably not the same as LargeCollection.Intersect(LookupCollection) ... the latter is probably much slower.
This assumes LookupCollection is a HashSet

A: Have you considered List.BinarySearch(item)?
You said that your large collection is already sorted so this seems like the perfect opportunity?  A hash would definitely be the fastest, but this brings about its own problems and requires a lot more overhead for storage.

A: If you aren't worried about squeaking every single last bit of performance the suggestion to use a HashSet or binary search is solid.  Your datasets just aren't large enough that this is going to be a problem 99% of the time.
But if this just one of thousands of times you are going to do this and performance is critical (and proven to be unacceptable using HashSet/binary search), you could certainly write your own algorithm that walked the sorted lists doing comparisons as you went.  Each list would be walked at most once and in the pathological cases wouldn't be bad (once you went this route you'd probably find that the comparison, assuming it's a string or other non-integral value, would be the real expense and that optimizing that would be the next step).

A: In the most general case, consider System.Collections.Generic.HashSet as your default "Contains" workhorse data structure, because it takes constant time to evaluate Contains.
The actual answer to "What is the fastest searchable collection" depends on your specific data size, ordered-ness, cost-of-hashing, and search frequency.

A: You should read this blog that speed tested several different types of collections and methods for each using both single and multi-threaded techniques.
According to the results, a BinarySearch on a List and SortedList were the top performers constantly running neck-in-neck when looking up something as a "value".
When using a collection that allows for "keys", the Dictionary, ConcurrentDictionary, Hashset, and HashTables performed the best overall.


text:
Q: Let $G$ a graph without a $P_4$ as induced subgraph. Prove that either $G$ or $\overline{G}$ is disconnected. I've got the following problem:

Let $G$ a graph not containing a $P_4$ (path with 4 nodes) a an induced subgraph.
  Prove, that either $G$ or $\overline{G}$ is disconnected.

Initially, I assumed the above condition means that the graph does not contain any paths of length $\geq 3$. However, this disregards the fact that we're talking about induced subgraphs here. So, if there are "long" edges between nodes of a longer path, it would not be considered induced $P_4$ and would thus be admissible. This leaves me stuck.
How do I prove the above statement?

A: We have to assume that $G$ is finite and has more than one vertex. A graph with one vertex is obviously a counterexample. For an infinite counterexample take the integers as vertices and join $x$ to $y$ if $\max(x,y)$ is odd.
Theorem. If $G$ is a finite graph with more than one vertex, and if both $G$ and $\overline G$ are connected, then $G$ contains a $P_4$ as an induced subgraph.
Proof. Suppose $G$ is a minimal counterexample. Thus $G$ has more than one vertex, both $G$ and $\overline G$ are connected, and (since $P_4$ is self-complementary) neither $G$ nor $\overline G$ contains $P_4$ as an induced subgraph.
Clearly $G$ has more than two vertices. Choose a vertex $v$. Since $G-v$ is not a counterexample and has more than one vertex, either $G-v$ or $\overline G-v$ is disconnected. Without loss of generality, assume that $G-v$ is disconnected. Since $\overline G$ is connected, $v$ is not isolated in $\overline G$. Choose a vertex $x$ which is adjacent to $v$ in $\overline G$, i.e., $xv\notin E(G)$. Since $G-v$ is disconnected, we can choose a vertex $y$ so that $x$ and $y$ are in different components of $G-v$. Now it is clear that $d_G(x,y)\ge3$, so $G$ contains a geodesic path of length at least $3$ connecting $x$ to $y$.


text:
Q: Using setContentPane() method correctly I have created a java program in which i have used the setContentPane() method on a JFrame. My problem is that the frame does not get updated by the new panel immediately but gets updated upon resizing the frame.
In my program the size of the JFrame is 600,600.
To temporarily avoid this problem, after the setContentPane() method , I have applied a set of 2 statements:-
Frame.setSize(601,601);
Frame.setSize(600,600);

This resizes the frame and brings it back to its original size without showing much change to the user. This is working good and the panel is getting updated.
My question is, am I making any mistake and there is some other way to do it? Or I can continue using this trick? Please answer if there is any other(right) way to do it.


text:
Q: Makefile removes argument post white space value when called from bash script I've written a small bash script to invoke a make command.
The makefile expects args='<arguments to be passed to program>' argument. (i.e. make a args='--aaa 5 --bbb 6')
The problem is when I use the script to invoke the make command, the argument is truncated on its first white space.
For example, when executing make a args='--aaa 5' through the script, the args variable is '--aaa and not '--aaa 5'
I've also tried adding quotes and single quotes but the result is the same.
When I invoke the make command manually through terminal the, the args variable gets all the arguments and their values as expected.
Here is the script call :
args="args='--aaa 5 --bbb 6'"
make a ${args}

A: You have to double-quote $args to preserve the whitespace.
make a "$args"

I'm assuming the Makefile correctly handles the value once it receives it.


text:
Q: Access to account, contact and opportunity on lead conversion I was practicing for Sales Cloud and came across the following dummy question:

Joe is the record owner of a Lead. A Lead sharing rule has been
  defined so that leads owned by Joe are shared with public group called
  'Joe's Team'.When the Lead is converted to an Account, Contact, and
  Opportunity, who will have access to these records assuming that a
  private sharing model in place on these objects and there are no
  sharing rules defined for these objects?
a.    Joe, all members of the public group, Joe's Team, and anyone above
  any group member in the role hierarchy will be able to access the
  three records.
b.    Joe and anyone above him in the role hierarchy will be able to
  access the three records
c.    Joe, all members of the public group, and Joe's Team will be able
  to access the three records
d.    Joe will be the only person who will be able to access the Account,
  Contact, and opportunity records.

Now, according to my understanding members of the public group would not have access to the Account Contact and Opportunity records so a and c is discarded.
Option b is applicable only when sharing using role hierarchy checkbox is checked - which is not mentioned in the question at all.
So, I think the answer should be option d.
Can anyone please validate if my thought process is correct or if there is anything else that I need to consider

A: You can't currently disable Grant Access Using Hierarchy for standard objects, so the correct answer is "b." If, at some point in the future, this changes, then "d" would become a possibility, but the question would require that that it explicitly calls out if Grant Access Using Hierarchies is enabled or not.


text:
Q: jtable - how to set gap between columns Is there a way to add a gap between JTable columns or rows?
(without using a cell renderer)

A: look at setIntercellSpacing and/or setRow/ColumnMargin. Okay, looked up the methods:
// set gap between rows, api in JTable
table.setRowMargin(int)
// set gap between columns, api in TableColumnModel
table.getColumnModel().setColumnMargin(int)
// convenience for setting both row and column gaps
table.setIntercellSpacing(Dimension)


text:
Q: Raspberry Pi: External HDD "wrong fs type, bad option" I'm trying to set up an external hard drive to my Pi. I got one from the store with 2TB of storage. I plugged it in and ran lsblk:
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
loop0         7:0    0 38.8M  1 loop /snap/certbot/1344
loop1         7:1    0 38.7M  1 loop /snap/certbot/1435
loop2         7:2    0 84.4M  1 loop /snap/core/11610
loop3         7:3    0 51.5M  1 loop /snap/core20/1085
sda           8:0    0  1.8T  0 disk
mmcblk0     179:0    0 29.8G  0 disk
├─mmcblk0p1 179:1    0  256M  0 part /boot
└─mmcblk0p2 179:2    0 29.5G  0 part /

I tried to mount it to /var/www/drive2 but I got this error:
mount: /var/www/drive2: wrong fs type, bad option, bad superblock on /dev/sda, missing codepage or helper program, or other error.

How can I fix this? Is there something wrong with my HDD?


text:
Q: selenium python fullscreen_window I want to put full window, but it only leaves me 800x600
def driver(request):
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument('--headless')

try:
    web_driver = webdriver.Chrome(chrome_options=options)
    yield web_driver
    web_driver.close()
except Exception as e:
    pytest.skip(e)

I'm doing tests with selenium, but the window is very inferior. help how could you put maximum window.

A: You can set the window size by setting it:
web_driver = webdriver.Chrome(chrome_options=options)
# Resize the window to the screen width/height
web_driver.set_window_size(1024, 720)


text:
Q: Cannot add border to the button I want to add the border to my button in the webpage, following is what I do.
The strange things it that the color set works, which can control the font color within the button, but the sets for the border does not work.
I have tried some solutions with highest votes, but none of them works.
.btn-general {
    color: #fff;
    border-color: #fff;
    border-style: solid;
    border-width: 2px;
    border-radius: 10px;
    padding: 12px 26px 12px 26px;
    font-size: 16px;
    font-weight: 400;
}

A: I tried you code, and it seems to be working fine. Are you using bootstrap or something like that? Because if you are, it can be that Bootstrap is overwriting your CSS. You can try putting !important behind your css lines to see if it works.
<style>
.btn-general {
    color: #fff !important;
    border-color: #fff !important;
    border-style: solid !important;
    border-width: 2px !important;
    border-radius: 10px !important;
    padding: 12px 26px 12px 26px !important;
    font-size: 16px !important;
    font-weight: 400 !important;
}

</style>
<button class="btn-general">
Test
</button>


text:
Q: How to integrate Google Realtime Playground with Android App? I am in serious need to any tutorial for integrating Google Realtime Playground with Android App.
I know it is possible as people has done this:
https://play.google.com/store/apps/details?id=com.goodow.realtime.android.playground
I've found the code for the same on GitHub:
https://github.com/goodow/realtime-android-playground
But code shared here is also not complete.
Please help me with some useful links and tutorials.
Regards,
RJ

A: There is no official library that wraps Realtime functionalities for Android for now. What goodow does is to wrap a WebView and wrap non-native calls.
See also the sources on the GitHub Project.


text:
Q: Is there a REGEXP_LIKE equivalent function in Apache Drill? Anything in Drill which can be similar to:
REGEXP_LIKE ( <COLUMN>, <REGULAR_EXPRESSION< ) RETURNS BOOLEAN ?

A: The following code should mimic REGEXP_LIKE in drill. Just make sure to replace '1' with a text string that does not occur in the column and that the regular expression captures the entire string (by appending .*) .
SELECT CASE WHEN REGEXP_REPLACE(<COLUMN>, <REGULAR_EXPRESSION>,'1') = '1' THEN true ELSE false END

A: REGEXP_LIKE is not supported as per drill docs.
If you can proceed with wildcard, you can check ILIKE.
ILIKE ( <COLUMN>, <VALUE> ) RETURNS BOOLEAN

Sample command:
SELECT * FROM employee WHERE ILIKE(name, '%DEV%')"

You can ask the community if somebody has written any UDF for this.
Or you can write your own UDF for this function. Check drill docs for details of writing a UDF.