Sunday, July 24, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to clear Safari webview cache using SFSafariViewController?

Posted: 23 Jul 2022 09:06 AM PDT

I am currently using the SFSafariViewController to open a safari webview inside my app, however I seem to run into some issues inconsistently when the safari browser asks for some user permissions (like camera, location, etc). All these issues seem to resolve when the user clears the safari browser cache and reloads the page. Any ideas on how can I clear the cache programmatically using SFSafariViewController?

PS: Any possible reasons that might be causing the issues would be very helpful as well. The issues are mostly related to "denied" permission getting propagated without any input from the user, even though the user has selected "Always Ask for Permission". TIA.

Multiple API Calls with Promise.all in react.js

Posted: 23 Jul 2022 09:06 AM PDT

i'm trying to get different data from different apis. I don't have any problem when getting one and updating state. But i can't figured out how can i update two different state with Promise.all()

how can i make this code work.

const [stats, setStats] = useState(null);  const [info, setInfo] = useState(null);     React.useEffect(()=>{  Promise.all([    fetch('https://api.opensea.io/api/v1/collection/nickelodeon-rugrats-heyarnold-eth/stats'),    fetch('https://api.opensea.io/api/v1/asset_contract/0x223E16c52436CAb2cA9FE37087C79986a288FFFA')])    .then(res =>Promise.all(res.map(r=> r.json())))    .then((stats) => {      setStats(stats);    })    .then((info) => {      setInfo(info);    })    .then(data =>  console.log(data)).catch(error => console.log(error));  },[])  

Error reading file in python using openpyxl

Posted: 23 Jul 2022 09:05 AM PDT

So I have the error:

OSError: [Errno 22] Invalid argument  

When I try to read a file with openpyxl only in a server that uses ubuntu 22, in my computer with the same code I don't have the issue. It is not that the route is wrong, when I change the route it just says that the route does not exist. Here is the code part that opens the file:

workbook = load_workbook(filename="Web.xlsx", data_only=True)  

Does anyone know the reason of the error?

CPLEX function for basis inverse

Posted: 23 Jul 2022 09:05 AM PDT

I'm trying to reconstruct the final simplex tableau using CPLEX for the following problem

\ENCODING=ISO-8859-1  \Problem name:     Maximize   obj: 4 x1 - x2  Subject To   c1: x2 + x3  = 3   c2: 2 x1 - 2 x2 <= 3   c3: - 7 x1 + 2 x2 >= -14  End  

Using the function print(problem.solution.advanced.binvarow()[0] + problem.solution.advanced.binvrow())[0], I get the following output

[1.0, 0.0, 0.2857, 0.2857, 0.0, -0.1428]  

Thus, the coefficients of the first equation can be read from the elements of this array. For example,

1.0 x1 + 0.0 x2 + 0.2857 x3 + 0.2857 x4 + 1.0 x5 + 1.428 x6 = 2.8571  

However, the order in which these equations appear have interchanged. This corresponds to the third constraint in the original model specification, but is the first row in the function outputs.

I want to know if the original constraint correspond to this equation can be mapped easily, i.e., is there a way to know that this equation is associated with constraint c3?

I can find the basic columns and find its inverse without using the above in-built CPLEX function, but I wanted to avoid calculating the inverse.

Allow Unauthenticated users to only read data from firebase

Posted: 23 Jul 2022 09:06 AM PDT

I am working on a flutter app in which I want users to only read data without authenticating themselves with firebase auth. Is there a way? I tried the below code.

        rules_version = '2';             service cloud.firestore {            match /databases/{database}/documents {               match /{document=**} {          allow read, write: true;      }    }  }  

But firebase has been giving me warnings that my database is not secure every day. Is there a way to let users only read data from firestore without Unsecuring your firestore database?

Unity Raycasthit.Point Acting Weird

Posted: 23 Jul 2022 09:06 AM PDT

I'm trying to transport positions of a gameObject according to mouse position in 3D. However, When I do that with Raycasthit.point object is coming to player camera position like in this video

Is there anyone who can help me please

-> My Code:

 void Update()      {          if (currentObj != null)          {              currentObj.transform.position = MouseToWorldPositions();          }      }        public Vector3 MouseToWorldPositions()      {          Ray ray = playerCam.ScreenPointToRay(Input.mousePosition);          if (Physics.Raycast(ray, out RaycastHit hit, 999f, floorLayer))          {              return hit.point;          }          else          {              return Vector3.zero;          }      }    

How to click on link with text See more anyway using Selenium in Python?

Posted: 23 Jul 2022 09:06 AM PDT

