text:
Q: IntelliJ javaFX keeps showing "com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged" error for background image I am trying to give my scene a background image, however, the program keeps saying:
"Aug 25, 2022 10:52:00 AM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not find stylesheet: jar:file:///C:/Users/Muhammed%20Zain%20Muneem/IdeaProjects/CSIAFXMLL/build/libs/FXMLCSIA-1.0-SNAPSHOT.jar!/java/cssstyle/style.css"
And when I am setting it in scene builder, the background image is displayed perfectly. Its only when I run the program the image doesn't display. I have tried using different images, fxml files, and I have made the images are in the right file path, and this is evident as scene builder picks it up.
my main code:
package com.example.fxmlcsia;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("logInPage.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 800, 400));
        primaryStage.show();
    }

}

My FXML code:
<?xml version="1.0" encoding="UTF-8"?>

<?import java.net.*?>
<?import com.jfoenix.controls.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="800.0" styleClass="root" stylesheets="@../../../../java/cssstyle/style.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.fxmlcsia.controller">
   <children>
      <AnchorPane layoutX="516.0" prefHeight="400.0" prefWidth="284.0" style="-fx-background-color: #000000;">
         <children>

            <Hyperlink layoutX="77.0" layoutY="357.0" text="Forgot Password?" textFill="#f5f5f5" underline="true" />
            <Button fx:id="signIn" blendMode="LIGHTEN" layoutX="15.0" layoutY="315.0" mnemonicParsing="false" prefHeight="31.0" prefWidth="256.0" style="-fx-background-color: #f05241;" text="Sign In" textFill="WHITE" />
         </children>
      </AnchorPane>

      <Button fx:id="sUbutton" blendMode="LIGHTEN" layoutX="56.0" layoutY="252.0" mnemonicParsing="false" prefHeight="31.0" prefWidth="256.0" style="-fx-background-color: #f05241;" text="Sign Up" textFill="WHITE" />
   </children>
</AnchorPane>

CSS FIle Code:
.root {
-fx-background-image:url("../images/background.jpg");
-fx-background-size:cover;
}

I haven't added any controller file because I haven't made one yet.
Thanks.


text:
Q: Azure Storage Account Networking Tab is not shown/Accessible I am the only one who is not able to access the Azure Storage Account Networking tab in West Europe or other people are having the same problem?

A: There was an issue with the Storage account which trigger in Azure Service Health yesterday evening.
Between approximately 11:20 UTC and 17:58 UTC on 27 Sep 2021, you were identified as a customer who may have been unable to see Firewall and Virtual Network blade and Private Endpoint Connection blades under the Networking section of your Storage account in your Azure Portal. Programmatic methods such as PowerShell, Azure CLI, and APIs were not affected. Additionally, certain features may be unavailable when creating new storage accounts. This issue is now mitigated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Append newly query request ?page=2 to existing query ?q=python I search http://127.0.0.1:8000/search/?q=python in my project home page which return results with multiple pages:
Here is my pagination sinppet

  {% for i in page.page_list %}
    {% if i == page.number %}

        {{ i }}

    {% else %}

        {{ i }}

    {% endif %}
  {% endfor %}

When I click page 2 in the page, it issue request http://127.0.0.1:8000/search/?page_number=2 rather than http://127.0.0.1:8000/search/?q=python?page_number=2
How append the ?page_number=2 to its existing query?

A: You can use {% if %} tag like this:
{{ i }}


text:
Q: Stop listview scrolling when popupmenu showing up I have a listview whose each item has a button. When clicking an item's button, I would like to show a popupmenu has many options (about 8 options).
The problem is when the popupmenu showing up, the listview scrolls along to it so it distract from what item was clicking on.
Please help!
My code for showing the popup menu:
// 'view' is the button in a row
private void showPopupMenu(final View view){
    PopupMenu popupMenu = new PopupMenu(getContext(), view);
    popupMenu.getMenuInflater().inflate(R.menu.menu_popup, popupMenu.getMenu());
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if (mMenuItemClickListener != null){
                int position = (int) view.getTag();
                return mMenuItemClickListener.onMenuItemClick(item, (int) getItemId(position), position);
            }

            return false;
        }
    });
    popupMenu.show();
}

A: Create a method like below:
private void stopScroll(AbsListView view)
{
    try
    {
        Field field = android.widget.AbsListView.class.getDeclaredField("mFlingRunnable");
        field.setAccessible(true);
        Object flingRunnable = field.get(view);
        if (flingRunnable != null)
        {
            Method method = Class.forName("android.widget.AbsListView$FlingRunnable").getDeclaredMethod("endFling");
            method.setAccessible(true);
            method.invoke(flingRunnable);
        }
    }
    catch (Exception e) {}
}

Whenever/wherever you want to stop scrolling just call this method like this stopScroll(listView);


text:
Q: From where java extract the default encoding? from where java extract the default encoding ?
I tried the following code on 2 plateforms : redhat 4 and centos 5
public class EncodingTest {
    public static void main(String args[]) throws Exception{
    System.out.println(System.getProperty("file.encoding"));
    System.out.println(
               new java.io.OutputStreamWriter(
                              new java.io.ByteArrayOutputStream()).getEncoding()
               );
    }
}

I have two different results,redhat UTF-8 and for centos ASCII. It's the same java installation and version (1.4). I launch java without parameter -Dfile.encoding.
Thanks.

A: The default platform charset is taken from the OS and depends on the default locale. If you get different results on different machines these machines have different default locale. Now it depends on your needs. If you wish your application to work exactly the same way on all platform pass charset using -Dfile.encoding


text:
Q: Как узнать оператора у пользователя на android? Как узнать оператора у пользователя на android?
A: Как то так
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    telephonyManager.getNetworkOperatorName();
    //или
    telephonyManager.getNetworkOperator();

и не забываем про манифест

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>


text:
Q: Java File Parsing - Go word by word I have a file content as Follows:
Sample.txt:
Hi my name is john
and I am an engineer. How are you
The output I want is an arrayList of string like [Hi,my,name,is,john,and,I,am,an,engineer,.,How,are,you]
The standard java function parses it as line and I would get an array containing the lines. I am confused as to which approach I should use to get the following output.
Any help is appretiated.

A: .nextLine() will get one whole line but .next() will go word by word

A: You could check out using the Scanner class with the .next() method.

A: This will read the file and collect all words into a list of strings.
Edit: Updated so as to handle punctuation and the likes as distinct words:
    try {
        List<String> words = Files.lines(Paths.get("/path/to/sample.txt"))
            .map(line -> line.split("\\b"))
            .flatMap(Arrays::stream)
            .filter(w -> !w.trim().isEmpty())
            .collect(Collectors.toList());

        return words;
    } catch (IOException e) {
        // handle error
    }

A: If you are getting the strings as whole lines, but just want the words, you could use .split(" ") on the words, as this would return an array containing individual words with no spaces. If you want to do this within the file reading, you could use something like the following...
public ArrayList<String> readWords(File file) throws IOException {
  ArrayList<String> words = new ArrayList<String>();
  String cLine = "";
  BufferedReader reader = new BufferedReader(new FileReader(file));
  while ((cLine = reader.readLine()) != null) {
    for (String word : cLine.split(" ")) {words.add(word);}
  }
  reader.close();
  return words;
}

which would return an ArrayList<String> containing all of the individual words in the file.
Hope this helps.


text:
Q: How to build executable jar using maven-jar-plugin and groovy? I have an example app with a main class in Groovy and a main class in Java. maven-jar-plugin successfully builds an executable jar when the Java class is specified as the main class but not when the Groovy class is. Let me demonstrate. Here is my build:
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>3.0.2</version>
      <configuration>
        <archive>
          <manifest>
            <mainClass>com.example.hello.JavaHello</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.1</version>
      <configuration>
        <compilerId>groovy-eclipse-compiler</compilerId>
        <verbose>false</verbose>
        <source>${java.compiler.version}</source>
        <target>${java.compiler.version}</target>
      </configuration>
      <dependencies>
        <dependency>
          <groupId>org.codehaus.groovy</groupId>
          <artifactId>groovy-eclipse-compiler</artifactId>
          <version>${groovy-eclipse-compiler.version}</version>
        </dependency>
        <dependency>
          <groupId>org.codehaus.groovy</groupId>
          <artifactId>groovy-eclipse-batch</artifactId>
          <version>2.4.3-01</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>

Then compiling and running:
$ mvn -q clean package && \
>   jar xf target/hello-world-1.0-SNAPSHOT.jar META-INF/MANIFEST.MF && \
>   cat META-INF/MANIFEST.MF && rm -r META-INF && \
>   java -jar target/hello-world-1.0-SNAPSHOT.jar
Manifest-Version: 1.0
Built-By: tytk
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_66
Main-Class: com.example.hello.JavaHello

Hello from Java!

Then, changing the mainClass to:
<mainClass>com.example.hello.GroovyHello</mainClass>

And running the same command:
$ mvn -q clean package && \
>   jar xf target/hello-world-1.0-SNAPSHOT.jar META-INF/MANIFEST.MF && \
>   cat META-INF/MANIFEST.MF && rm -r META-INF && \
>   java -jar target/hello-world-1.0-SNAPSHOT.jar
Manifest-Version: 1.0
Built-By: tytk
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_66
Main-Class: com.example.hello.GroovyHello

Error: Could not find or load main class com.example.hello.GroovyHello

Each class just has a main method with a println statement.
So how can I get an executable jar with my groovy classes? maven-shade-plugin works but I don't want a fat jar - I want dependencies excluded.