When using Selenium I tried to scroll down the page but I don't know how to click on the link with text See more anyway.

enter image description here

The srand() doen't work until it's inside main().Why is this happening? [duplicate]

Posted: 23 Jul 2022 09:05 AM PDT

Newbie here!

I wrote a simple two dice rolling code. The srand() function doesn't work until I put it into the main() function. Why is that? At first I thought that with every dice_roll funtion call the srand() would do it's job! Insted I get doubles every time. As I said I fixed it when the srand() got into main() but I have a hard time understanting the logic! Here's my code(before solving the problem!!)

#include<stdio.h>  #include<stdlib.h>  #include<time.h>    int dice_roll();    main(int argc, char* argv[]){      int dice_1,dice_2;                dice_1=dice_roll();      dice_2=dice_roll();      printf("%d\n",dice_1);      printf("%d",dice_2);      }    int dice_roll(){      srand(time(NULL));      return (rand() % 6 +1);  }  

While migrating default database model assigned for another database is being migrated

Posted: 23 Jul 2022 09:06 AM PDT

I was working on two database for my Django project. I followed online Django documentation and made two sqlite database work at the same time for different purposes but I ended up having one issue which is while migrating default database the model Game that I created for 'games.db' is also being migrated to 'default.sqlite'. I have added my code below. Kindly help me fix this issue as I have tried multiple things but nothing worked out.