A: I see your note about dependencies excluded, which is why you don't want to use maven-shaded-plugin. I'm not sure how well that will work with a Groovy class.
(But it's worth noting explicitly to myself and other Java newbies: maven-jar-plugin does not include dependencies)
First possibility: is Java barfing because it can't find Groovy, and really wants it?
I found a SO answer about ability to load main classes that extend from dependent classes.
I know that a plain Groovy script file, without an explicit class declaration, that the compiler wraps that up in a class it extends from (Groovy's) Script. I don't know what happens if you write your own explicit class - I'd unpackage the .jar and use a Java Decompiler to look at the generated code, to see if that gives you any clues.
Second possibility: package name
That feature about Groovy creating a class for you if you haven't explicitly declared one, doesn't seem to be able to put that implicit Java class inside a package based on the directory structure. I thought this worked in the past: not sure if I'm seeing a bug here, a new feature, or if I'm mis-remembering.
So, two ways to fix this:

*

*Add a package declaration to your Groovy script.
package com.example.hello
println "I'm Groovy!"

*Have your maven mainClass tag refer to the class without package namespace (ie: GroovyHello instead of com.example.hello.GroovyHello


text:
Q: I appear to be offline when I'm online
Possible Duplicate:
Why does it say "that player is offline" when that player is most certainly online?

My friends are telling me that I appear as "offline" in their friends lists while playing Diablo 3. I can join up with them, quest with them, trade with them, talk to them, and I am most definitely online.
I opened up my social window and the icon in the top left shows that I'm "offline" or gray icon. So I switch it to the "online" or green icon. This does nothing, as each time I open the social window, it's back to "offline".
Does anyone know how to fix this issue?


text:
Q: How to revoke JWT Bearer Token in .net core API I have implemented  JWT Bearer token base authentication and authorization. I am using the below code for destroying the JWT token or logout the current user but it's not working.
//var claim = _httpContextAccessor.HttpContext.User.Claims;
            // var users = await _userManager.FindByNameAsync(_httpContextAccessor.HttpContext.User.Identity.Name);
            //  var identity = _httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
            // foreach (var item in claim)
            // {
            //     identity.RemoveClaim(item);
            // }

            await _signInManager.SignOutAsync();

A: It is not possible to cancel/revoke a JWT token during user's logout, it is not straightforward, but there is a workaround to that. You can try following the steps below:

*

*Set a reasonable expiration time on tokens

*Delete the stored token from client side upon log out

*Have DB of no longer active tokens that still have some time to live

*Query provided token against The Blacklist on every authorized request

I am also pasting 2 links below that myself found very helpful:

*

*How to log out when using JWT

*Canceling JWT tokens in .NET Core


text:
Q: Edit XML via HTML Form (PHP) I'm trying to create a form that will let you edit the contents of an xml tag. i currently have a form.php:
<?php
$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;
?>

<form method="post">
    <textarea name="name"><?php echo $welcome ?></textarea>

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

<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$xml->asXML());
fclose($handle);
}
?>

and welcome.xml:
<welcome>
    <item>
        <name>$welcome</name>
    </item>
</welcome>

when i press submit it doesn't save what's entered, it just refreshes the page and deletes whatever the value in the xml file was before..
UPDATE
The form works now, but I've added a reset button, i need it to clear the xml file so it only has the <welcome> tags. I've changed $data->item->name=$_POST['welcome']; to $data=''; but it deletes the text and keeps the tags still.

A: You can do it with simplexml.
To read data from xml:
$data = simplexml_load_file('welcome.xml');

$welcome = $data->item[0]->name;

And to write data:
$data = simplexml_load_file('welcome.xml');

$data->item[0]->name = $_POST['welcome'];

$handle = fopen("welcome.xml", "wb");
fwrite($handle, $xml->asXML());
fclose($handle);

EDIT:
For the question in the comment:
<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('welcome.xml');
$data->item->name=$_POST['name'];
$handle=fopen("welcome.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}

$data=simplexml_load_file('welcome.xml');
$welcome=$data->item->name;

?>

<form method="post">
    <textarea name="name"><?php echo $welcome ?></textarea>

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


text:
Q: Unable to install Linux container in 14.04 LTS Firstly I tried to update Linux with the command :
sudo apt-get update

It failed with errors and I resolved it with command :
sudo rm /var/lib/apt/lists/* -vf

Which was mentioned in the answers to Failed to fetch update on Ubuntu 14.04 LTS (Trusty Tahr), and then it displayed this :
rm: cannot remove '/var/lib/apt/lists/partial': is a directory

After that I tried using commands :
sudo apt-get update

It came with the same error as mentioned in Failed to fetch update on Ubuntu 14.04 LTS (Trusty Tahr).
And neither can I now install lxc.

A: The following command:
sudo apt-get clean

will delete the contents of those directories.
Then, try the command again:
sudo apt-get update

If you continue to get the error, change mirrors and repeat the process over again.

Alternatively, you can run this instead:
sudo rm -R /var/lib/apt/lists/* -vf

The -R flag is recursive so it will delete directories as well as files.


text:
Q: How can i select a IE tab from its handle I have the Internet Explorer Handle and i have the tab Handle that i want to select.
How can i select this tab?
I know how to select a tab by Index (Using IEAccessible), but i can't get the tabIndex from the handle. The Spy++ doesn't sort them in order.

A: There's a way hack way  to do it.  Not supported, and dependent upon the version of IE as well as the language of the OS.
In an IE instance, the control with the name "Tab Row" is the
thing that holds all the various tabs. Given an IAccessible
corresponding to that thing, it's easy to enumerate the children,
and get the tabs. An automation app can inspect the URL on each
tab, and then call IAccessible.accDoDefaultAction(0), to activate
a tab by URL.  That's the basic approach.
But I couldn't figure how to directly get the "Tab Row" control
of an IE instance, from a SHDocVw.WebBrowser COM object, which is
what an app gets out of SHDocVw.ShellWindowsClass.  I tried it a
million ways, and finally the simplest way I could find to get it
to work is this: get the WebBrowser COM object, get the HWND from that
object (which is really the HWND numerous levels "up"), then traverse down the OS HWND hierarchy to find the HWND
with the name "DirectUIHWND".  From there, walk down the IAccessible
tree, to find the "Tab Row", then select the tab and invoke the
method.
It sounds ugly to describe, and it hurt to code it this way. I
could not figure out a way to do the traversal only in HWNDs or
only in IAccessible.  I have no idea why I needed to do both.

In Code
First, get the HWND of the WebBrowser:
        SHDocVw.WebBrowser ietab = ... ?
        string urlOfTabToActivate = ietab.LocationURL;
        IntPtr hwnd = (IntPtr) ietab.HWND;

Then get the HWND of the DirectUI thing in the IE instance that controls that WebBrowser:
        var directUi = GetDirectUIHWND(hwnd);

This is the hacky part. The GetDirectUIHWND method is defined like this:
    private static IntPtr GetDirectUIHWND(IntPtr ieFrame)
    {
        // try IE 9 first:
        IntPtr intptr = FindWindowEx(ieFrame, IntPtr.Zero, "WorkerW", null);
        if (intptr == IntPtr.Zero)
        {
            // IE8 and IE7
            intptr = FindWindowEx(ieFrame, IntPtr.Zero, "CommandBarClass", null);
        }
        intptr = FindWindowEx(intptr, IntPtr.Zero, "ReBarWindow32", null);
        intptr = FindWindowEx(intptr, IntPtr.Zero, "TabBandClass", null);
        intptr = FindWindowEx(intptr, IntPtr.Zero, "DirectUIHWND", null);
        return intptr;
    }

...where FindWindowEx is a dllimport:
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr FindWindowEx(IntPtr hwndParent,
                                              IntPtr hwndChildAfter,
                                              string lpszClass,
                                              string lpszWindow);

Then, get the IAccessible for that DirectUI thing:
        var iacc = AccessibleObjectFromWindow(directUi);

...where, of course, AccessibleObjectFromWindow is a DllImport, with some magic around it:
    [DllImport("oleacc.dll")]
    internal static extern int AccessibleObjectFromWindow
        (IntPtr hwnd, uint id, ref Guid iid,
         [In, Out, MarshalAs(UnmanagedType.IUnknown)] ref object ppvObject);

    private static IAccessible AccessibleObjectFromWindow(IntPtr hwnd)
    {
        Guid guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessible
        object obj = null;
        uint id = 0U;
        int num = AccessibleObjectFromWindow(hwnd, id, ref guid, ref obj);
        var acc = obj as IAccessible;
        return acc;
    }

Ok, then, you walk down the IAccessible tree, to find the "Tab Row". In IE this is the thing that displays all the tabs for the various browser windows.
        var tabRow = FindAccessibleDescendant(iacc, "Tab Row");

...where that method is:
    private static IAccessible FindAccessibleDescendant(IAccessible parent, String strName)
    {
        int c = parent.accChildCount;
        if (c == 0)
            return null;

        var children = AccChildren(parent);

        foreach (var child in children)
        {
            if (child == null) continue;
            if (strName.Equals(child.get_accName(0)))
                return child;

            var x = FindAccessibleDescendant(child, strName);
            if (x!=null) return x;
        }

        return null;
    }
}

And...
    private static List<IAccessible> AccChildren(IAccessible accessible)
    {
        object[] res = GetAccessibleChildren(accessible);
        var list = new List<IAccessible>();
        if (res == null) return list;

        foreach (object obj in res)
        {
            IAccessible acc = obj as IAccessible;
            if (acc != null) list.Add(acc);
        }
        return list;
    }

Then, get the IAccessible within THAT, and click it:
        var tabs = AccChildren(tabRow);
        int tc = tabs.Count;
        int k = 0;

        // walk through the tabs and tick the chosen one
        foreach (var candidateTab in tabs)
        {
            k++;
            // the last tab is "New Tab", which we don't want
            if (k == tc) continue;

            // the URL on *this* tab
            string localUrl = UrlForTab(candidateTab);

            // same? if so, tick it. This selects the given tab among all
            // the others, if any.
            if (urlOfTabToActivate != null
                && localUrl.Equals(urlOfTabToActivate))
            {
                candidateTab.accDoDefaultAction(0);
                return;
            }
        }

....where UrlForTab is....
    private static string UrlForTab(IAccessible tab)
    {
        try
        {
            var desc = tab.get_accDescription(0);
            if (desc != null)
            {
                if (desc.Contains("\n"))
                {
                    string url = desc.Substring(desc.IndexOf("\n")).Trim();
                    return url;
                }
                else
                {
                    return desc;
                }
            }
        }
        catch { }
        return "??";
    }

Whew.  I could not find a cleaner, simpler way to do this.


text:
Q: How to get any web site alert message UWP WebView what am I doing wrong?
I used w3schools.com for testing.
webView.Navigate(new Uri("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert"));

Package.appxmanifest file

NavigationCompleted
private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    string result = await sender.InvokeScriptAsync("eval", new string[] { "window.alert = function (AlertMessage) {window.external.notify(AlertMessage)}" });
}

ScriptNotify
private async void WebView_ScriptNotify(object sender, NotifyEventArgs e)
{
     MessageDialog dialog = new MessageDialog(e.Value);
     await dialog.ShowAsync();
}

A: The problem here is related to the web page
(https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert) you are using to test.
If you inspect on this page, you will find the "Try it" button is actually in a iframe named "iframeResult".

  <!DOCTYPE html>

Click the button to display an alert box.

      <button onclick="myFunction()">Try it</button>

So your code won't work while clicking "Try it" as you are overriding window.alert which is the alert method in parent frame. And to make your code work, you can simply change it to iframeResult.window.alert like the following:
private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    string result = await sender.InvokeScriptAsync("eval", new string[] { "iframeResult.window.alert = function(AlertMessage) {window.external.notify(AlertMessage)}" });
}


text:
Q: How to jump and fall in Unity? I am coding a game jump in Unity. How can I jump (move) like in the Jupiter jump game, so that at a touch my hero will fall at high speed?
###
public float forceFly;
void Update () {
    rigidbody2D.velocity = Vector2.zero;
    rigidbody2D.AddForce (new Vector2 (0, 1) forceFly);

    if(Input.GetMouseButtonDown(0)){

        // ?
    }

A: This question is horribly structured, and it really looks like you didn't even try. What you'll need to do is get the current position of the object by its transform.
gameObject.transform.position

and apply vector math on it. In this case you're wanting to move the Y axis up (to move into the air). A very simple implementation of this would be like so:
gameObject.transform.position = new Vector3(transform.position.x, transform.position.y + forceFly, transform.position.z);

where forcefly is the amount that you'll "jump" every second.


text:
Q: Jsoup 404 error I am new with Jsoup but I can't understand why I receive a 404 error when trying to obtain a page, even if the page is accessible from browser and I don't use any proxys. I have tried with the following code:
private static Document connect() {
    String url = "http://www.transfermarkt.co.uk/real-madrid/startseite/verein/418";
    Document doc = null;
    try {
        doc = Jsoup.connect(url).get();
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (HttpStatusException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return doc;
}

and I receive the exception message:
org.jsoup.HttpStatusException: HTTP error fetching URL. Status=404, URL=http://www.transfermarkt.co.uk/real-madrid/startseite/verein/418
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:449)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:424)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:178)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:167)
at ro.pago.ucl2015.UCLWebParser.connect(UCLWebParser.java:27)
at ro.pago.ucl2015.UCLWebParser.main(UCLWebParser.java:16)

A: It seems that the site doesn't allow bots and it will throw a
404 error response in case it doesn't locate the User-Agent headers.
The below works as it sets the user agent headers
private static Document connect() {
    String url = "http://www.transfermarkt.co.uk/real-madrid/startseite/verein/418";
    Document doc = null;
    try {
        doc = Jsoup.connect(url)
               .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
               .referrer("http://www.google.com")
               .get();
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (HttpStatusException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return doc;
}

User Agent
The Hypertext Transfer Protocol (HTTP) identifies the client software
  originating the request, using a "User-Agent" header, even when the
  client is not operated by a user.

Referrer (I don't think this is necessary)
HTTP referer (originally a misspelling of referrer) is an HTTP header
  field that identifies the address of the webpage (i.e. the URI or IRI)
  that linked to the resource being requested.

Just to provide full service I would advise you to set the timeout period for your requests. The default is 3 seconds, if the server takes longer than that you will receive
an exception. Bellow follows your code with timeout setter. Set it to zero for the longest possible period.
private static Document connect() {
    String url = "http://www.transfermarkt.co.uk/real-madrid/startseite/verein/418";
    Document doc = null;
    try {
        doc = Jsoup.connect(url)
               .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
               .referrer("http://www.google.com")
               .timeout(1000*5) //it's in milliseconds, so this means 5 seconds.
               .get();
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (HttpStatusException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return doc;
}

A: If in case you are getting response code 404 , you can skip that url
Use ignoreHttpErrors(true), will surely solve your problem
Document doc3 = null;
    try {
        doc3 = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
                .referrer("http://www.google.com").ignoreHttpErrors(true).get();

    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


text:
Q: Why is Number([]) === 0 and Number({}) === NaN in Javascript? I was looking at the first table on http://zero.milosz.ca/, and wanted to understand why, for example, 0 == [] and 0 != {}. I'm assuming it's because Number([]) == 0 and Number({}) == NaN. However, that part seems arbitrary. Why is an empty list 0 and empty object a NaN?

A: To elaborate a bit on ThiefMaster's answer, I've taken a look into ECMAScript's specifications:
When converting a string into a number, a grammar is used for the conversion. In particular, the mathematical value of StringNumericLiteral ::: [empty] is defined as 0. In fact, it's 0 for any whitespace.

A: When one value is an object ([],{}) and the other is a number or string, operator == converts the object to a primitive value (a number in this case) using the built-in conversion methods which all objects in Javascript inherit: toString() and valueOf().
For generic objects like {}, valueOf is used, and by default it returns the object itself, which is != 0.
For built-in arrays, toString is used. This method applied to an array returns a string containing all the elements joined by commas. For the empty array, it returns an empty string, ''.
Then the interpreter applies valueOf to that string; the return value of this method for an empty string is 0, so [] == 0.

A: Using Number(some_object) will use the string representation of the given object. For your examples the string representations are:
js> ({}).toString();
[object Object]
js> [].toString();

js>

The string '[object Object]' cannot be converted to a number but the empty string '' can.


text:
Q: Is there a way to find out what headers were sent? We all have encountered Headers already sent error probably. But I wonder if there's a way to find out what headers were sent?

A: You can also use the ob_start(); on this page at the begging of the line after <?php tag.


text:
Q: how can i call my database class in different class I'm trying to learn OOP along with PDO and prepared statements. I've made a database class which I believe is very simple.
I have a posts class and I want to echo all the data in this database, I have a constructor method which I want to call the database connection on however I believe I am doing this wrong and probably going about it the wrong way  as I am getting the following error message:

Notice: Undefined variable: pdo in E:\xampp\htdocs\attendance\class.Register.php on line 18
Fatal error: Call to a member function prepare() on a non-object in E:\xampp\htdocs\attendance\class.Register.php on line 18

Any ideas on how I should go about calling my database correctly
posts.php
<?php
require 'database.php';

class Posts {

protected $Database;

     public function __construct() {
 $pdo = new Database();
     $this->pdo = $pdo;
        }

public function viewall() {

    $stmt = $pdo->prepare('SELECT * FROM posts');
    $stmt->execute();
    $stmt->fetch();
    }
}
$run = new Users();
$run->viewall();
?>

database.php
<?php

class Database {
    public $dbo;

    public function __construct() {
        // Connection information
        $host   = 'localhost';
        $dbname = 'testdb';
        $user   = 'root';
        $pass   = '';

        // Attempt DB connection
        try
        {
            $this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            //echo 'Successfully connected to the database!';
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }

    }

     public function __destruct()
    {
        // Disconnect from DB
        $this->pdo = null;
        //echo 'Successfully disconnected from the database!';
    }
}
?>

A: You seem to be calling the method 'viewall' within the 'Users' class. However in the code you've shown the method 'viewall' is a member of the 'Posts' class.
$run = new Users();
$run->viewall();

Also you're setting the 'pdo' property, even though it doesn't exist within the class.
$pdo = new Database();
$this->pdo = $pdo;

Try changing
class Posts {

to
class Users {

and
protected $Database;

to
protected $pdo;


text:
Q: operator norm of a matrix and trace of a matrix Suppose $A=(a_{ij})$ is an $n\times n$ complex matrix, $\operatorname{tr}(A)=\displaystyle \frac{1}{n}\sum_{i}a_{ii}$. I wonder whether there exists a relationship between $\|A\|$ (the operator norm) and $\operatorname{tr}(A^k)$, where $k=1,\cdots,n$?

A: In general no, as nilpotent operators exist. For instance consider $$A=\begin{bmatrix}0&1\\0&0\end{bmatrix}. $$ Then $\|A\|=1$ and $\operatorname{tr}(A^k)=0$ for all $k$.
When $A$ is normal, it is easy to check that
$$\tag1
\|A\|=\lim_{k\to\infty}|n\operatorname{tr}(A^k)|^{1/k}.
$$
Indeed, you have that $\|A\|=\max\{|\lambda_j|:\ j=1,\ldots,n\}$, where $\{\lambda_j\}$ are the eigenvalues of $A$ counting multiplicities. If we take $\lambda_1$ to be the one with $|\lambda_1|=\|A\|$,
\begin{align}
|\operatorname{tr}(A^k)|^{1/k}&=\exp\left({\tfrac1k\,\log|\sum_{j=1}^n\lambda_j^k|}\right)
=\exp\left({\tfrac1k\,\log|\lambda_1^k|\,|1+\sum_{j=1}^n(\lambda_j/\lambda_1)^k|}\right)\\ \ \\
&=|\lambda_1|\,\exp\left({\tfrac1k\,\log |1+\sum_{j=1}^n(\lambda_j/\lambda_1)^k|}\right)\xrightarrow[k\to\infty]{}|\lambda_1|,\\ \ \\
\end{align}
as the expression inside brackets is bounded above by $\tfrac1k\,\log(1+n)$.


text:
Q: Determining user current location in IPhone and nearest locations from it I am currently developing a mobile application for IPhone which consists a part that requires to determine the user current location and also the nearest locations ( as lat,long point stored in phone). I am having the following questions:
1- Does the user needs to be connected to the internet so his/her location can be determined by our application? Won't GPS devise sufficient to determine the user current location as lat,long?
2- Since we will be having some locations as lat,long stored in the application, is it possible to determine the nearest locations (e.g. within 5 km) from the user current location without having an internet connection?
If code sample can be provided to narrow down the answer for the above, that would be highly appreciated.
Thanks a lot

A: well, for u r first question u need not required internet connection for fetching your current location.
For u r second question, well if u are able to get the co ordinates of your position(latitude,longitude) you said  we will be having some locations as lat,long stored in the application then you can compute the co ordinates and find the distance between them.
Use the following function for computing distance from coordinates
 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371;
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double dist = earthRadius * c;

    return(float)(dist);
    }

Its a java implementation of the haversine formula. Use it for finding distance.

A: yes you have to find the nearest location information  under 5 or something miles using the  google API ,with this API you ll find everything ..country info ,nearest location..ect
use this link :- http://maps.google.com/maps/geo?q=%f,%f&output=json&oe=utf8&sensor=true_or_false&key=ABQIAAAAO_WEDXjKUGDDHu8iB2FQ-xTFGipc9T1i1tjtezgvz0dWKwv3jxTjn5y1VrjIixtSrXmeMwiaCfxS8g


text:
Q: How to detect fixed focus camera blackberry? How can i detect models with fixed focus camera using java development in blackberry OS 6.0 > ?

A: you can use FocusControl.isAutoFocusSupported() to check if the camera can do auto focus. If not then its fixed focus.


text:
Q: Why is program counter incremented by 1 if memory organised as word and by 2 in case of bytes? If in a computer an instruction is of 16 bits and if memory is organized as 16-bits words, then the address of the next instruction is evaluated by adding one in the address of the current instruction. In case, the memory is organized as bytes, which can be addressed individually, then we need to add two in the current instruction address to get the address of the next instruction to be executed in sequence. Why is it so?? Please explain this concept. I am new to computer organisation and assembly language programming so any help is appreciated. Thanks.

A: Your question does not say what architecture you are referring to.
Talking about designs that do not allow instructions to be aligned to bytes, the behavior you describe differs from CPU to CPU!
First we look at the meaning of the "address" on 8-bit CPUs. On such CPUs the address is increased by 1 when going from one byte to the next byte in memory:
Address   Meaning
0         1st byte in memory
1         2nd byte in memory
2         3rd byte in memory
3         4th byte in memory
4         5th byte in memory
...

The 68000 uses a similar addressing like 8-bit CPUs. However, the memory is actually organized in 16-bit units and instructions must start at an even address and are a multiple of 16 bits long. Therefore the program counter always contains an even value. It will increase by 2 or a multiple of 2 during each instruction.
(Using odd addresses is only allowed for byte-wise memory access (read/write) which will actually perform a 16-bit memory access in the background.)
For the TMS9900 (a 16-bit CPU) the address is increasing by 1 for 16 bits; the bytes in between can be accessed but the addresses are formed by adding 0x8000:
Address   Meaning
0         1st byte in memory
0x8000    2nd byte in memory
1         3rd byte in memory
0x8001    4th byte in memory
2         5th byte in memory
...

The program counter may contain an odd or an even value here, but not a value above 0x7FFF because this would refer to a byte which is not 16-bit aligned. Of course, the program counter will increase by 1 when the instruction is 16 bits long.
The TMS320 does not allow addressing odd bytes:
Address       Meaning
0             1st + 2nd byte in memory
not possible  2nd + 3rd byte in memory
1             3rd + 4th byte in memory
2             5th + 6th byte in memory
...

In this design the program counter will also increase by 1 when the instruction is 16 bits long.
The LittleMIPS (or similar; I don't remember the correct name) design is a reduced MIPS CPU intended for students to learn microchip design. It allows only 32-bit memory access and only 4-aligned addresses:
Address       Meaning
0             1st to 4th byte in memory
1             address does not exist
2             address does not exist
3             address does not exist
4             5th to 8th byte in memory
5             address does not exist
...

On this design the program counter will always contain a multiple of 4. Because each instruction is exactly 4 bytes long, the program counter will increase by 4 during an instruction.

A: If the smallest addressable unit is 2 bytes, then adjacent 2-byte instruction words are only 1 address apart.
The whole point of word-addressable memory is to avoid wasting an address bit on byte-within-word in a system that can't do byte loads/stores in the first place.


text:
Q: xamarin for mac couldnot create or open xamarin.form project

MarshalError: [NOTE: this exception originated in the server.]
  Couldn't get signature for selector 'supportedRuntimes'

A: I had the same error, and it seems it was because some Mac updates (I had just updated the SO and XCode), I updated Xamarin (Xamarin Studio > Check for Updates...) and it worked just fine.


text:
Q: Error: Call to a member function hashName() on null Task: Upload image on s3 server
The code functioning properly on my local system and the file in saving properly on s3 server but when I push this code on server it gives me the hashName error.
Error: Call to a member function hashName() on null in file /var/www/html/doctring-api/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php on line 240
Code for Image Helper
<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class UserHelper
{
    public static function uploadImage($image)
    {
        try {
            if (count(explode("data:image/", $image)) > 1) {

                $fileName = \Carbon\Carbon::now()->timestamp . '_' . uniqid() . '.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
                $image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '',$image));
                Storage::disk('s3')->put($fileName, $image, 'public');

                return $fileName;
            }

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}

Api Controller
 public function uploadPrescription(Request $request){
        $validator = Validator::make($request->all(), [
            'patient_id' => 'required',
            'appointment_id' => 'required',
            'prescription' => 'required'
        ]);

        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());
        }

        $input = $request->all();

        $status_check = Appointment::where('id','=',$input['appointment_id'])->first();
        if($status_check->status == 'OnGoing'){

            //upload prescription(image in base64) to s3 bucket
            if($request->has('prescription'))
            {
                $imageName = UserHelper::uploadImage($request->prescription);

                $input['image_url'] = $imageName;
            }

            $data=[
                'patient_id' => $input['patient_id'],
                'appointment_id' => $input['appointment_id'],
                'prescription'=>  $imageName
            ];

            //Uploading Prescription only one record
//            $profile = Prescriptions::updateOrCreate(Arr::except($data, 'prescription'), $data);

            $profile = Prescriptions::updateOrCreate($data);
            return response()->json(['message' => "Prescription Uploaded", 'profile'=> $profile, 'error'=> 0, 'status'=> 1 ]);
        }else{
            return response()->json(['message' => "Prescription Uploading Failed", 'error'=> 1, 'status'=> 0 ]);
        }

    }

A: At line 240 of Filesystem/FilesystemAdapter as reported by your error, there is this line:
return $this->putFileAs($path, $file, $file->hashName(), $options);

This means that $file is null when you are trying to upload it.
In your question you say that in local environment you don't have this problem, so you should check in the code that precede this, what is causing the problem on the production server environment.
Hope this helps


text:
Q: Doing workbook.xlsx.writeFile without page reload (refresh or restart) in Electron const Exceljs = require('exceljs');
let wb = new Exceljs.Workbook();
wb.xlsx.readFile(sourceFileName).then(function(){
                        let SheetName = "Sheet1";
                            var sh;
                            sh = wb.getWorksheet(SheetName);
                            var cell = sh.getCell('C6');
                            cell.value = 242;
                            wb.xlsx.writeFile(fileName).then(function(){
                                console.log("Success");
                            });

                        });

This is my code.
The problem is "when I write the new excel file, then It forces my electron application to reload"
I simply wanted to open the existing excel file and edit.
My questions are ..

*

*Is it possible to edit existing excel file without using wb.wlsx.writeFile and writing again?

*If I can't, then how can I prevent reload of electron application??

A: It was because I saved the excel file in my app folder.
After I changed fileName's path outside app folder, there was no reload.
May this be helpful for some developers who are in the same level with me.
referecne : https://github.com/Unitech/pm2/issues/2710#event-959600970


text:
Q: How can I place a text below another text when they're in the same row but in different columns? I was wondering how can I place a text below another text when they're in the same row but in different columns?
This is image shows my current situation and goals. I applied a border attribute to see how the row and columns were distributed.

This is my HTML code:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Choose it

Select your favorite
product

Any ideas how can I distribute my HTML elements in a way that it resembles the desired result?

A: If you want this behavior for mobile screens you can change the display property for col-7's flex property on responsive view

 @media screen and (max-width: 767px) {
  .col-7.d-flex {
    display: block!important;
  }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css">

Choose it

Select your favorite
product

Make sure to wrap both images in a same div
Else
If you want the same behavior desktop view you can try this

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css">

Choose it Select your favorite  product

A:

Choose it Select your favorite  product


text:
Q: Weird Windows 'cleanmgr' result I just ran cleanmgr in my windows 7 and I've got a seriously weird result.
It says my TEMP folder is 352 GB. But my HDD is only 300 GB. I have 2 OS on it (Windows 7 and a Linux)
Is is virus related, bug, ...what should I do ?
Should I click to clean those 352 GB ?

A: The issue is that many "files" listed in the WinSxS, and perhaps other folders, are actually hard links, and there may be multiple links to one file, with size of each included in the sum. Apparently MS has yet to update Explorer to show the true size of its contents.
It is safe to remove files using Windows Disk Cleanup. After the initial pause, you then need to click Clean up system files. If you are willing to forego being able to revert to the state before updates were installed, you casn use the dism utility to remove yet more files.


text:
Q: In map(), when is it necessary to use a tilde and a period. (~ and .) I'm going through the examples of map() from 'R For Data Science'.
One example is:
library(dplyr)
library(purrr)
df <- tibble(
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)

df
#> # A tibble: 10 x 4
#>         a      b       c       d
#>     <dbl>  <dbl>   <dbl>   <dbl>
#>  1 -0.570  1.48   2.37    1.60
#>  2  0.122  2.08   0.222   0.0338
#>  3 -0.890  0.429 -1.75   -1.48
#>  4  0.334  0.854  0.849  -0.525
#>  5  1.22  -0.378 -1.00   -0.147
#>  6 -1.04  -0.427 -1.18    0.907
#>  7 -0.392  0.102  0.0951  0.842
#>  8  0.893  0.932  0.620  -0.911
#>  9  1.00   0.616 -0.937  -0.0286
#> 10  0.190  1.12  -1.02    1.45

In the map_dbl() below, I don't need to add a tilde before the function map_dbl(~ mean) and I don't have to put .
df %>% map_dbl(mean)

#>           a           b           c           d
#>  0.08714704  0.68069227 -0.17382734  0.17470388

Whereas, in the example below, I do have to put the ~ before the .f and I also have to specify data = .
models <- mtcars %>%
  split(.$cyl) %>%
  map(~ lm(mpg ~ wt, data = .))
models

I've tried reading previous answers, eg What is meaning of first tilde in purrr::map, but I'm still unsure as to the exact difference of when I need to use the tilde and .
Would perhaps the easiest way be for me to just always include those two things, even if they aren't strictly necessary?

A: I am not an expert on map, but here is why I think in this case you have to use the tilde.  I believe it has to do with apply a formula versus a function.
Here is an example where you would not have to.  In this case I am taking a list of the cylinders and sending it to a function:
cyl = mtcars%>%
  select(cyl)%>%
  unique%>%
  unlist()

model = function(CYL){

  lm(mpg ~ wt, data = mtcars%>%
       filter(cyl == !!CYL))
}

cyl%>%
  map(model)

In your example you are applying a formula not a function.  Here is another example of having to use a tilde:
models <- mtcars %>%
  split(.$cyl) %>%
  map(~.$mpg+.$cyl)
models

In help map is defined as: The map functions transform their input by applying a function to each element and returning a vector the same length as the input.  I believe the tilde is changing your formula into a function.

A: The quick answer to your question is, it is never necessary to use the tilde notation when calling map. There are different ways of calling map and the tilde notation is one of them. You already described the simpelst way of calling map, when a function only takes/needs one argument.
df %>% map_dbl(mean)

However, when functions get more complex there are basically two ways to call them either with the tilde notation or with a normal anonymous function.
# normal anonymous function
models <- mtcars %>%
  split(.$cyl) %>%
  map(function(x) lm(mpg ~ wt, data = x))

# anonymous mapper function (~)
models <- mtcars %>%
  split(.$cyl) %>%
  map(~ lm(mpg ~ wt, data = .))

The tilde notation is basically turning a formula into a function, which is most times easier to read. Each option can be turned into a named function, which works as follows. Ideally, the named function reduces the complexity of the underlying function to one argument (the one which should be looped over) and in this case the function can be called like all simple functions in map without further arguments/notations.
# normal named function notation
lm_mpg_wt <- function(x) {
  lm(mpg ~ wt, data = x)
}

models <- mtcars %>%
  split(.$cyl) %>%
  map(lm_mpg_wt)

# named mapper function
mapper_lm_mpg_wt <- as_mapper(~ lm(mpg ~ wt, data = .))

models <- mtcars %>%
  split(.$cyl) %>%
  map(mapper_lm_mpg_wt)

Basically these are your options. You should choose whatever is easiest and most fit to your problem. Named functions are best, if you need them again. Many think that mapper functions are easier to read, but at the end of the day that is a choice of personal preference.


text:
Q: How to pass object of type `any` with functions in jest? I have a code where I am receiving an object from a third party component, so I have marked its type as any. There are a few methods of that object that I am using in my code.
init(context: any) {
  context.doSomething('profile');
}

Now while testing this code, I want to mock the functionality of the doSomething method, but I am not sure how can I do that. I tried a few things in jest.fn() but nothing seems to work. I tried something like
type ContextType = { doSomething?: (arg0: { val: string; }) => any; }
let context: ContextType = {};
jest.spyOn(context, 'doSomething').mockReturnValue({});
obj.init(context);

But this doesn't seem to work. But  Can someone tell me how can I get this working in my tests?

A: Create a context that includes doSomething as a mock function.
let context = { doSomething: jest.fn() };
obj.init(context);

expect(context.doSomething).toHaveBeenCalledWith('profile');


text:
Q: number of control points for B spline curve I am trying to use B spline curve fitting. The order of B spline curve is 4. When I have many control points, it works well. However if the number of control points is small such as two, my program will crash. I realize that the number of control points is related to number of knots and the order. Can anyone help me clarify the relationship or give some links on it?

A: Sounds like you're simply reading out of bounds, which is not a specific issue of calculating splines. To calculate a b-spline of degree n, you'll need at least n + 1 points.
To simplify and show the issue:

*

*The easiest way of interpolation is linear interpolation - just draw a line between two points.

*If you've got only one point, you can't interpolate anything, simply due to the fact that you don't know where to draw.

*For a quadratic interpolation, you'll need at least three points, etc.

*In a similar way, you'll need at least 5 points for a b-spline of 4th degree.
A really nice online demo can be found here:

*

*Pick any b-spline demo on the lower left side, I'd just go for the linear one.

*On the right you're now able to set the number of control points as well as the degree of the curve.

*Feel free to try around, also by moving the points around with your mouse.

A: Two control points is not sufficient to define a B-spline of order 4. For B-splines, the number of knots needs to equal the sum of number of control points and order. A single segment degree 3 B-spline will require 4 control points and 8 knot values. So, to calculate a B-spline with order N, you at least need N points. That will give you a B-spline with single segment. If you have more points, then the resulting B-spline will have more segments.

A: As others stated, the number of control points is equal to the number of knots minus the order of the bspline basis. Thus you cannot have an arbitrary combination of order, say k, and knot vector for your bspline function/curve once you fix the control points.
A very useful link for theory on b-splines and nurbs curves is the following:
http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/index.html
There you can find the relationship of number of control points with dimensionality of knot vector etc as well as detailed examples and some algorithms.
Depending on your needs, you may also wish to check "The NURBS book" by Piegl and Tiller
http://www.amazon.com/NURBS-Book-Monographs-Visual-Communication/dp/3540615458
they have done an amazing job and in their book they include working algorithms.
The curve fitting problem of a b-spline to data is a rather large subject since you have to take care to avoid over/under fitting. There are several approaches, and most involve including a curvature penalty term. The literature is vast, but you can find a lot of information and a great starting point in the book by Hastie et. al. "The elements of statistical learning" which you can legally download from the authors site:
http://statweb.stanford.edu/~tibs/ElemStatLearn/
The curve fitting problem is covered to some extent in all references I gave. Good luck.


text:
Q: setting fixed width with 100% height of the parent In the following HTML, I want to set the height of left and right 100% of the parent element. In addition, the left div has fixed width. The right should use all of the remaining width.
I think because of using display: flex; in the parents div, the width of the left div doesn't stay constant. How can I set fixed width for it and allocate all of the remaining space to the right.
Edit: the calc(100-52px) is the height of the parent. The question is only about setting fixed width of 100px to the left so that it doesn't change on resizing the window.

Here's what I'm trying:

body {
  padding: 0;
  margin: 0;
}

.parent {
  background: red;
  display: flex;
  height: calc(100vh - 52px);

}

.left {
  width: 100px;
  background: yellow;

}

.right {
  background: orange;
  width: 100%;

}

the width should be fixed, not flexible

width should be all of the remaining

A: parent { display: -webkit-box;display:-webkit-flex;display: -ms-flexbox;display:flex;flex-wrap: wrap; }
.parent > [class*='col-'] { display: flex; flex-direction: column; }

A: You can use width: calc(100% - 100px) or flex: 1 for the right div.
Percentage values are calculated from the parent element, therefore you need to extract static values from 100% to get the remaining area.
But as you are already using a flex container here, you can just set flex: 1, which is the shorthand for flex-grow: 1, that will allow your container to take all the extra space in the parent container, since no other items are available.

A: Add a flex declaration to the .left selector:
flex: 0 0 100px;

flex syntax:
none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]

So this declaration is stating: "don't grow, don't shrink, define the initial size as 100px"
Read more: flex (MDN)

A: If right is to stand 52px away from the far right, then a margin will do . Please clarify your question.

body {
  padding: 0;
  margin: 0;
}

.parent {
  background: red;
  display: flex;
  height: calc(100vh - 52px);
}

.left {
  width: 100px;
  background: yellow;
}

.right {
  flex-grow: 1;
  background: orange;
  margin-right: 52px;
}

the width should be fixed, not flexible

width should be all of the remaining

A: Set flex: 0 0 100px; on your .left div (you can remove width: 100px) if you want it to be a constant 100px - so no growing or shrinking.

body {
  padding: 0;
  margin: 0;
}

.parent {
  background: red;
  display: flex;
  height: calc(100vh - 52px);

}

.left {
  flex: 0 0 100px;
  background: yellow;

}

.right {
  background: orange;
  width: 100%;

}

the width should be fixed, not flexible

width should be all of the remaining

A: see if this helps you, comment if you need any changes
stackblits link for 1 fixed width, 1 relative column


text:
Q: How to show that $(3,x-1)\not=(3,x+1)$ as ideals in $Z[x]$ How to show that $(3,x-1)\not=(3,x+1)$ as ideals in $Z[x]$
Both are maximal.
I think all i need to do is to show is that $x+1 \not \in (3,x-1)$ but I do not know how to show that. I wanted to assume towards contradiction that $3f(x)+(x-1)g(x)=x+1$. It is clear that $deg(f(x))\geq1$ and $deg(g(x))=deg(f(x))-1$. I was thinking induction on the degree but it seems messy with weird system of equations.

A: Hint: If $3f(x)+(x-1)g(x)=x+1$, then what happens when $x=1$?


text:
Q: Merging two sheets into one I want to merge two files in excel, e.g.:
File 1 -
col1 col2
1    3
1    4
2    5
2    6
3    7

File 2 -
Col2
101
102
103

Expected Output -
col1 col2 col3
1    3     101
1    4     101
2    5     102
2    6     102
3    7     103

Thanks

A: Assuming Col2 in File 2 is in B2, 'label' a column:
=OFFSET(B$1,INT(ROW()/2),)

copy down to suit and then copy the values from that column into File1 where required.
OFFSET
INT
ROW


text:
Q: Getting File Attributes with XMLReader in C# I used the XMLReader format:

XmlReader xmlReader = XmlReader.Create("batch.xml");
while (xmlReader.Read())
{
    //Keep reading
    if (xmlReader.Name.Equals("Keyword") && (xmlReader.NodeType == XmlNodeType.Element))
    {
        // get attribute from the Xml element here
        string keywords = xmlReader.GetAttribute("name");
    }
}

How do I cast "keywords" as a String[]?

A: It depends.
If your XML has a single name attribute that contains multiple keywords, call String.Split, like this:
string[] keywords = xmlReader.GetAttribute("name").Split(' ');

If you have multiple name attributes or Keyword elements, create a List<string> and fill it up in a loop, like this:
List<string> keywords = new List<string>();
XmlReader xmlReader = XmlReader.Create("batch.xml");
while (xmlReader.Read()) {
    //Keep reading
    if (xmlReader.Name.Equals("Keyword") && (xmlReader.NodeType == XmlNodeType.Element))
        keywords.Add(xmlReader.GetAttribute("name"));
}

If you really need a string[], you can call keywords.ToArray().

A: Since you're using a XmlReader, you can't have all nodes at once. You need to create a List<string> collection, populate and return it.


text:
Q: In Mapfish Print Modules YAML, how do I break a string over multiple lines? In MapFish Printing Module YAML, I have a string that's very long. so I'd like to break the string . What's the syntax for this?
In other words, I have this:

*

*!columns
        config:
          width: 5
         # borderWidth: 1
         # borderColor: black
          cells:
            - padding: 10
              paddingBottom: 10
              vertAlign: middle
              width: 5
              maxSize: 100
        absoluteX: 35
        absoluteY: 111
        width: 5
        height:350
        items:
          - !text
            font: Kalpurush
            fontEncoding: Identity-H
            fontSize: 12
            #align: center
            text: '${onm} ${fnm}'
            textMaxWidth: 8
            maxWidth: 5
            maxHeight: 15

I have parameter as '${Name} ${FatherName}' , I need to put break or newline in String for this parameter.


text:
Q: Add event, through extension, to an element with event handler function in original page In my Content Script, I have an element (an a tag, to be more specific) and I need to add an event to it. The event handler, however, is defined in the page JS, and I dont know how to attach it to the event of my element in the extension. What I want to achieve is:
element.addEventListener("mouseover", pageFunction("foo", "bar"));

I have read other questions, like this one, which suggests injecting code or using location.href="javascript:pageFunction(); void 0"; but I dont see how I could apply them in my case.

A: According to the MDN reference there is a way for page and content scripts to communicate with each other.

In Firefox*, DOM objects in content scripts get an extra property wrappedJSObject. This is an "unwrapped" version of the object, which includes any changes made to that object by any page scripts.

Now, in your code, you're immediately calling the function rather than passing the listener a reference. To solve this you should wrap your function call in an arrow function to prevent this:
element.addEventListener("mouseover", () => window.wrappedJSObject.pageFunction("foo", "bar"), false);

∗ I couldn't find any information about whether this method should be used for Chrome too.


text:
Q: Dynamic root for authenticated polymorphic attribute I have three models as follows:
user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :role, polymorphic: true

  validates_presence_of :first_name, :last_name, :email, :password,
    :password_confirmation
end

student.rb
class Student < ActiveRecord::Base
  has_one :user, as: :role, dependent: :destroy

  accepts_nested_attributes_for :user
end

teacher.rb
class Teacher < ActiveRecord::Base
  has_one :user, as: :role, dependent: :destroy

  accepts_nested_attributes_for :user
end

I have user registration and login working as expected. However, I cannot figure out how to direct users to the appropriate homepage when they're logged in.
I handle routing for authenticated users as follows:
authenticated :user do
  root to: "students#home", as: :user_root
end

Ideally if current user's role attribute is a student, then it sets students#home as :user_root. If it's a teacher, then it sets teachers#home as :user_root. Is there any way to handle this purely in routes?

A: They way you've structured it seems confusing to me. How much do teachers and students really have in common? Won't students and teachers need different associations, fields, and everything?
Why not have completely separate Student and Teacher models with different devise scopes? See devise wiki configuring multiple models: https://github.com/plataformatec/devise#configuring-multiple-models
For shared functionality you can have both inherit from an abstract model or use concerns / modules for shared functionality.
module DeviseConcern
  extend ActiveSupport::Concern

  included do
    devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

    validates_presence_of :first_name, :last_name, :email, :password,
      :password_confirmation
  end
end

A: While playing around with AJcodez's solution, some things like user authentication were less than pleasant  to implement. I ended up opting for my original implementation.
One lesser known things about routes is that they can have lambas in them. Our routes ended up looking like the following:
authenticated :user, lambda { |u| u.role_type == "Student" } do
  root to: "students#home", as: :student_root
end

authenticated :user, lambda { |u| u.role_type == "Teacher" } do
  root to: "teachers#home", as: :teacher_root
end


text:
Q: NetExtender VPN not launch on ubuntu 18.4.6, To launch it we have to use home/usr/lib and then NetExtender.jar. However, on ubuntu 20 it is working NetExtender VPN not launch on ubuntu 18.4.6, To launch it we have to use  home/usr/lib and then NetExtender.jar. However, on ubuntu 20 it is working  fine. Can someone help me to resolve this issue.
Your help will really appreciated.


text:
Q: Automated review failure from store - online_accounts I'm trying to upload a package to the Ubuntu Software Store that uses Online Accounts. However, it keeps failing automated review with errors like:
No JSON object could be decoded. Value: "ERROR: accounts xml unparseable: (Document is empty, line 1, column 1) ". click-check-online-accounts

- online_accounts_account-service_name_myapp
       Could not find '<name>' tag

- online_accounts_peer_hooks_required_account-service
       Missing required hooks for 'myapp': account-application
       https://wiki.ubuntu.com/SecurityTeam/Specifications/OnlineAccountsConfinement

How can I get my package to pass the automated review?

A: Taking the error messages one at a time:
No JSON object could be decoded. Value: "ERROR: accounts xml unparseable: (Document is empty, line 1, column 1) ". click-check-online-accounts

This means one of a couple of things:

*

*That you have specified one of the online-accounts manifests (account-service, account-application) in the hooks section of your package manifest (manifest.json) but provided an empty value.

*That you have specified one of the online-accounts manifests (account-service, account-application) in the hooks section of your package manifest (manifest.json) but provided a value pointing to a non-existent file.

*That you have specified one of the online-accounts manifests (account-service, account-application) in the hooks section of your package manifest (manifest.json) but provided a value pointing to an empty file.

*That you have specified one of the online-accounts manifests (account-service, account-application) in the hooks section of your package manifest (manifest.json) but provided a value pointing to a file which does not contain valid XML.

You need to ensure that:

*

*You provide a valid value for the account-service and account-application hooks, that points to the appropriate file relative to the root of your package.

*The files contain valid XML.

See the Online Accounts Developer Guide for information on what each file should contain.
- online_accounts_account-service_name_myapp
       Could not find '<name>' tag

The file you specified with the account-service hook contained valid XML, but did not contain a <name> element within the top-level <service> element.
- online_accounts_peer_hooks_required_account-service
       Missing required hooks for 'myapp': account-application
       https://wiki.ubuntu.com/SecurityTeam/Specifications/OnlineAccountsConfinement

You have specified an account-service hook, but not a corresponding account-application hook in your package manifest. As well as the link provided, the Online Accounts Developer Guide has more information.


text:
Q: Oauth refresh token Sorry for the newbie question.
What the point of refresh token if i have to send my credentials anyway?
Or in another words, what the practical difference between requesting refresh token or just a new access token?
here is my code:
    TokenResponse tokenResponse = null;
var tokenRequest = new TokenRequest
    {
        GrantType = "customgrant",
        ClientId = "myUserName",
        ClientSecret = "secret",
        Address = disco.TokenEndpoint,
    };

tokenResponse = await client.RequestTokenAsync(tokenRequest);

var testClient = new HttpClient();

testClient.SetBearerToken(tokenResponse.AccessToken);

var apiRes = await testClient.GetAsync("http://localhost:11000/api/GetData/104246");
if (!apiRes.IsSuccessStatusCode)
{

    if (apiRes.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {

        RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest();
        refreshTokenRequest.RefreshToken = tokenResponse.RefreshToken;
        refreshTokenRequest.ClientId = "myUserName";
        refreshTokenRequest.ClientSecret = "secret";
        refreshTokenRequest.Address = disco.TokenEndpoint;
        tokenResponse = await testClient.RequestRefreshTokenAsync(refreshTokenRequest);
    }
}

A: Your question is not clear. refresh token is used to get new valid access token and you don't need user credentials, when you already have valid refresh token.


text:
Q: Рекурсивная функция с указателями Вызываю функцию из главной программы и передаю значения аргументов по ссылке , но функция потом рекурсивно вызывает сама себя , что делать с указателями ?Как они себя поведут .Например , я веду счетчик перемещений в быстрой сортировке
Из главной программы вызываю так
             qsortx(A,0,N-1, &movents, &compasion);

Формальные аргументы в шапке функции выглядят так :
               void qsortx(int *a, int low,int  high,int *movents,int *compasion) {

А в рекурсивных вызовах этой самой функции так :
             qsortx(a, i, high,movents,compasion);

Но переменные перемещений и сравнений остаются равны нулю , где ошибка ?
Целиком функция выглядит так :
void qsortx(int *a, int low,int  high,int *movents,int *compasion) {
    int i=0, j=0;
    int tmp=0, medianofthree=0;

    i = low;
    j = high;
    int k = 0, l = 0, m = 0;
    k = *(a + 0);
    l = *(a + high);
    m = *(a + (high + low) / 2);
    /*Median-of-three*/
    if (k > l && k < m || k < l && k > m)
        medianofthree= k;
    else
        if (l > k && l < m || l < k && l > m)
            medianofthree=l;
        else
            medianofthree= m;
    /*Median-of-three*/
    printf("\n%d\n", medianofthree);
    do {
        while (a[i] < medianofthree)
        {
            i++;
            compasion++;
        }
        while (a[j] > medianofthree)
        {
            j--;
            compasion++;
        }
        if (i <= j)
        {
            if (a[i] > a[j])
            {
                tmp = a[i];
                a[i] = a[j];
                a[j] = tmp;
            }
            i++;
            if (j > 0)
            {
                j--;
            }
        }
    } while (i <= j);

    if (i < high)
    {
        qsortx(a, i, high,movents,compasion);
    }
    if (j > low)
    {
        qsortx(a, low, j,movents, compasion);
    }
}


text:
Q: Calculate weekdays and weekends count between two dates without considering daylight saving - javascript Due to daylight saving time in London, I'm not able to get the correct count for weekdays and weekend days. In the below fiddle 26/10/2019 is considering at times as weekday and at times as a weekend.
I want to get the output for the below fiddle is
"workingDays": 1,
  "weekendDays": 2
Any suggestions, please?

var startDate = new Date('2019-10-26');
var endDate = new Date('2019-10-28');
var workingDays = number_of_working_days(startDate, endDate);
var weekendDays = number_of_weekend_days(startDate, endDate);
console.log({
  'workingDays': workingDays,
  'weekendDays': weekendDays
})

function number_of_working_days(startDate, endDate) {
  var workingDays = 0;
  for (var i = startDate; i <= endDate; i = i + (60 * 60 * 24)) {
    if (i.getDay() <= 5) {
      workingDays = workingDays + 1;
    }

  }
  return workingDays;
}

function number_of_weekend_days(startDate, endDate) {
  var weekendDays = 0;
  for (var i = startDate; i <= endDate; i = i + (60 * 60 * 24)) {
    if (i.getDay() > 5) {
      weekendDays = weekendDays + 1;
    }
  }
  return weekendDays;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


text:
Q: I have a problem with an eventhandler (c#) This code is from one class
 Button pagebtn = new Button();
 pagebtn.Text = "2";

 pagebtn.Click +=
        listTopicPerPage_Click(this, new btnEventArgs() { btnNumber = 2 });

I get an underline on the eventHandler method saying..

cannot immplicitly convert type 'void'
  to 'System.EventHandler'.

Why is that?
Code from a different class that i created:
class btnEventArgs : EventArgs
{
    public int btnNumber { get; set; }
}

A: To specify the event parameters you should create a event field in your class, and rise it up on demand:
public partial class WebForm1 : System.Web.UI.Page
{
    public event EventHandler<btnEventArgs> SampleEvent;

    public void DemoEvent(int val)
    {
        // Copy to a temporary variable to be thread-safe.
        EventHandler<btnEventArgs> temp = SampleEvent;
        if (temp != null)
            temp(this, new btnEventArgs { btnNumber = val });
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += new EventHandler(Button1_Click);
    }

    void Button1_Click(object sender, EventArgs e)
    {
        DemoEvent(2);
    }
}

class btnEventArgs : EventArgs
{
    public int btnNumber { get; set; }
}

MSDN article

A: just try this:
pagebtn.Click += new EventHandler(listTopicPerPage_Click);

A: Edit
pagebtn.Click += listTopicPerPage_Click;

A: it's because your method signature of the listTopicPerPage_Click is something like
protected void listTopicPerPage_Click( object sender, EventArgs e )

There are a couple of things you can do here,
You can update your method signature to use btnEventArgs instead of EventArgs
protected void listTopicPerPage_Click( object sender, btnEventArgs e )

or you can cast your new btnEventArgs to be EventArgs and then cast it back to btnEventArgs in the method body.
pagebtn.Click +=
    listTopicPerPage_Click(this, (EventArgs) new btnEventArgs() { btnNumber = 2 });

protected void listTopicPerPage_Click( object sender, EventArgs e )
{
   btnEventArgs bea = (btnEventArgs) e;

   ...
}


text:
Q: DataGridView text export to CSV I want to export all data from DataGridView to a CSV file, but the date format is wrong.
The date format I want is "dd-MMM-yy"
Full code:
Imports System.Data.OracleClient
Imports System.IO
Imports System.Text

Public Class Form1
    Private da As OracleDataAdapter
    Private cb As OracleCommandBuilder
    Private ds As DataSet

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim oradb As String = "Data Source=testdb;User Id=teszt;Password=teszt;"
        Dim conn As New OracleConnection(oradb)
        conn.Open()
        Dim cmd As New OracleCommand

        Dim sql As String = "select * from dont"
        cmd = New OracleCommand(sql, conn)
        cmd.CommandType = CommandType.Text

        da = New OracleDataAdapter(cmd)
        cb = New OracleCommandBuilder(da)
        ds = New DataSet()

        da.Fill(ds)

        DataGridView1.DataSource = ds.Tables(0)

        Dim xRowCount As Integer = 0
        Do Until xRowCount = DataGridView1.RowCount
            DataGridView1.Rows(xRowCount).Cells(2).Style.Format = Format("dd-MMM-yy")
            DataGridView1.Rows(xRowCount).Cells(1).Style.Format = Format("dd-MMM-yy")
            xRowCount = xRowCount + 1
        Loop
        conn.Dispose()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim StrExport As String = ""

        For Each C As DataGridViewColumn In DataGridView1.Columns
            StrExport &= """" & C.HeaderText & ""","
        Next
        StrExport = StrExport.Substring(0, StrExport.Length - 1)
        StrExport &= Environment.NewLine

        For Each R As DataGridViewRow In DataGridView1.Rows
            For Each C As DataGridViewCell In R.Cells
                If Not C.Value Is Nothing Then
                    StrExport &= """" & C.Value.ToString & ""","
                Else
                    StrExport &= """" & "" & ""","
                End If
            Next
            StrExport = StrExport.Substring(0, StrExport.Length - 1)
            StrExport &= Environment.NewLine
        Next

        Dim tw As IO.TextWriter = New IO.StreamWriter("C:\Users\rg\teszt.csv")
        tw.Write(StrExport)
        tw.Close()
    End Sub
End Class

I'm working from an Oracle SQL database
I tried this:
 Dim StrExport As String = ""
     For Each C As DataGridViewColumn In DataGridView1.Columns
        StrExport &= """" & C.HeaderText & ""","
    Next
    StrExport = StrExport.Substring(0, StrExport.Length - 1)
    StrExport &= Environment.NewLine
    For Each R As DataGridViewRow In DataGridView1.Rows
        For Each C As DataGridViewCell In R.Cells
            If Not C.Value Is Nothing Then
                StrExport &= """" & C.Value.ToString & ""","
            Else
                StrExport &= """" & "" & ""","
            End If
        Next
        StrExport = StrExport.Substring(0, StrExport.Length - 1)
        StrExport &= Environment.NewLine
    Next
    Dim tw As IO.TextWriter = New IO.StreamWriter("C:\Users\rg\teszt.csv")
    tw.Write(StrExport)
    tw.Close()

currently looks like this and that's not good:
"264117","2019.01.14. 0:00:00","2019.06.01. 0:00:00","sikeres eredmény","továbbra jogosult"
"264547","2019.01.15. 0:00:00","2019.06.02. 0:00:00","sikeres eredmény","továbbra nem jogosult"
I would like it to look like this in the csv file:
"264117","19-JAN.  -14","19-JUN.  -01","sikeres eredmény","továbbra jogosult"
"264547","19-JAN.  -15","19-JUN.  -02","sikeres eredmény","továbbra nem jogosult"

A: you should use  tostring("yy-MMM.-dd") for  every C.ValueType that is a date.

A: The TextFieldParser class is used to read structured text files.
It allows to specify the Fields separator and other variant of the record format.  For example we can specify whether the Fields values are enclosed in quotes, using the TextFieldParser.HasFieldsEnclosedInQuotes property.
It's just a parser, we cannot use it write to a file, only read from one.
But, of course, we can use it to validate a CSV formatted file, when needed.
This is a generic method that writes to a file the structure and values of a DataGridView's content.
The TextFieldParser class is then used to validate the output that this method generates.
You can pass some parameters to the CSVSaveDGVData method:

*

*The path of the file where the data will be stored. If the file does not exist, it will be created. A StreamWriter is use to write the data to a File. Note that I have set the Encoding to UTF8, even though it's the default: just to remind that a different Encoding could be specified, should it be needed.

*The DataGridView which is the source of the Data.

*A specific format to use when the Cell type is of Type DateTime (Date).

*A specific CultureInfo, if the decimal values need to be formatted using the a specific Culture format. If none is specified, it defaults to InvariantCulture.

Important note about null/DBNull handling: the current Cell.Value conversion, handles null/DBNull values as empty strings: the null format of a Field actually depends on what is reading these values back. You'll need to adapt it, if something else is required.
Sample call:
Dim culture = CultureInfo.CreateSpecificCulture("hu-HU")
If CSVSaveDGVData("test.csv", DataGridView1, "dd-MMM.-yy", culture) Then
    'All good
End If

Imports System.Globalization
Imports System.IO
Imports System.Text

Public Function CSVSaveDGVData(filePath As String, control As DataGridView, dateTimeFormat As String, Optional culture As CultureInfo = Nothing) As Boolean
    Dim decimalFormat = If(culture, CultureInfo.InvariantCulture)
    Dim dateFormat = If(String.IsNullOrEmpty(dateTimeFormat), culture.DateTimeFormat.FullDateTimePattern, dateTimeFormat)

    Dim columns As String = String.Join(","c, control.Columns.OfType(Of DataGridViewColumn).Select(Function(c) ChrW(34) & c.Name & ChrW(34)))
    Using writer As StreamWriter = New StreamWriter(filePath, False, Encoding.UTF8)
        writer.WriteLine(columns)

        For Each row As DataGridViewRow In control.Rows
            If row.IsNewRow Then Continue For
            Dim record As New List(Of String)
            For Each cell As DataGridViewCell In row.Cells
                Dim fieldType As Type = cell.ValueType
                Dim fieldValue As String
                Select Case fieldType
                    Case GetType(Single), GetType(Decimal), GetType(Double)
                        fieldValue = If(cell.Value IsNot DBNull.Value,
                            CType(cell.Value, Decimal).ToString(culture.NumberFormat),
                            String.Empty)
                    Case GetType(Date)
                        fieldValue = If(cell.Value IsNot DBNull.Value,
                            DirectCast(cell.Value, Date).ToString(dateFormat),
                            String.Empty)
                    Case GetType(Image)
                        fieldValue = cell.ValueType.ToString()
                    Case Else
                        fieldValue = cell.Value?.ToString()
                End Select
                record.Add(ChrW(34) & fieldValue & ChrW(34))
            Next
            writer.WriteLine(String.Join(",", record))
            record.Clear()
        Next
    End Using
    Return CSVValidate(filePath)
End Function

Private Function ValidateCSV(filePath As String) As Boolean
    Using tfp As New FileIO.TextFieldParser(filePath)
        tfp.TextFieldType = FileIO.FieldType.Delimited
        tfp.SetDelimiters(",")
        Dim sb As New StringBuilder()
        Try
            While Not tfp.EndOfData
                sb.Append(tfp.ReadFields)
            End While
        Catch exIO As IOException
            MessageBox.Show($"Invalid File: {exIO.Message}")
            Return False
        Catch exIDX As IndexOutOfRangeException
            MessageBox.Show($"Invalid Data format: {exIDX.Message}")
            Return False
        Catch exIO As FileIO.MalformedLineException
            MessageBox.Show($"Invalid Data format at line {exIO.Message}")
            Return False
        Finally
            sb.Clear()
        End Try
    End Using
    Return True
End Function


text:
Q: Importing Excel Data for Isovolume Rendering Paraview I am trying to visualize heat intensity data(0 to 1)based on xyz. I have the data in a excel file and also in a csv file. In csv, the format is as follows:
x, y, z, scalar
0, 1, 1, 0.489324
1, 1, 1, 0.899
.
.
.

Each unit on an axis represents one voxel. There are totally 12 voxels along each axis. I would like visualize something close to this -> https://www.youtube.com/watch?v=UMnIwdQhZE4. How do i import either an excel data or csv into paraview? Is there a way to copy paste values from excel sheet into a 3d array?

A: Paraview can easily open csv files, creating a table source. Once you load your data, you can use the

*

*TableToPoints: I find it the easiest option, you just have to select which column represent x,y,z. The outout is a polygonall mesh
or

*TableToStructuredGrid: besides choosing the columns, you also have to write the extent - in your case I think 0-11 0-11 0-11 . I don't have much experience with this, but I think you also have to be careful if your data is x-fastest or not. The output in this case is a structuredGrid

*If you have to do something more complicated, you can use the programmable filter and change the output format. For examples see the paraview guide. For suitable formats, here is a nice answer https://stackoverflow.com/a/7667417/1136458


text:
Q: iterate through multi-level hash ref I want to iterate following multilevel hash ref and create a single select box showing parent->child relationship.Following is the hash ref which I got from dumper. SO basically I want to create a subroutine through which we could build a HTML select box.
my $hash = {
          '136666' => {
                        'children' => {
                                        '136954' => {
                                                      'children' => {
                                                                      '137004' => {
                                                                                'title' => 'child of child',
                                                                                'parentid' => '136954'
                                                                                }
                                                                    },
                                                      'title' => 'add child',
                                                      'parentid' => '136666'
                                                    }
                                      },
                        'title' => 'Main Forum',
                        'parentid' => '-1'
                      },
          '136720' => {
                        'children' => {
                                        '136997' => {
                                                      'title' => 'under category',
                                                      'parentid' => '136720'
                                                    }
                                      },
                        'title' => 'Android',
                        'parentid' => '-1'
                      },
          '136719' => {
                        'title' => 'Nokia C2-01',
                        'parentid' => '-1'
                      },
          '136665' => {
                        'children' => {
                                        '136994' => {
                                                      'title' => 'sub form under test forum',
                                                      'parentid' => '136665'
                                                    }
                                      },
                        'title' => 'test',
                        'parentid' => '-1'
                      }
        };

and want to select box like :
<option value='136666'>Main Forum</option>
<option value='136954'>--add child</option>
<option value='137004'>----child of child'</option>
<option value='136665'>test</option>
<option value='136994'>--sub form under test forum</option>
<option value='136719'>Nokia C2-01</option>
<option value='136720'>--Android</option>
<option value='136997'>----under category'</option>

thanks in advance!
New hash as follows:
my $hash  = {
          '4' => {
                   'forumid' => '136720',
                   'children' => {
                                   '7' => {
                                            'forumid' => '136997',
                                            'title' => 'under category',
                                            'is_category' => '0',
                                            'parentid' => '136720'
                                          }
                                 },
                   'title' => 'Android',
                   'is_category' => '0',
                   'parentid' => '-1'
                 },
          '1' => {
                   'forumid' => '136666',
                   'children' => {
                                   '5' => {
                                            'forumid' => '136954',
                                            'children' => {
                                                            '8' => {
                                                                     'forumid' => '137004',
                                                                     'title' => 'child of child',
                                                                     'is_category' => '0',
                                                                     'parentid' => '136954'
                                                                   }
                                                          },
                                            'title' => 'add child',
                                            'is_category' => '0',
                                            'parentid' => '136666'
                                          }
                                 },
                   'title' => 'Main Forum',
                   'is_category' => '0',
                   'parentid' => '-1'
                 },
          '3' => {
                   'forumid' => '136719',
                   'title' => 'Nokia C2-01',
                   'is_category' => '1',
                   'parentid' => '-1'
                 },
          '2' => {
                   'forumid' => '136665',
                   'children' => {
                                   '6' => {
                                            'forumid' => '136994',
                                            'children' => {
                                                            '9' => {
                                                                     'forumid' => '137012',
                                                                     'title' => 'another child',
                                                                     'is_category' => '0',
                                                                     'parentid' => '136994'
                                                                   }
                                                          },
                                            'title' => 'sub form under test forum',
                                            'is_category' => '0',
                                            'parentid' => '136665'
                                          }
                                 },
                   'title' => 'test',
                   'is_category' => '0',
                   'parentid' => '-1'
                 }
        };

and I need my output as follows

Main Forum

        add child, child of child

test

        sub form under test forum, another child

Nokia C2-01

Android

            under category

which should looks as below:
Main Forum
add child, child of child
test
sub form under test forum, another child
Nokia C2-01
Android
under category

thanks in advance.

A: This will create an HTML form without sorting
use strict;
use warnings;
use Data::Dumper;

sub form {
    my $hash = shift;
    my $form = '';
    my $iter; $iter = sub {
        my $hash = shift;
        my $indent = shift || '';
        while(my($k, $v) = each %{$hash}) {
            $form .= "<option value='" . $k . "'>" . $indent . $v->{title} . "</option>\n";
            if ($v->{children}){
                $iter->($v->{children}, $indent . "-");
            }
        }
    };
    $iter->($hash);
    return $form;
}

##EDIT
##SORT options by id
sub Sortedform {
    my $hash = shift;
    my $form = '';
    my $iter; $iter = sub {
        my $hash = shift;
        my $indent = shift || '';
        foreach my $k (sort keys %{$hash}) {
            my $v = $hash->{$k};
            $form .= "<option value='" . $k . "'>" . $indent . $v->{title} . "</option>\n";
            if ($v->{children}){
                $iter->($v->{children}, $indent . "--");
            }
        }
    };
    $iter->($hash);
    return $form;
}

print Dumper form($hash);
print Dumper Sortedform($hash);


text:
Q: Custom back button throws exception in iOS I am trying to implement a custom back button in iOS.
This is the code for the button inside viewDidLoad method:
let customFont = UIFont(name: "ChalkDuster", size: 17.0)
        UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: customFont!], forState: UIControlState.Normal)

        let backButton = UIBarButtonItem(title: "<<<", style: UIBarButtonItemStyle.Plain, target: navigationController, action: "transition:")
        navigationItem.leftBarButtonItem = backButton

Then the function transition() is as follows:
func transition() {
        print ("estoy aqui")
        self.navigationController?.popViewControllerAnimated(true)

    }

But I am getting an exception after touching the button:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[UINavigationController
  transition:]: unrecognized selector sent to instance 0x7f9f84008a00'

I don't know how to solve the exception.
Thanks

A: Remove semicolon at the end of the Selector. transition: to transition.
Also change target navigationController to self.