Project/settings.py  -------------------  DATABASES = {      'default': {          'ENGINE': 'django.db.backends.sqlite3',          'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),      },      'games': {          'ENGINE': 'django.db.backends.sqlite3',          'NAME': os.path.join(BASE_DIR, 'games.db'),      },  }    DATABASE_ROUTERS = (      'Games.dbrouters.GamesDBRouter',  )    Games/models.py  ---------------  from django.db import models  from django.urls import reverse    STATUS = (      (1, "Publish"),      (0, "Draft")  )      class Game(models.Model):      title = models.CharField(max_length=2000, unique=True)      slug = models.SlugField(max_length=2000, unique=True)      image = models.CharField(max_length=2000, unique=True)      overlay = models.CharField(max_length=2000, blank=True)      updated_on = models.DateTimeField(auto_now=True)      story_p = models.TextField(blank=True)      story_span = models.TextField(blank=True)      about_p = models.TextField(blank=True)      about_span = models.TextField(blank=True)      screenshot_1 = models.CharField(max_length=2000, blank=True)      screenshot_2 = models.CharField(max_length=2000, blank=True)      screenshot_3 = models.CharField(max_length=2000, blank=True)      screenshot_4 = models.CharField(max_length=2000, blank=True)      gameplay = models.CharField(max_length=2000, blank=True)      download_android = models.CharField(max_length=2000, blank=True)      download_ios = models.CharField(max_length=2000, blank=True)      download_windows = models.CharField(max_length=2000, blank=True)      download_linux = models.CharField(max_length=2000, blank=True)      download_mac = models.CharField(max_length=2000, blank=True)      torrent_android = models.CharField(max_length=2000, blank=True)      torrent_ios = models.CharField(max_length=2000, blank=True)      torrent_windows = models.CharField(max_length=2000, blank=True)      torrent_linux = models.CharField(max_length=2000, blank=True)      torrent_mac = models.CharField(max_length=2000, blank=True)      minimum_requirements = models.TextField(max_length=2000, blank=True)      recommended_requirements = models.TextField(max_length=2000, blank=True)      created_on = models.DateTimeField(auto_now_add=True)      status = models.IntegerField(choices=STATUS, default=1)        class Meta:          db_table = 'games'          ordering = ['-created_on']        def __str__(self):          return self.title        def get_absolute_url(self):          return reverse('game-detail', kwargs={              'slug': self.slug          })      Game.objects = Game.objects.using('games')    Games/dbrouters.py  ------------------  from .models import Game      class GamesDBRouter(object):      def db_for_read(self, model, **hints):          if model == Game:              return 'games'          return None        def db_for_write(self, model, **hints):          if model == Game:              return 'games'          return None        def allow_relation(self, obj1, obj2, **hints):          if obj1._meta.app_label == Game or \                  obj2._meta.app_label == Game:              return True          return None        def allow_migrate(self, db, app_label, model_name=None, **hints):          if app_label == Game:              return 'games'          return None

How do I count the frequency of letters in a string and sort by alphabetical orders?, if their frequency is 1, ignore them

Posted: 23 Jul 2022 09:06 AM PDT

Given string S consisting of only lowercase letters (a-z). Print to the screen all the letters that appear more than once in the string S and their number in lexicographical order.

a = input()  for i in range(len(a)):      if a.count(a[i])!=1:          print(a[i], a.count(a[i]))  

the problem here is it does print the frequency, but doesn't sort in alphabetical order, and some letter and their frequencies it print out more than 1

example input

thequickbrownfoxjumpsoverthelazydog  

example output

e 3  h 2  o 4  r 2  t 2  u 2  

How do I do this pls help

SQL Server 2019. Cannot create index in view because column is "Imprecise,computed and not persisted"

Posted: 23 Jul 2022 09:06 AM PDT

I want to create an index on a SQL Server view. The column I want to index is defined like this:

CASE       WHEN (CAST([LOCAL_DATE] AS float) - FLOOR(CAST([LOCAL_DATE] AS float)))            BETWEEN CAST([START_DATE] AS float) - floor(CAST([START_DATE] AS float)))                 AND (CAST([END_DATE] AS float) - FLOOR(CAST([END_DATE] AS float)))           THEN 1          ELSE 0   END AS InTime  

LOCAL_DATE is a datetime column in my source table. The InTime column in my view is just a flag, so normally it would be a bit, but SQL Server creates it as an Int column.

The thing is when I try to create a index in my view, it throws an error stating that the column is is "imprecise, computed and not persisted".

CREATE INDEX Index_Name ON [dbo].[MyView](InTime)  

Is there any workaround for this? I use float conversion to compare datetime, as to my understanding it's the fastest way.

For example DateTime is 1 Jan 2022 12:00

I need to know if this event occurred between 8:00 and 16:00 or not, and show my InTime column. So I use

(CAST([LOCAL_DATE] AS float) - FLOOR(CAST([LOCAL_DATE] AS float)))  

to get just the time.

The goal is to speed up any query that request events that occurred InTime

---- EDIT/UPDATE -----

After your suggestions, I'm trying with CAST function. But now I get a different error, saying that the column 'InTime' is "non-deterministic"

This is my actual view definition:

ALTER VIEW [dbo].[MyView]  WITH SCHEMABINDING   AS  SELECT        TOP (100) A.LOCAL_DATE,                               CASE WHEN CAST(LOCAL_DATE AS TIME) BETWEEN (CASE DATEPART(WEEKDAY, A.LOCAL_DATE) WHEN 1 THEN                               (SELECT        (CAST(StartDate AS TIME))                                 FROM            [dbo].[SCHEDULLE_TABLE] E                                 WHERE        E.IdCen = A.IdCen) ELSE                               (SELECT        (CAST(StartDateB AS TIME))                                 FROM            [dbo].[SCHEDULLE_TABLE] E                                 WHERE        E.IdCen = A.IdCen) END) AND (CASE DATEPART(WEEKDAY, A.LOCAL_DATE) WHEN 1 THEN                               (SELECT        (CAST(EndDate AS TIME))                                 FROM            [dbo].[SCHEDULLE_TABLE] E                                 WHERE        E.IdCen = A.IdCen)  ELSE                               (SELECT        (CAST(EndDateB AS TIME))                                 FROM            [dbo].[SCHEDULLE_TABLE] E                                 WHERE        E.IdCen = A.IdCen) END) THEN 1 ELSE 0 END AS InTime  FROM            dbo.EventTable AS A   GO  

seboarn lmplot in python3 in ubuntu terminal

Posted: 23 Jul 2022 09:06 AM PDT

I am not able to see lmplot in python3. created a test.py file and ran in using python3 in terminal.

I can see the reg_plot while using sns.regplot(). But I am not able to see sns.lmplot().

*File : test.sv

import pandas as pd  import numpy as np  import seaborn as sns  import matplotlib.pyplot as plt  df = sns.load_dataset("iris")  sns.lmplot(x="sepal_length", y="sepal_width", data=df, hue='species', legend=False)  ## note : sns.regplot --> is working fine in this case   plt.show()  

Convert Single Line to Multiple Lines

Posted: 23 Jul 2022 09:06 AM PDT

I am new to this Powershell.

I am trying to learn how to modified output.

When I run "Write-output $result | format-list" I have the following output


userDetails     : @{id=AA:BB:CC:DD:11:22; connectionStatus=CONNECTED; hostType=WIRELESS;                    authType=WPA2/WPA3+802.1x/FT-802.1x}  connectedDevice : {@{deviceDetails=}}  

How do I rewrite this output to below using powershell 7.2 ? I would like to have


userDetails     :   connectionStatus= CONNECTED  hostType        = WIRELESS  authType        = WPA2/WPA3+802.1x/FT-802.1x    connectedDevice :  

Thank you for your help.

Dismiss a child view without it executing the parent view OnCreate function

Posted: 23 Jul 2022 09:06 AM PDT

I have the following in my AndroidManifest.xml file:

<activity      android:name=".PickemAllPicksResultsActivity"      android:label="@string/title_activity_backActionBar"      android:parentActivityName=".PoolDetailsActivity"      android:screenOrientation="portrait" />  

The above places a back button/arrow (in the action bar) in my child view in order to navigate back to the parent view.

I have the following layout for the child view:

<RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      tools:context=".PickemAllPicksResultsActivity" >        <com.google.android.material.tabs.TabLayout          android:id="@+id/tabLayout"          android:layout_width="match_parent"          android:layout_height="wrap_content" >            <com.google.android.material.tabs.TabItem              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:text="Weekly" />            <com.google.android.material.tabs.TabItem              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:text="Overall" />        </com.google.android.material.tabs.TabLayout>        <androidx.viewpager2.widget.ViewPager2          android:id="@+id/viewPager"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:layout_below="@+id/tabLayout"          android:layout_centerHorizontal="true" />    </RelativeLayout>  

When i click on the back button in the action bar the app crashes because the parent view is executing the onCreate which is calling a Firebase function:

// Get the Pool Info  poolReference = mFirebaseDatabase.getReference("PICKEMPOOLS").child(poolID);  

and poolID is null.

Question, why does this back button trigger the OnCreate function, but if I press the back button on the Android Navigation is just dismisses the screen and goes to the previous view?

Java generic erasing after Java 8

Posted: 23 Jul 2022 09:05 AM PDT

I know that Java generic type information is erased at runtime. I have sort-of-abused this to put "wrongly typed" objects into maps to mark mapping to nulls:

import java.util.*;    public class test  {      private static final Object NULL = new Object();        public static void main(String[] args) throws Exception      {          Map<String, String> kek = new HashMap<>();          kek.put("foo", maskNull(null));      }        @SuppressWarnings ("unchecked")      public static <T> T maskNull(T value)      {          return value != null ? value : (T) NULL;      }  }  

Of course in real code I would use sth. like maskNull(foo) where foo could be anything, so I wouldn't know if it was null or not in advance. Functions like isMaskedNull() etc. are omitted for brevity.

This used to work fine in Java 8. However, now that I'm trying to upgrade to Java 11, I get the following error at runtime:

Exception in thread "main" java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.String (java.lang.Object and java.lang.String are in module java.base of loader 'bootstrap')          at test.main(test.java:10)  

As I understand, Java compiler now implicitly emits type-casting operation before put() is called. Is there a way out of it, i.e. can I get the old behavior at least in specifically marked (I don't know, with an annotation?) cases?

Why can't I access Session data that exists before the return statement in NextJs page

Posted: 23 Jul 2022 09:05 AM PDT

Trying to understand how this works.

I have a Session present in NextJS. I can access that inside the page view no problem.

But If I try to access any of that data before the return statement, it comes back undefined, even though the variables are in the page when it renders.

Can anyone tell me why this is?

Sample code from a page

...  const { data: session } = useSession();    if(session) {    console.log("USER ID : " + session.userId); <--- Never runs  }  console.log("USER ID : " + session?.userId); <--- Undefined  // @ts-ignore  if(session) {    return (      <>        <div className="min-h-full">          <nav className="bg-fadedFadedPurple">            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">              <div className="flex items-center justify-between h-16 w-full">                <div className="flex items-center w-full h-full">                  <div className="flex-shrink-0">   Perfectly fine ---><Link className="hover:cursor-pointer" href={`/app/${session.userId}/dashboard`}>                    ...  

Resizing NSImage keeping aspect ratio reducing the image size while trying to scale up

Posted: 23 Jul 2022 09:06 AM PDT

I'm using the following code to resize an NSImage by preserving the aspect ratio. But this extension method keeps reducing the image size when I try to increment the same

func resizeMaintainingAspectRatio(width: CGFloat, height: CGFloat) -> NSImage? {          let ratioX = (width/(NSScreen.main?.backingScaleFactor)!) / size.width          let ratioY = (height/(NSScreen.main?.backingScaleFactor)!) / size.height          var ratio = ratioX < ratioY ? ratioX : ratioY          let newHeight = size.height * ratio          let newWidth = size.width * ratio          let canvasSize = CGSize(width: newWidth, height: newHeight)          let img = NSImage(size: canvasSize)          img.lockFocus()          let context = NSGraphicsContext.current          context?.imageInterpolation = .high          draw(in: NSRect(origin: .zero, size: NSSize(width: newWidth,height: newHeight)), from: NSRect(origin: .zero, size: size) , operation: .copy, fraction: 1)          img.unlockFocus()          return img      }  

Usage:

    let w = CGFloat(logoimage!.size.width) + 10      let h=CGFloat(logoimage!.size.height) + 10      logoimage=originallogoimage?.resizeMaintainingAspectRatio(width: w, height: h)  

Replacing some emoticons with emojis in python

Posted: 23 Jul 2022 09:06 AM PDT

This is what my code currently looks like. I wanted to change the emoticons to emojis when the user inputs a sentence or word. How do I go by it?

def main():      sentence = input("Input a Sentence: ")      convert(sentence)      print(sentence)      def convert():      emo1 = ":)"      emo2 = ":("      emo1.replace(":)", "🙂")      emo2.replace(":(", "🙁")      main()  

Display image or video from source in react when source is random

Posted: 23 Jul 2022 09:06 AM PDT

I'm pulling certain assets from an api but the issue is that the assets contain image, video and canvas therefore the source type is random, I want to display all of them on a page but the source link doesn't have a mimetype it's just an ipfs hash so can't differentiate on basis of that.

Is there a way to display image and if image is broken display with video tag and if its broken display with canvas tag?

Example for video -> https://infura-ipfs.io/ipfs/QmVSCZfGc5ArLSzra2A5yTrwASaM92sdWGj4ovZuiLTG6f

Example for canvas -> https://infura-ipfs.io/ipfs/QmSD9GfNwAtBH6WVUEhfK7wX6vFbsUqRzupqjD25Pn2RQV

How to represent meta data in JSON

Posted: 23 Jul 2022 09:05 AM PDT

Note: this is a NodeJs app

I have the following JSON object that stores questions and answers:

{      "id": "SOME_GUID",      "questions": {          "page-1": {              // ... JSON schema for page 1.          },          "page-2": {              // ... JSON schema for page 2.          }      },      "answers": {          "page-1": {              "page-1-question-1": "something"          },          "page-2": {              "page-2-question-1": true,              "page-2-question-2": "foo"          },      }    }  

Is there a benefit of representing the data in a specific way over another? I would naturally opt for a simple key/value pair notation (shown below) as it seems to fit the bill here. But I have seen the "array notation" (shown below) in the wild (in projects written in Java)

key/value pair notation (what I would naturally use):

{      "meta": {          "createdData": "some date",          "modifiedData": "some date",          "referenceNumber": "some reference number",          "type": "some type code"      }  }  

or

"array" notation

{      "meta": [          {              "key": "createdDate",              "value": "some date"          },          {              "key": "modifiedData",              "value": "some date"          },          {              "key": "referenceNumber",              "value": "some reference number"          },          {              "key": "type",              "value": "some type code"          },      ]  }    

OpenCV 4.0.0 SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set

Posted: 23 Jul 2022 09:06 AM PDT

Hello I am trying to create a facial recognition program but I have a peculiar error: here is my code:

import cv2 as cv  gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  face_cascade = cv.CascadeClassifier("lbpcascade_frontalface.xml")  faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);  

and this error is the output

SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set  

I have "lbpcascade_frontalface.xml" in the working directory so that shouldn't be an issue

if it helps when I enter

cv.__version__  

I get

'4.0.0'  

Read DbContextOptions value in Entity Framework core constructor

Posted: 23 Jul 2022 09:05 AM PDT

In my asp.net core service, I have this in the startup

services.AddDbContext<Mydb_Context>(      options => options.UseSqlServer(Configuration["Settings:ConnString"]));  

and to make it works, I created also this snippet:

public Mydb_Context(DbContextOptions<Mydb_Context> options) : base(options)  {      //other stuff here  }  

My problem now is: in "other stuff here" section, how can I read the options value and retrieve my connection string? Since there another dll and not the same project, I can't just read it again from the appsettings.json.

If I break my code during a debug session, I can see the connection string in the value inside this object, but I don't know how to get it properly. I see this value inside the "Extension" attribute of the options object.

So, how can I read the DbContextOptions value?

How does Holoviews know which colours to assign to each scatterplot in an overlay?

Posted: 23 Jul 2022 09:05 AM PDT

In the bokeh Holoviews gallery, there is an example called 'Scatter economic'.

http://holoviews.org/gallery/demos/bokeh/scatter_economic.html#bokeh-gallery-scatter-economic

In this plot, notice how one of the options for Scatter is (color=Cycle('Category20')). The last line of the plot is gdp_unem_scatter.overlay('Country').

  • My question is: How does Holoviews know to connect each Scatter to a particular color in Cycle('Category20')? Is this just a property of Cycle()? Is there some way that the Overlay interacts with the Scatter and with the Cycle automatically?
  • A slightly related confusion is that if I use the .opts method instead of the cell magic as in the example, it still works. For example, if I use the .opts method with this cycle color on the Scatter (i.e., second to the last line in the above example), and then do an .overlay('Country'), somehow Holoviews knows to assign each Scatter to a particular color based on the Country.

I want to make sure that I am properly plotting what I intend to.

Thank you!

Reverse object with Object.keys and Array.reverse [duplicate]

Posted: 23 Jul 2022 09:06 AM PDT

i got the following object

{    "20170007": {      "id": 1    },    "20170008": {      "id" : 2    },    "20170009": {     "id": 3    },    "20170010": {      "id": 4    }  }  

desired output:

{    "20170010": {      "id": 4    },    "20170009": {     "id": 3    },    "20170008": {      "id" : 2    },    "20170007": {      "id": 1    }  }  

my attempt:

const obj = {    "20170007": {      "id": 1    },    "20170008": {      "id" : 2    },    "20170009": {     "id": 3    },    "20170010": {      "id": 4    }  }    const reverseObj = (obj) => {    let newObj = {}      Object.keys(obj)      .sort()      .reverse()      .forEach((key) => {        console.log(key)        newObj[key] = obj[key]      })      console.log(newObj)    return newObj    }    reverseObj(obj)

the wierd part is that when i console.log the key inside the forEach, the keys are reversed. but when i assign the key to the newObj the output is still in the original order... whats going on here ?

EDIT:

thanks for all the responses i took a look into The Map object. Map

new Map([iterable])  

Wich was actually i was looking for and the order is guaranteed.

Google Visualization - vAxis maxValue property not working

Posted: 23 Jul 2022 09:06 AM PDT

For a reason that totally escapes me, I can't get the maxValue property of vAxis to work:

var options = { vAxis: { maxValue: .85 } }

The vAxis is a percentage with a range of 0 to 100% and I'd like to save some room by setting the max to 85%. I think it has something to do with this project switching between 7 DataSources and 4 ChartTypes because I've never had this problem when I made single charts.

The following Snippet is a reduced case with the minimal functionality that could be related to the issue. Thank you for your time and effort.

SNIPPET

<!DOCTYPE html>  <html>    <head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">    <title>G04B32</title>    <link href='https://glpro.s3.amazonaws.com/_css/glb.css' rel='stylesheet'>    <style>      @import url('https://fonts.googleapis.com/css?family=Open+Sans');      *,      *:before,      *:after {        font-style: normal !important;      }      body {        position: relative;      }      form {        background-image: url(https://glpro.s3.amazonaws.com/ag/04/data/bgl720x404.png);        background-color: #333;      }      #ii {        margin-top: 80px      }      .panel {        display: flex;        flex-wrap: wrap;        justify-content: center;        align-items: center;      }      #chart {        height: 70vh; width: 96vw; background-image: url(https://glpro.s3.amazonaws.com/ag/04/data/bgl720x404.png); background-size: cover; background-repeat: no-repeat; }        .group.group: after, .chart.chart: after, .root.root: after {          color: #333;        }        div.google-visualization-tooltip {          background-color: rgba(0, 0, 0, .6);          border-radius: 6px;          min-width: 325px;          max-height: 75px;        }        div.google-visualization-tooltip > ul > li {          display: table-cell;          margin: 0 5px;        }        div.google-visualization-tooltip > ul > li > span {          color: gold;        }        #groupOpt.off {          display: none;        }        #groupOpt.on {          display: block;        }    </style>  </head>    <body class='sl'>  <!--THIS SECTION WAS REMOVED-->    <section id="ii">      <h1>Sources</h1>      <figure id='chart'></figure>    </section>    <footer></footer>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>    <script type="text/javascript">      google.charts.load('current', {        packages: ['corechart']      });      google.charts.setOnLoadCallback(drawChart);        var options = {        backgroundColor: {          fill: 'transparent'        },        tooltip: {          textStyle: {            color: 'gold',            fontSize: 16,            fontName: 'Verdana'          },          trigger: 'focus',          isHtml: true        },        animation: {          startup: true,          duration: 1000,          easing: 'out'        },        title: 'Percentage of Americans in Favor of Same-sex Marriage (2001-16)',        titleTextStyle: {          color: 'gold',          fontName: 'Open Sans',          fontSize: 22        },        hAxis: {          textStyle: {            color: 'cyan'          },          title: 'Year',          titleTextStyle: {            color: 'gold',            fontName: 'Open Sans',            fontSize: 22          },          format: '####',          slantedText: true        },        vAxis: {          maxValue: .85,// <<<<<<<<<<<<<<<<<<<<<DOESN'T WORK>>>>>>          format: '#%',          textStyle: {            fontName: 'Open Sans',            color: 'cyan'          },          title: 'Percentage of Sub-Population that Approves of Same-sex Marriage',          titleTextStyle: {            color: 'gold',            fontName: 'Arial',            fontSize: 16          }          },                legend: {          textStyle: {            color: 'white',            fontName: 'Verdana'          },          position: 'bottom'        },          crosshair: {          trigger: 'both',          orientation: 'both',          focused: {            color: 'gold',            opacity: .7          },          selected: {            color: 'cyan',            opacity: .7          }        },        pointSize: 12,        theme: 'materials',        chartArea: {          left: 100,          top: 75,          width: '90%',          height: '60%'        }        }        var chart;      var main;      var cArray = ['LineChart', 'AreaChart', 'ColumnChart', 'ScatterChart'];      var qArray = [DATA REMOVED];        function drawChart() {        chart = new google.visualization.ChartWrapper();        chart.setDataSourceUrl(qArray[0]);        chart.setChartType(cArray[0]);        chart.setContainerId('chart');        chart.setOptions(options);        chart.draw();      }        function alterChart(C, Q) {          C = Number(C);        Q = Number(Q);        var URL = qArray[Q];        var VIS = cArray[C];          main = new google.visualization.ChartWrapper();        main.setDataSourceUrl(URL);        main.setChartType(VIS);        main.setContainerId('chart');        main.setOptions(options);        main.draw();      }        $('#chartOpt, #groupOpt, #rootOpt').on('change', function(e) {        var chartSel = $("input[name='chart']:checked").val();        var groupSel = $("input.chx:checked").val();        if (e.target !== e.currentTarget) {          var target = e.target.id;          var status = $("input[name='root']:checked").attr('id');        }          if (target === 'root0' && status === 'root0') {          $('#groupOpt').slideUp().removeClass('on').addClass('off');          return alterChart(chartSel, groupSel);        }        if (target === 'root1' && status === 'root1') {          $('#groupOpt').slideDown().addClass('on').removeClass('off');          return alterChart(chartSel, groupSel);        }      <!--THIS PART REMOVED-->      }    </script>    <!--<script src='gvis-api.js'></script>-->  </body>    </html>

How to get sftp version of remote server?

Posted: 23 Jul 2022 09:06 AM PDT

As part of trying to debug an issue, I would like to know which version of sftp is installed on the remote server where I am trying to push files.

I was told to use -vvv at the command line, but I can't any documentation about it. Is there any other option? My server is Linux based.

My other question is: say two servers have not installed the same version of SFTP, is there a kind of protocol version negotiation to make sure they 'speak the same language'?

Mock private static final String using Mockito

Posted: 23 Jul 2022 09:05 AM PDT

I am having a difficulty time mocking a private static final String field in a class. Here is my java sample code:

public class Fruit {  private static final String FRUIT = "apple";    public void getFruit() {      System.out.println("I like " + FRUIT);  }  

}

And I used Mockito to mock the FRUIT variable so that I can change the value of FRUIT from "apple" to "mango". For that here is my test:

public class FruitTest {  @Test  public void testFruit() throws NoSuchFieldException, SecurityException, Exception {      setFinalStatic(Fruit.class.getDeclaredField("FRUIT"), "mango");      Fruit fruit = new Fruit();      fruit.getFruit();  }    static void setFinalStatic(Field field, Object newValue) throws Exception {      field.setAccessible(true);      Field modifiersField = Field.class.getDeclaredField("modifiers");      modifiersField.setAccessible(true);      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);      field.set(null, newValue);  }  

}

I was expecting when I do System.out.println("I like " + FRUIT); it will print mango, but still it is printing apple. I would really appreciate if anyone can help me with this ONLY USING MOCKITO and not PowerMock etc.

Delete history for all browsers with Batch file

Posted: 23 Jul 2022 09:05 AM PDT

I am trying to delete the history of IE, FireFox, Chrome and Opera using a batch file when staff log in. Below is what I have and it works but it also clears the bookmarks and preferences of Chrome and I think Firefox. How do I just clear the history without clearing bookmarks and preferences. Any help would be great, thank you.

@echo off    rem IE  taskkill /F /IM iexplore.exe  start "" "C:\Windows\System32\rundll32.exe" InetCpl.cpl,ClearMyTracksByProcess  255    :: Parse the Local AppData sub path  call :Expand xAppData "%%LocalAppData:%UserProfile%=%%"    set "xFirefox=\mozilla\firefox\profiles"  set "xChrome=\google\chrome\user data"  set "xOpera1=\Local\Opera\Opera"  set "xOpera2=\Roaming\Opera\Opera"    :: Start at the User directory  pushd "%UserProfile%\.."    taskkill /F /IM firefox.exe  taskkill /F /IM chrome.exe  taskkill /F /IM opera.exe    :: Loop through the Users      for /D %%D in (*) do if exist "%%~fD%xAppData%" (      rem Check for Firefox      if exist "%%~fD%xAppData%%xFirefox%" (          rd /s /q "%%~fD%xAppData%%xFirefox%"      )       rem Check for Chrome     if exist "%%~fD%xAppData%%xChrome%" (          rd /s /q "%%~fD%xAppData%%xChrome%"      )        rem Check for Opera      if exist "%%~fD%xAppData%%xOpera1%" (          rd /s /q "%%~fD%xAppData%%xOpera1%"      )      if exist "%%~fD%xAppData%%xOpera2%" (          rd /s /q "%%~fD%xAppData%%xOpera2%"      )  )  popd  goto End      ::::::::::::::::::::::::::::::  :Expand <Variable> <Value>  if not "%~1"=="" set "%~1=%~2"  goto :eof      :End  endlocal  pause  

Cannot install .apk file on emulator

Posted: 23 Jul 2022 09:05 AM PDT

The Issue:
I'm using Android Studio on Win8 platform to develop my new android application. I can upload and install the apk on my physical device (Samsung Galaxy S4-mini Dous) with no problem. But, when I want to upload and install it on Emulator, it gets stock and wait for ever!

What I have done:
- I used Eclipse to see if the issue is related to Android Studio, but the same result.
- I increased the ADB connection timeout value; no success.
- I used adb in command-line mode tp install the package; no success again.
- Searched through StackOverflow site (and some other sites) to see if there is any answer to similar issue, didn't help.

My Situation:
Actually AVD is needed to run some optimization tools (which is not working for physical devices). I would appreciate if somebody can help me fixing this issue.

Thanks in advance for any reply.

Sams Teach Yourself Java in 24 Hours Sixth Edition by Rogers Cadenhead MP3 Chapter 20 MP3 File Error

Posted: 23 Jul 2022 09:05 AM PDT

I am a java novice trying to go through the book listed in the title of this post. This is also my first question to post on stack overflow. There does not appear to be a forum for the book so I decided to ask here.

I am on Chapter 20: Reading and Writing Files in Java 24 Hours and have gotten to the ID3Reader.java project. I am using Netbeans 7 to create this project. The code is supposed to analyze an MP3 file (which I have made my argument using the absolute path) and skip everything but the last 128 bytes. Then, the remaining bytes are examined to see if they contain any ID3 data. If they do, the first three bytes are the numbers 84, 65, 71. Then it displays the title, the artist, the album and the year in a descending order.

import java.io.*;    public class ID3Reader {  public static void main(String[] arguments) {      try {          File song = new File(arguments[0]);          FileInputStream file = new FileInputStream(song);          int size = (int) song.length();          file.skip(size - 128);          byte[] last128 = new byte[128];          file.read(last128);          String id3 = new String(last128);          String tag = id3.substring(0, 3);          if (tag.equals("TAG")) {              System.out.println("Title: " + id3.substring(3, 32));              System.out.println("Artist: " + id3.substring(33, 62));              System.out.println("Album: " + id3.substring(63, 91));              System.out.println("Year: " + id3.substring(93, 97));          } else {              System.out.println(arguments[0] + " does not contain"                  + " ID3 info.");          }          file.close();      } catch (Exception e) {          System.out.println("Error — " + e.toString());      }      }  

Again I have set the argument to exactly where the MP3 file is and have even got the code from the website for this book.

C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\Java24\Where The Moon Came From - Moonbrows (Twin Of Pangaea).   

But instead I get this error.

Error — java.io.FileNotFoundException: C:\Documents (The system cannot find the file specified)  

I have pulled my hair out trying to find something that would help me on this problem but I just cannot seem to find anything that I can translate to this problem. I would very much appreciate any information that you can give me. If there is any more information that is needed to be known before you can answer just say the word an I will get it.

No comments:

Post a Comment