text:
Q: "All of X" unexpected result | Podio JS Calculation I am using the Podio variables and it's returning unexpected results.
var $arr_type = @All of TIME TYPE;
var $arr_duree = @All of DURATION;
var $result = 0;
for (var i = 0; i < $arr_type.length; i++) {
    if($arr_type[i] == 'WANTED_TYPE')
        $result += $arr_duree[i];
}
$result;

TIME TYPE is a category field. DURATION is a duration field.
How can I return the string of the category? $arr_type[0] returns 0 and $arr_type[1]doesn't process.
See screenshot: http://dev.magikweb.ca/hotlink/screeny.png
Thank you for any feedback!
Solution
This is actually a working exemple. I was comparing ouvrable when it should of been Ouvrable. The calculation field is VERY limited about debugging.

A: JavaScript is case sensitive. Look at the value of WANTED_TYPE and see if there's some caps in it.
Example: if you have a value called "Potato" and you compare to "potato", the result will be false.


text:
Q: Pkg.install on windows repo in top.sls files for node group I follow the following guide on how to setup windows software repository
I can manually install a package on a node by executing:
salt node pkg.install 'firefox'

How do I transform this to a configuration in a top.sls file using pkg.install (or something similar) so that I could target a nodegroup using state.highstate and only install software that is not previously installed?
Using the answer from Utah_Dave firefox I will get the following error message: (given that firefox is already installed on the machine, if I do a fresh install the error message/logs are similar and firefox will install on the machine but still return False)
my-node:
----------
          ID: firefox
    Function: pkg.installed
      Result: False
     Comment: The following packages failed to install/update: firefox=40.0.3

And from the debug logs from the salt-minion:
[DEBUG   ] Fetching file from saltenv 'base', ** attempting ** 'salt://firefox.sls'
[INFO    ] Fetching file from saltenv 'base', ** done ** 'firefox.sls'
[DEBUG   ] LazyLoaded cmd.run
[DEBUG   ] Jinja search path: ['c:\\salt\\var\\cache\\salt\\minion\\files\\base']
[DEBUG   ] Rendered data from file: c:\salt\var\cache\salt\minion\files\base\firefox.sls:
firefox:
  pkg.installed
[DEBUG   ] LazyLoaded config.get
[DEBUG   ] Results of YAML rendering:
OrderedDict([('firefox', 'pkg.installed')])
[DEBUG   ] LazyLoaded pkg.install
[DEBUG   ] LazyLoaded pkg.installed
[DEBUG   ] Error loading module.tls: ['PyOpenSSL version 0.14 or later must be installed before  this module can be used.']
[DEBUG   ] Error loading module.nacl: libnacl import error, perhaps missing python libnacl package
[DEBUG   ] Error loading module.ipmi: No module named pyghmi.ipmi
[DEBUG   ] Error loading module.npm: npm execution module could not be loaded because the npm binary could not be located
[DEBUG   ] Could not LazyLoad pkg.ex_mod_init
[INFO    ] Running state [firefox] at time 08:18:32.643000
[INFO    ] Executing state pkg.installed for firefox
[DEBUG   ] Initializing COM library
[DEBUG   ] Uninitializing COM library
[DEBUG   ] Could not LazyLoad pkg.normalize_name
[DEBUG   ] Could not LazyLoad pkg.check_db
[DEBUG   ] Could not LazyLoad pkg.normalize_name
[DEBUG   ] Initializing COM library
[DEBUG   ] Uninitializing COM library
[WARNING ] Specified file https://download-installer.cdn.mozilla.net/pub/firefox/releases/40.0.3/win32/en-US/Firefox%20Setup%2040.0.3.exe is not present to generate hash
[DEBUG   ] Reading configuration from c:\salt\conf\minion
[DEBUG   ] file_roots is c:\salt\srv\salt
[DEBUG   ] Using GET Method
[INFO    ] Executing command ['c:\\salt\\var\\cache\\salt\\minion\\extrn_files\\base\\download-installer.cdn.mozilla.net\\pub\\firefox\\releases\\40.0.3\\win32\\en-US\\Firefox%20Setup%2040.0.3.exe', '/s'] in directory 'C:\\Users\\aes.jenkins'
[DEBUG   ] Initializing COM library
[DEBUG   ] Uninitializing COM library
[DEBUG   ] Could not LazyLoad pkg.hold
[DEBUG   ] Initializing COM library
[DEBUG   ] Uninitializing COM library
[ERROR   ] The following packages failed to install/update: firefox=40.0.3
[INFO    ] Completed state [firefox] at time 08:18:46.939000

A: cat /srv/salt/firefox.sls:
firefox:
  pkg.installed

cat /srv/salt/top.sls:
base:
  'myNodeGroupName':
    - match: nodegroup
    - firefox

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open an URL in Safari with Private Browsing I want to open an URL in a browser's private mode.
--args -incognito does the job with Chromium-based browsers (e.g. open -na "Google Chrome" --args -incognito http://www.example.com).
I tried -incognito, -private, -private-browsing arguments, but none worked with Safari.
What's a Safari's command option to open in private mode?

A: Safari does not have similar command line options like Google Chrome, however, here is a way to roll your own:
In Terminal, run the following compound command:
touch safari; open -e safari; chmod +x safari

Copy and paste the example AppleScript code, shown further below, into the opened safari document, then save it.
You should then move the safari shell script to a directory located within the shell's PATH.
I moved it to /usr/local/bin, e.g,:
sudo mv -v safari /usr/local/bin/

Now from Terminal I can open a new private window for Safari.  Typing just the executable's name without any arguments shows how it can be used e.g,:
% safari
Missing Arguments!...
Examples:
safari https://www.example.com
safari -private
safari -private https://www.example.com
%

Notes:

*

*As coded, the example AppleScript code is focused on opening a new private window, however, as you can see it can open a normal new window to the provided URL too. For the new private window, you can open it with or without passing it a URL.

*As coded, the example AppleScript code only allow for one URL to be passed at a time. Additional coding is required to allow passing multiple URLs.

Example AppleScript code:
#!/usr/bin/osascript

on run args

    if args is {} then return ¬
        "Missing Arguments!..." & linefeed & ¬
        "Examples:" & linefeed & ¬
        "safari https://www.example.com" & linefeed & ¬
        "safari -private" & linefeed & ¬
        "safari -private https://www.example.com"

    set newPrivateWindow to false

    if item 1 of args contains "-private" then
        set newPrivateWindow to true
        if (length of args) is not greater than 1 then
            set theURL to missing value
        else
            set theURL to item 2 of args
        end
    else
        set the theURL to item 1 of args
    end if

    tell application "Safari" to activate
    delay 1

    if newPrivateWindow then
        tell application "System Events" to ¬
            keystroke "n" using ¬
                {shift down, command down}
        delay 1
        openURL(theURL)
    else
        tell application "System Events" to ¬
            keystroke "n" using ¬
                {command down}
        delay 1
        openURL(theURL)
    end if

end run

on openURL(theURL)
    if theURL is missing value then
        return
    else
        tell application "Safari" to ¬
            set URL of ¬
                current tab of ¬
                front window to ¬
                theURL as string
    end if
end openURL


text:
Q: Problem with sqlite in the android device I am using sqlite to save some string values in the database, my app works perfectly in the emulator. But when I tried it on the Samsung Galaxy Tab, the log cat says that there are not such tables... before mounting the apk files to the device I have tried opening it in the archive mode and found the database and the tables secure in my "assets" folder.
Can any one tell me whats going wrong with me ?
thanks in advance...
Happy coding

A: Databases don't belong in the assets-folder! You should use a SQLiteOpenHelper-class to create and update your Database when it's needed.
Tutorial (or simply Google for it).

A: I have experience with the same thing you are experiencing now. This is a classic in device manufacturer fragmentation. It has happened to me before when trying to run an application on a Samsung Nexus S phone that had a method to copy a already existing database to the application from assets on install (i am guessing that's what you are doing at the moment). so long story short, after quite some testing the best and only solution i could find was to actually do the manual work and create the database with the help of the SQLiteHelper methods and table creating queries and recreate the same scheme. this method works 100% so far on every phone i have tried it so that's the safest thing you can do.
Hope this helps.

A: The db file should be available in "/data/data/YOUR_PACKAGE/databases/" folder in your device.
If this is the first time you are creating the db then you should copy the db file from your assets folder into the above location (the first time when you access the database).


text:
Q: why my subquery is not executing? I am going to Work with Sub queries in mysql, the question is when I am trying to execute it, i got this error, it should be mention that my column names are correct.
 Error message: #1064 - You have an error in your SQL syntax; check
 the manual that corresponds to your MySQL server version for the
 right syntax to use near 'Products      WHERE
 productLine In              (SELECT text' at line 2

SELECT ProductName, buyPrice
     FROM Products
     WHERE productLine In
             (SELECT textDescription
             FROM productline
             WHERE productLine = "Motorcycles");


text:
Q: creating XML file inside WEB-INF Im using http://tuckey.org/urlrewrite/ to create a map of my website, currently i have a lot of links and i cant write all the rules by hand, example:
<rule>
   <from>^/about-us$</from>
   <to type="redirect">/myWeb/Controller?page=ForwardAbout</to>
</rule>

Tuckey uses a file called urlrewrite.xml inside WEB-INF folder.
The redirect rules could come from a database, for example: whenever an article is created, insert a row to the desired link like:
/about-potatoes

And the rule would become this
<rule>
   <from>^/about-us$</from>
   <to type="redirect">/myWeb/Controller?page=ForwardPotatoes</to>
</rule>

Then the urlrewrite.xml should be written so the redirect to the new article applies.
The main question is: How can I create this urlrewrite.xml inside WEB-INF?
Secondary question: Suposing that new articles are made every week, creating this urlrewrite.xml every week to update the rules, would the rules apply without having to re-deploy the web-app again?

A: On most application servers, you can't dynamically change anything inside the web application, unless you re-package and re-deploy the application.
Even if you could change the file, e.g. in unpacked wars, tuckey will probably still read the file only once, and not pick up the new rules unless you restart the application.
Why don't you make a more dynamic rule that matches all requests? In the rewrite rule you can use backreferences e.g. '$1' that will match the first regular expression that is between brackets, like:
<rule>
   <from>^/about-(.*)$</from>
   <to type="redirect">/myWeb/Controller?page=Forward$1</to>
</rule>


text:
Q: Computing Gaussian curvature of hyperbolic space using Thurston I'm currently reading through Thurston's book Three-Dimensional Geometry and Topology, and I am working on an exercise that has you compute the Gaussian curvature of the Poincare ball model of hyperbolic space. The way he has you compute this is by computing the hyperbolic length of a circle of radius $r$ centered at the origin, and then using the following fact that he gave earlier: he claims that $-1/3$ times the Gaussian curvature is equal to the second derivative of the ratio $c/2\pi r$ at $r=0$, where $c$ is the hyperbolic circumference of a circle of radius $r$, (this is found on page 47 of Thurston).
Here is what I have so far. To find the circumference of the circle, I computed
$$ c=2\int_0^{2\pi} \frac{r}{1-r^2}dt = \frac{4\pi r}{1-r^2}.$$
Then if we let $f(r) = c/2\pi r$, then
$$ f''(r) = 2\left(\frac{8r^2}{(1-r^2)^3} + \frac{2}{(1-r^2)^2}\right),$$
so $f''(0) = 4$. Then according to Thurston, if $K$ is the Gaussian curvature, we should get that $-1/3 K = 4$, meaning $K = -12$. This is clearly not correct since I know the curvature is supposed to be $-1$.
If anyone sees a mistake I am making or something that I am misunderstanding, your insight would be much appreciated!

A: The problem is that the coordinate $r$ does not tell you the radius of the circle: the length of a geodesic from the origin of the coordinate system to a point with parameter $r$ is
$$ R(r) = \int_0^r ds(\rho) = \int_0^r \sqrt{\frac{4}{(1-r'^2)^2}dr'^2} = \int_0^r \frac{2}{1-r'^2} \, dr' = 2\arg\tanh{r}. $$
(You do actually know the length can't be just $r$, since the lengths of radial lines are unbounded, rather than bounded above by $1$) So $r = \tanh{(R/2)}$. Therefore, the circumference of a disc of radius $R$ in terms of $R$ is
$$ 2\pi\frac{2r}{1-r^2} = \dotsb = 2\pi\sinh{R}, $$
and $\sinh{R}/R = 1 + R^2/6 + O(R^4)$, so the second derivative is $1/3$, whence the Gaussian curvature is $-1$.


text:
Q: Java If statement that can change String I'm making an app where a user can pick a city in a giving area, and this brings up a listview of events in that given area. I'm using this video guide as a way to help me https://www.youtube.com/watch?v=zjHYyAJQ7Vw&index=21&list=PL2F07DBCDCC01493A  . Unlike the person in the video, I need to have my list say one thing, and the results say another. I'm having trouble finding a way to change my String before it gets to the try statement. For example, I want to change "City history" to "beachcity" (so it takes them to this page), "Fort Macon" to "fortmacon", and so on. That away the user sees something they can understand.
Is there a way to do this? At worst, is there a way to change this with some if statement? Below is the JAVA code
public class Alantic extends ListActivity{
String classes[] = { "City history", "Fort Macon", "example2", "example3", "example4", "example5", "example6"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(Alantic.this, android.R.layout.simple_list_item_1, classes));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    String abc = classes[position];
    try{
    Class ourClass = Class.forName("com.techreviewsandhelp.carteretcountyhistoryguide." + abc);
    Intent ourIntent = new Intent("Alantic.this, ourClass");
    startActivity(ourIntent);
    }catch (ClassNotFoundException e){
        e.printStackTrace();
    }
}

How this code should work is items within String classes shows up in a list (which it does)> user clicks item on list> item goes to String abc> (I need something to convert the item to something else. City history needs to be BEACHCITY, Fort Macon needs to be FORTMACON, and so on)> what's converted will go into the Class ourClass line? this looks for the same "com.tech...." within the manifest action list> this starts another Java file that matches up with the action name> this starts the layout and any functions (buttons and what not) that I want.
I don't think I can use spaces in action names, but giving I can. I would still need the name to change, because I have to do this exact same thing in multiple cities. This means I have to reuse City history, cemeteries, and several other things as a list item for each city.
Below is my code from the manifest.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.techreviewsandhelp.com.carteretcountyhistoryguide"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:screenOrientation='portrait' >
    <activity
        android:name=".Splash"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.techreviewsandhelp.com.carteretcountyhistoryguide.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.techreviewsandhelp.carteretcountyhistoryguide.MAINACTIVITY" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

     <activity
        android:name=".Alantic"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.techreviewsandhelp.carteretcountyhistoryguide.Alantic" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

     <activity
        android:name=".Beachcity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.techreviewsandhelp.carteretcountyhistoryguide.BEACHCITY" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
<activity
        android:name=".FortMacon"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.techreviewsandhelp.carteretcountyhistoryguide.FORTMACON" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

I tested out the actions, and they  work fine.

A: For instance have two arrays - one with the display names and one with the names to send. Or use a HashMap, but that is probably overkill.
As such:
public class Alantic extends ListActivity{
String displayClasses[] = { "City history", "Fort Macon", "example2", "example3", "example4", "example5", "example6"};
String classes[] = { "BEACHCITY", "FORTMACON", "example2", "example3", "example4", "example5", "example6"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(Alantic.this, android.R.layout.simple_list_item_1, displayClasses));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    String abc = classes[position];
    try{
       Class ourClass = Class.forName("com.techreviewsandhelp.carteretcountyhistoryguide." + abc);
       Intent ourIntent = new Intent("Alantic.this, ourClass");
       startActivity(ourIntent);
    }catch (ClassNotFoundException e){
        e.printStackTrace();
    }
}

Another option is to create a custom (Array) Adapter and use a custom data class containing both names.

A:     @Override
   protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setListAdapter(new ArrayAdapter<String>(Alantic.this,  android.R.layout.simple_list_item_1,     displayClasses));

   Hashmap hm = new HashMap<String, String>;
    hm.put("City History","BEACHCITY");// add your items

   }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
   super.onListItemClick(l, v, position, id);
    HashMap hasmap = new HashMap
    String abc = classes[position ];// this becomes your key
    String newString = hm.get(abc);
    try{
   Class ourClass = Class.forName("com.techreviewsandhelp.carteretcountyhistoryguide." +       newString);
   Intent ourIntent = new Intent("Alantic.this, ourClass");
   startActivity(ourIntent);
   }catch (ClassNotFoundException e){
    e.printStackTrace();
   }
  }


text:
Q: Can anyone suggest a Java or Scala DOS/terminal-based UI framework? I'm looking for some framework to build an interface like Turbo C.

A: Six years later, you can consider (for Scala 2.12+) Tenchi2xh/Scurses
Scurses and Onions are frameworks for drawing nice things in your terminal using simple, elegant Scala. Scurses provides a low-level drawing and event handling API while Onions provides a high-level UI API with useful widgets.

A: How about a Text User Interface peer for the AWT: http://www.bmsi.com/tuipeer/
Other TUI libraries include JavaTUI and CHARVA
CHARVA is probably your best bet.

A: Take a look at JavaCurses library.


text:
Q: Is my proof for any finite-dimensional vector space being isomorphic to its double dual correct? Learning about dual vector spaces I began thinking about how the product of a row vector and a column vector acts like a dot product and that furthermore, the row vector is almost acting like a functional that takes in the column vector and outputs a real number. This made me think of the following way to prove that all vector spaces are isomorphic to their double dual:
First, recall that the set of all column vectors with $n$ entries forms a $n$-dimensional vector space. Furthermore, every vector space of dimension $n$ is isomorphic to the vector space of column vectors with $n$ entries, $\mathscr C_n$. This can be shown through a simple change in basis. Therefore to show that any finite-dimensional vector space $V \cong V^{**}$, it suffices to show that $\mathscr C_n \cong \mathscr C_n^{**}$.
Consider the map $\phi : \mathscr C_n \rightarrow \mathscr C_n^*$ defined such that
$$\forall \mathbf v,\mathbf x \in \mathscr C_n : \phi(\mathbf v)(\mathbf x) = \mathbf v^T\mathbf x$$
If we can show that this map is (1) one-to-one, (2) onto, and (3) linear, then it follows that the image of any basis in $\mathscr C_n$ under $\phi$ is a basis of $\mathscr C^*$ and so $\phi$ is an isomorphism.
Denote the vector space of all row vectors with n entries as $\mathscr R_n$. Then
$$\forall \mathbf f \in \mathscr R_n : \exists! \mathbf v \in \mathscr C_n : \mathbf f = \mathbf v^T \implies \forall  \omega \in \mathscr C_n^* : \exists! \mathbf v \in \mathscr C_n : \phi(\mathbf v) = \omega$$
So $\phi$ is (1) one-to-one and (2) onto.
Let $\mathbb F$ denote the underlying field for $\mathscr C_n, \mathscr R_n,$ and consequently $\mathscr C^*$. Now, note that $\forall \mathbf v,\mathbf w,\mathbf x \in \mathscr C_n, c \in \mathbb F:$
$$\phi(c\mathbf v)(\mathbf x) = (c\mathbf v)^T\mathbf x = c(\mathbf v^T\mathbf x) = c\phi(\mathbf v)(\mathbf x)\\\phi(\mathbf v+\mathbf w)(\mathbf x)=(\mathbf v+\mathbf w)^T\mathbf x=(\mathbf v^T+\mathbf w^T)\mathbf x=\mathbf v^T\mathbf x+\mathbf w^T\mathbf x=\phi(\mathbf v)(\mathbf x)+\phi(\mathbf w)(\mathbf x)$$
And so $\phi$ is (3) linear. Therefore $\phi$ is an isomorphism and so $\mathscr C_n \cong \mathscr C_n^* \implies \mathscr C_n^* \cong \mathscr C_n^{**}$, which implies that any finite-dimensional vector space $V$ is isomorphic to $V^{**}$.
I know of the much simpler canonical isomorphism between $V$ and $V^{**}$, I just want to test my knowledge and see if this proof is also valid. Any feedback would be appreciated!


text:
Q: Are there interesting maps between groups preserving non-equality that are not homomorphisms? A homomorphism is generally defined as a map that preserves equality. That is, for groups $G,H$, a map $\phi : G \to H$ is a homomorphism if $ab=c \implies \phi(a)\phi(b) = \phi(c)$. Is there a notion of a map $\rho : G \to H$ such that $ab\neq c \implies \rho(a)\rho(b) \neq \rho(c)$? Are there examples apart from injections? That is, a map $\phi$ that preserves non-equality but not equality? That is, for some $a,b,c \in G$, we have $ab = c$, but $\rho(a)\rho(b) \neq \rho(c)$?

A: There are plenty of examples of such maps that are not homomorphisms.  For instance, you could let $h\in H$ be any non-identity element, and define $\rho(a)=h$ for all $a\in G$.  Or, for $G=H=(\mathbb{Z},{+})$, you could define $\rho(n)=3^{|n|}$.  (Both of these examples in fact have the even stronger property that $\rho(c)\neq \rho(a)\rho(b)$ for all $a,b,c\in G$.)  There are many other possibilities.  It seems unlikely that you can say very much about the structure of such maps in general.


text:
Q: canActivate does not get called the 2nd time when inner observable emits another value I am using combineLatest(which combines the values from all the Observables passed as arguments) in the canActivate method.
My understanding is that, whenever any one of the observables fires, the canActivate observable needs to fire. But that is not happening
In my AuthorizationGuard, I have the following canActivate method -
public canActivate(route: Route): Observable<boolean> {
    return combineLatest(this.service1.checkRoles(route.routeConfig.data.roles),
                         this.service2.serviceLoadedSub).pipe(
                         map(([isAuthorized, permissions]) => {

        console.log('permission in auth guard');
        console.log(permissionSet);

        // some auth checks
        return isAuthorized;
}

service1 checkRoles-
public checkRoles(roles: string[]): Observable<boolean> {
    return this.existingRoles.pipe(
      map(roleMap => {
         // perform some checks

         return true;

      })
    );
  }

service 2 -
export class Service2 {
     public serviceLoadedSub: BehaviorSubject<Set<string>> = new BehaviorSubject<Set<string>>(null);

     constructor (private restService: RestService) {
          this.resService.get('url-info').subscribe(data => {

               serviceLoadedSub.next(new Set(data));
          }
      }
}

So, when service 2 load completes...the behavior subject is fired again.
But for some reason, the observable in canActiavte does not get fired.
Any idea why?


text:
Q: having trouble in getting all the P tags of page
the article passages are divided into different divs tags
like in the image you can see it is written data-page-number="2"
just like that the data is divided into 8 different divs and the problem is that divs are further into div and then there is a pre tag
when I write the code
from bs4 import BeautifulSoup
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0',
}
link="https://www.wattpad.com/1163185219-the-amazing-charlie-wade-volume-2-chapter-2001"
url=f"{link}"
r=requests.get(url,headers=headers)
soup=BeautifulSoup(r.content,'html.parser')
#print(soup.prettify()
div=soup.find("div",{"id":"sp1163185219-pg1"})
print(div.get_text())

output is
Mrs. Willson had never been so happy to shake her whole body to eat.
 According to the foreman, she had been busy at the grocery store, and at seven in the afternoon, she finally received the food coupon she was thinking of.
Although she had already had a full meal at noon, Ms. Willson still looked like a starving dog that had been confined for three days with this meal in the mess hall. He had a big belly and couldn't stand up.
 I could no longer eat. He rested on the canteen seat for half an hour before reluctantly getting up with his hands on the table.
After eating and drinking, the whole person has energy.
  Mrs. Willson wiped her mouth with the back of her hand and touched her belly with the palm of her hand, feeling self-satisfied: "Unexpectedly, eating after this delivery is so delicious! Today I had enough to eat! "
Immediately, he looked at the time and realized that it was already past eight, so he planned to go home quickly.
 Although he has always been selfish, after living through all the hardships and hardships during this period, he has more or less cared for his children and grandchildren.
 Thinking of her son and grandson still lying in bed waiting to be fed, Mrs. Willson rushed to the cafeteria window and asked the staff member who was about to get off work, "Excuse me, do you still need these leftovers, steamed buns and rice? "
The other person looked at her and said helplessly, "Didn't you, old lady, have you eaten three people's food alone and haven't eaten enough?"
 s. Willson wiped her mouth in embarrassment and said with a smile, "Hey, I'm full and the kids in the family are still hungry. You know, they haven't eaten anything for almost two days and two nights. "
the other party asked in surprise, "Really? When is there someone who still cannot eat? "
Ms. Willson had a hot face and said sheepishly, "Hey, something happened to my family during this period of time. The oldest daughter-in-law in the family has breast cancer. It is in an advanced stage. The ball is about to die, my eldest son spent all the money at home to cure his illness ... "
 With that said, Ms. Willson suddenly felt very refreshed in her heart.
It's pretty cool!
had been a long time since I had seen Horiyah that my eyes did not like him. If Regnar hadn't stopped her, she would have wanted to beat Horiyah to death herself.
Especially recently, Horiyah has disobeyed her in various ways and even forced her to work. She has long hated her for this in her heart.
 Therefore, in front of the others, manufacturing the rumor that Horiyah was dying of breast cancer made her feel the pleasure of revenge.
When the cafeteria staff heard this, they suddenly exclaimed, "Huh? Advanced breast cancer, that would be too miserable ... "
"That's not a big deal!" Mrs. Willson sighed, "Hey ... My oldest daughter-in-law has advanced breast cancer and my second daughter-in-law is even more miserable!"
he staff member hurriedly asked, "Ma'am, what happened to your second daughter-in-law?"
Ms Willson said regretfully: "The second daughter-in-law has uremia and is on dialysis all day. However, on the way to the hospital for her dialysis some time ago, she was hit by a car, and her limbs were amputated under her $ s... "
he staff were scared and dumbfounded: "Isn't this ... so miserable?"
 Mrs. Willson said with a face, "What is this? The worst is yet to come!

either here is a whole next passage after this
I get partial result
and when i change
div=soup.find("div",{"id":"sp1163185219-pg1"}) to div=soup.find("div",{"id":"sp1163185219-pg2"})
and re run the code it fails.
here is the link to the website =https://www.wattpad.com/1163185219-the-amazing-charlie-wade-volume-2-chapter-2001
it would be great help if i am able to complete this
thank you in advance for your help

A: Data is also generating from API
import requests

api_url = 'https://www.wattpad.com/api/v3/stories/293954234/recommended?limit=7&fields=id%2Ctitle%2CvoteCount%2CreadCount%2CcreateDate%2ClastPublishedPart%2Cuser(name%2Cavatar)%2Ccover%2Curl%2CnumParts%2CisPaywalled%2Ccompleted%2Cmature%2Cdescription'
headers={
    "content-type": "application/json",
    "x-requested-with": "XMLHttpRequest",
    'User-Agent': 'Mozilla/5.0'
}
req =requests.get(api_url,headers=headers).json()
#print(req)

for para in req:
    txt=para['description']
    print(txt)

OR
The endpoint of the url chapter-2001 contains 10 pages
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0'}
url="https://www.wattpad.com/1163185219-the-amazing-charlie-wade-volume-2-chapter-2001/page/{page}"
for page in range(1,11):
    r=requests.get(url.format(page=page),headers=headers)
    soup=BeautifulSoup(r.content,'html.parser')
    #print(soup.prettify()
    div=soup.find("div",{"id":"sp1163185219-pg1"})
    print(div.get_text(strip=True).replace('Chapter 2001',''))

A: Try matching with a regex, then finding children p tags.
import re

soup = BeautifulSoup(r.content,'html.parser')
divs = soup.findAll("div",{"id": re.compile(r"sp1163185219-pg\d+")})
for div in divs:
    p_tags = div.findAll("p")
    for p in p_tags:
        print(p.get_text())

Output:
Chapter 2001
Mrs. Willson had never been so happy to shake her whole body to eat.
According to the foreman, she had been busy at the grocery store, and at seven in the afternoon, she finally received the food coupon she was thinking of.
Although she had already had a full meal at noon, Ms. Willson still looked like a starving dog that had been confined for three days with this meal in the mess hall. He had a big belly and couldn't stand up.
I could no longer eat. He rested on the canteen seat for half an hour before reluctantly getting up with his hands on the table.
After eating and drinking, the whole person has energy.
Mrs. Willson wiped her mouth with the back of her hand and touched her belly with the palm of her hand, feeling self-satisfied: "Unexpectedly, eating after this delivery is so delicious! Today I had enough to eat! "
Immediately, he looked at the time and realized that it was already past eight, so he planned to go home quickly.
Although he has always been selfish, after living through all the hardships and hardships during this period, he has more or less cared for his children and grandchildren.
Thinking of her son and grandson still lying in bed waiting to be fed, Mrs. Willson rushed to the cafeteria window and asked the staff member who was about to get off work, "Excuse me, do you still need these leftovers, steamed buns and rice? "
The other person looked at her and said helplessly, "Didn't you, old lady, have you eaten three people's food alone and haven't eaten enough?"
Ms. Willson wiped her mouth in embarrassment and said with a smile, "Hey, I'm full and the kids in the family are still hungry. You know, they haven't eaten anything for almost two days and two nights. "
The other party asked in surprise, "Really? When is there someone who still cannot eat? "
Ms. Willson had a hot face and said sheepishly, "Hey, something happened to my family during this period of time. The oldest daughter-in-law in the family has breast cancer. It is in an advanced stage. The ball is about to die, my eldest son spent all the money at home to cure his illness ... "
With that said, Ms. Willson suddenly felt very refreshed in her heart.
It's pretty cool!
It had been a long time since I had seen Horiyah that my eyes did not like him. If Regnar hadn't stopped her, she would have wanted to beat Horiyah to death herself.
Especially recently, Horiyah has disobeyed her in various ways and even forced her to work. She has long hated her for this in her heart.
Therefore, in front of the others, manufacturing the rumor that Horiyah was dying of breast cancer made her feel the pleasure of revenge.
When the cafeteria staff heard this, they suddenly exclaimed, "Huh? Advanced breast cancer, that would be too miserable ... "
"That's not a big deal!" Mrs. Willson sighed, "Hey ... My oldest daughter-in-law has advanced breast cancer and my second daughter-in-law is even more miserable!"
The staff member hurriedly asked, "Ma'am, what happened to your second daughter-in-law?"
Ms Willson said regretfully: "The second daughter-in-law has uremia and is on dialysis all day. However, on the way to the hospital for her dialysis some time ago, she was hit by a car, and her limbs were amputated under her $ s... "
The staff were scared and dumbfounded: "Isn't this ... so miserable?"
Mrs. Willson said with a face, "What is this? The worst is yet to come! "


text:
Q: Поместить элемент в div bottom:0 Подскажите пожалуйста, как поместить текст прижать его к низу div

Нжиний текст

A: Еще как вариант с абсолютным позиционированием внутри элемента с относительным:

.external {
  width: 200px;
  height:200px;
  border:1px solid;

  position: relative;
}

.internal {
  position: absolute;
  bottom: 0;
}

    Нжиний текст

A: Вот примерно так

.text{
    display: table-cell;
    vertical-align: bottom;
width:200px;height:200px;border:1px solid;}

.text1 {
    display: flex;
    align-items: flex-end;
    width:200px;height:200px;border:1px solid;
}

Нжиний текст

Нжиний текст


text:
Q: My Sharepoint styled header text is breaking words in order to wrap lines. How can I prevent this? I would like the text to break only on whitespace, as is normally expected. Here is the css that Sharepoint generated for the line:

A: Look through the entire css for word-break and word-wrap

A: The word-wrap and word-break styles were set correctly. I ended up fixing the issue by changing the  tag to a
.


text:
Q: Create Inputs Dynamically in react native I want to create inputs dynamically in react native, for example if value is 3 , it should create three input components , if value is 2 it should have 2 inputs.
Please check my code below
const [myloop, setMyloop] = React.useState([]);

const renderButtons = (data) => {
  for (let i = 0; i < data; i++) {
    myloop.push(
      <Input
        placeholder="Name"
      />
    );
  }
};
renderButtons(2);

In my main function i have slider , which if i set some value i need to create that number of inputs..
return (
  <View>
    <Slider
      minValue={1}
      maxValue={4}
      onChange={(v) => {
        renderButtons(Math.floor(v));
      }}
    </Slider>
    {myloop}
  </View>
)

here the problem is its creating lots of inputs dynamically , How do i create dynamic inputs properly.
Also when i try to reset the array using
setMyloop([]);
i get following error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

A: const [size, setSize] = useState(0);

return (
  <View>
    <Slider
      minValue={1}
      maxValue={4}
      onChange={(v) => setSize(v)}>
    </Slider>
   {renderButtons(size)}
  </View>
);

Then
const renderButtons = (size) => {
  <>
  {for (let i = 0; i < size; i++) {
    <Input
      placeholder="Name"
    />
  }}
  </>
};

A: One of the solution you can use is by using the map function inside your JSX:
For a Reactjs application, you can use the following code:
import { useEffect, useState } from "react";

const DEFAULT_VALUE = 0;

export default function App() {
  const [inputNumber, setInputNumber] = useState(DEFAULT_VALUE);
  const [inputArray, setInputArray] = useState(new Array(1).fill(0));

  useEffect(() => {
    setInputArray(new Array(parseInt(inputNumber)).fill(1));
  }, [inputNumber]);

  return (
    <div>
      <input
        type="range"
        min="0"
        max="100"
        value={inputNumber}
        onChange={(v) => setInputNumber(v.target.value)}
      />
      {inputArray.map((each, index) => (
        <input
          key={index}
          type="text"
          value={"INPUT NUMBER " + index}
          onChange={() => {
            console.log(index);
          }}
        />
      ))}
    </div>
  );
}

For your React Native application, replace the following components:

*

*div -> View

*input (type="range") -> Slider

*Depending of what is returning the Slider you can replace
v.target.value by v as you previously write in your code

*The parseInt() is maybe not necessary for your Slider component


text:
Q: How to use "Always Move Messages in This Conversation" feature from VBA in MS Outlook? I'm trying to implement a search and move feature in MS Outlook. Search is OK, it works like charm. But, I can find only the Move function to move message into an Outlook folder.
I use the Always Move Messages in This Conversation feature manually. Now, I'd like to use it from macro. Is there any way to use this feature from VBA?
Here is the current implementation but it uses the simple Move feature:
Private Sub btn_Click()
    Dim currentMail As Object
    Dim F As Outlook.MAPIFolder
    Dim Msg$
    Set currentMail = Application.ActiveWindow
    If TypeOf currentMail Is Outlook.Inspector Then
      Set currentMail = obj.CurrentItem
    Else
      Set currentMail = obj.Selection(1)
    End If

    currentMail.Move Folder
End Sub

A: Not sure if this is what your asking but here is how to move outlook messages in some conversations to sub-folder.
Update SubFolder = Inbox.Folders("Temp") Temp folder
Code will search all messages in same conversation in your outlook and then move it to Temp folder
Option Explicit
Sub MoveConv()
    Dim olNs As NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim SubFolder As Outlook.MAPIFolder
    Dim SelectedItem As Object
    Dim Item As Outlook.MailItem ' Mail Item
    Dim Folder As Outlook.MAPIFolder ' Current Item's Folder
    Dim Conversation As Outlook.Conversation ' Get the conversation
    Dim ItemsTable As Outlook.Table ' Conversation table object
    Dim MailItem As Object

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)

'    On Error GoTo MsgErr
'   // Must Selected Item.
    Set SelectedItem = Application.ActiveExplorer.Selection.Item(1)

'   // If Item = a MailItem.
    If TypeOf SelectedItem Is Outlook.MailItem Then
        Set Item = SelectedItem
        Set Conversation = Item.GetConversation

        If Not IsNull(Conversation) Then
            Set ItemsTable = Conversation.GetTable

            For Each MailItem In Conversation.GetRootItems ' Items in the conversation.
                If TypeOf MailItem Is Outlook.MailItem Then
                    Set Item = MailItem
                    Set Folder = Item.Parent
                    Set SubFolder = Inbox.Folders("Temp") ' Move to Temp Folder
                    Debug.Print Item.ConversationID & " In Folder " & Folder.Name
                    GetConv Item, Conversation
                    Item.Move SubFolder
                End If
            Next
        End If
    End If

MsgErr_Exit:
    Set olNs = Nothing
    Set Inbox = Nothing
    Set Item = Nothing
    Set SelectedItem = Nothing
    Set MailItem = Nothing
    Exit Sub

'// Error information
MsgErr:
    MsgBox "Err." _
         & vbCrLf & "Error Number: " & Err.Number _
         & vbCrLf & "Error Description: " & Err.Description _
         , vbCritical, "Error!"
    Resume MsgErr_Exit
End Sub

Function GetConv(Item As Object, Conversation As Outlook.Conversation)
    Dim Items As Outlook.SimpleItems
    Dim MailItem As Object
    Dim Folder As Outlook.Folder
    Dim olNs As NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim SubFolder As Outlook.MAPIFolder

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Conversation.GetChildren(Item)

    If Items.Count > 0 Then
        For Each MailItem In Items
            If TypeOf MailItem Is Outlook.MailItem Then
                Set Item = MailItem
                Set Folder = Item.Parent
                Set SubFolder = Inbox.Folders("Temp")
                Debug.Print Item.ConversationID & " In Folder " & Folder.Name
                Item.Move SubFolder
            End If
            GetConv Item, Conversation
        Next
    End If
End Function

A: This is what you want
Dim currentMail As MailItem
Dim conv As Conversation
Dim myFolder As Folder 'you have to set it to your target folder

Set conv = currentMail.GetConversation
conv.SetAlwaysMoveToFolder myFolder, myFolder.Store


text:
Q: How to Connect to Hive via pyhive from Windows I've been racking my brain for the past couple of days attempting to connect to a Hive server with a Python client using pyhive on Windows. I'm new to Hive (pyhive too for that matter), but am a reasonably experienced Python dev. Invariably I get the following error:
(pyhive-test) C:\dev\sandbox\pyhive-test>python test.py
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    conn = hive.Connection(host='192.168.1.196', port='10000', database='default', auth='NONE')
  File "C:\Users\harnerd\Anaconda3\envs\pyhive-test\lib\site-packages\pyhive\hive.py", line 192, in __init__
    self._transport.open()
  File "C:\Users\harnerd\Anaconda3\envs\pyhive-test\lib\site-packages\thrift_sasl\__init__.py", line 84, in open
    raise TTransportException(type=TTransportException.NOT_OPEN,
thrift.transport.TTransport.TTransportException: Could not start SASL: b'Error in sasl_client_start (-4) SASL(-4): no mechanism available: Unable to find a callback: 2'

when executing the following script:
from pyhive import hive

conn = hive.Connection(host='192.168.1.196', port='10000', database='default', auth='NONE')
cur = conn.cursor()
cur.execute('show tables')
data = cur.fetchall()
print(data)

The HiveServer2 instance is an out-of-the-box HDP Sandbox VM from Cloudera with HiveServer2 Authentication set to 'None'.
Client is an Anaconda virtual environment on Windows 10 with Python 3.8.5 and the following packages installed by conda:

*

*pyhive 0.6.1

*sasl 0.2.1

*thrift 0.13.0

*thrift-sasl 0.4.2

Right now I'm merely trying to connect to Hive with the script above, but ultimately I intend to use pyhive within SQLAlchemy in a Flask application. In other words: Flask -> Flask-SQLAlchemy -> SQLAlchemy -> pyhive. In production the Flask app will be hosted by Cloudera Data Science Workbench (i.e. some flavor of Linux), but will be developed (and therefore must also run) on Windows systems.
Of course I've looked at the many questions here, on Cloudera's site, and GitHub relating to Hive connection problems and if someone put a gun to my head I would have to say that trying this from a Windows client may be part of the problem as that doesn't seem to be a very common thing to do.
No mechanism available

What does that error even mean? It sure would be nice if there was some documentation on how to configure and use SASL from python - if there is I would like to know about it.
FWIW, the line causing the error is in thrift_sasl/__init__.py:
ret, chosen_mech, initial_response = self.sasl.start(self.mechanism)

self.mechanism is 'PLAIN'; chosen_mech and initial_response are empty strings (''). ret is False, which causes the exception to be thrown.
I know I'm not the only guy trying to connect to Hive with pyhive on Windows - this guy (SASL error when trying to connect to hive(hue) by python from my PC - Windows10) was, but his 'solution' - install Ubuntu as a VM on his Windows box - isn't going to work for me.

A: Long story short, the answer to this problem is that PyHive simply is not supported on Windows. This is due to the fact that PyHive uses the sasl library for Hive connections and sasl is not only difficult to compile from source on Windows but it seems that it simply may not work on Windows.
The key is providing your own thrift_transport instead of relying on PyHive to create it. Devin Stevenson has provided an alternative transport (https://github.com/devinstevenson/pure-transport) that works well on Windows and should work on other OSes (I haven't tested this, however). His repo provides examples using pure transport directly with Hive as well as with SQLAlchemy.
In my use case I am using it with Flask-SQLAlchemy within a Flask application. The way I inject the thrift transport is like this:
from flask_sqlalchemy import SQLAlchemy
import puretransport

thrift_transport = puretransport.transport_factory(host='127.0.0.1',
                                                   port=10000,
                                                   username='a_user',
                                                   password='a_password')

class MySQLAlchemy(SQLAlchemy):
    '''
    Subclassing the standard SQLAlchemy class so we can inject our own thrift
    transport which is needed to get pyhive to work on Windows
    '''
    def apply_driver_hacks(self, app, sa_url, options):
        '''
        If the current driver is for Hive, add our thrift transport
        '''
        if sa_url.drivername.startswith('hive'):
            if 'connect_args' not in options:
                options['connect_args'] = {'thrift_transport': thrift_transport}
        return super(MySQLAlchemy, self).apply_driver_hacks(app, sa_url, options)

# later, in models.py...
db = MySQLAlchemy()

class AModelClass(db.Model):
    __tablename__ = 'some_table'
    id = db.Column(db.Integer, primary_key=True)
    # etc...

In my case the URL I use for my Hive connection is simply of the form hive:///{database_name}, i.e.: hive:///customers, because all the necessary information is passed using the thrift transport. One caveat though - when injecting a thrift transport, PyHive asserts that host, port, auth, kerberos_service_name, and password cannot have any value other than None. Unfortunately SQLAlchemy assigns the default Hive port of 10000 to port if no port number is provided. The solution is to replace the HiveDialect.create_connect_args method, as shown here: https://github.com/devinstevenson/pure-transport/issues/7. Simply subclassing the HiveDialect class will not work here, as the name HiveDialect is in SQLAlchemy's dialect registry and can't simply be replaced.


text:
Q: Wanderers of Time & Next of Kin Cover artist I was looking through Amazon for a new science fiction to purchase. I came across the book Wanderers of Time by John Wyndham and noticed the cover art looked rather familiar.
So I went to my book collection and found Next of Kin by Eric Frank Russell. The cover-art's space ships had so many similarities they had to be by the same artist.
I looked at both of publications of the books according to its book publisher's publish date and found even more evidence to help back up that the artists are the same. Wanderers of Time copy was published in 1973 (under Coronet science fiction) and Next of Kin was in 1973 (under Sphere Books). Same year interesting eh?
Well I was wondering if anyone knew any information about the artists of these cover arts or can varify that they are the same artists.

A: I'm thinking that it's probably Chris Foss
he pretty much did most of the covers on Sci-Fi books in the 70s and 80s.
I've actually got the Wyndham book at home, will verify the artist (usualy credited in small print on the back cover in those days)

A: I actually contacted Chris and his daughter so kindly verified it is his art. So she posted Next of Kin on his site for me. They are in the process of finding a Hi-Res version for Wanderers of time.
For any fan-boy's out there of Chris Foss, here are the direct quotes from his daughter (which can also be found on facebook).

Hello John, thanks for the question and even better for answering it!
  I'll have a look and see if we have a good copy of that cover and
  upload it to the site if we do - but it does ring a bell. I'm slowly
  uploading book covers and artwork when I get the time. A twitter link
  will appear here once it's on the site. Do post a comment on
  ChrisFossArt.com or here if there are any other book covers you'd like
  to see. All best, Imogene (Chris' daughter).

A: It's Chris Foss, no question. If you zoom in, you see Foss's signature logo, an F in a shield. It's at bottom right of the "Wanderers" and bottom left of the "Next of Kin"


text:
Q: Using SELECT CASE WHEN in PostgreSQL to select the smallest polygon, produced from a split Like the example from the PostGIS refractions.
The query splits a circle with a line. The results are two polygons. Additionally it selects the distinct polygons (n) and calculates the area of each object.
WITH split AS
(SELECT
    ST_Split(circle, line) AS geom,
    generate_series(1,100) AS n
FROM (
    SELECT
        ST_MakeLine(ST_MakePoint(10, 10),ST_MakePoint(190, 190)) AS line,
        ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50) AS circle) AS foo),
objects AS
(SELECT
    n,
    ST_GeometryN(split.geom,n) AS geom
FROM split
    WHERE n <= ST_NumGeometries(split.geom))

    SELECT
        n,
        ST_Area(objects.geom),
        geom
    FROM objects

The query returns two objects with different area values.
My question is how I can select the smallest one?
The problem is that in some cases the n=1 geometry is the smaller one and for another polygon the n=2 geometry is the smaller one.
I tried this in my final query but it doesn't work. It returns no geometry.
CASE
    WHEN ST_Area(ST_GeometryN(objects.geom,1)) < ST_Area(ST_GeometryN(objects.geom,2))
        THEN ST_GeometryN(objects.geom,1)
    ELSE ST_GeometryN(objects.geom,2)
END

What I want is the smaller polygon after the split.
I thought the CASE WHEN clause could help here. So, it is more a PostgreSQL issue.

A: Keeping me busy with this issue I found the LEAST and GREATEST functions in the PostgreSQL documentation.
The following final query (after the subqueries in my question) works, even if this approach is maybe not the most elegant one.
The clue is ordering the results with the LEAST value of the area.
...

SELECT
    objects.n,
    -- objects.geom,
    ST_Area(objects.geom) AS area
FROM objects, split
    WHERE split.n <= ST_NumGeometries(split.geom)
        ORDER BY LEAST(ST_Area(ST_GeometryN(objects.geom,split.n)))
        -- LIMIT 1

The result set for this is:
 n |       area
---+------------------
 2 | 3199.62422930388
 1 | 4603.98865134125
 1 | 4603.98865134125
 2 | 3199.62422930388
(4 rows)

When I limit this query by 1 and include the geometry column (both commented out in the query above), I have always selected the smallest piece from the split.
Is there a way to avoid the limiting?


text:
Q: How to make rotate log file for every date, in Java. linux Look in the following code:
**FileHandler txtLog = new FileHandler("log/server-%u%g.log", 0, 1, true);**

 txtLog.setFormatter(new SimpleTextFormatter());
            BasicServerConfig config = qs.getBasicConfig();
            log.fine("Getting the log level.. from server.xml, after loading Quick Server...");
            txtLog.setLevel(Level.parse(config.getConsoleLoggingLevel()));
            log.setLevel(Level.parse(config.getConsoleLoggingLevel()));
            log.addHandler(txtLog);
            qs.setAppLogger(log);

I want that this file should be created with each new date (with out time).

A: From the Linux perspective, the general way would be to use logrotate to rotate the logs.  Then have you program handle the HUP signal to reopen the new logs and set up lograte to send that signal to program.
If you want to do this all within Java, then you should go ask on stackoverflow.com .


text:
Q: Is $X_{0}$ a subset of $X_{0}\sqcup X_{1}$? Since the disjoint union of $X_{0}= \{x_{1}, x_{2}, x_{3}\}$ and $X_{1}= \{x_{1}, x_{2}\}$ is: $ X_{0}\sqcup X_{1}= \{(x_{1},0), (x_{2},0), (x_{3},0), (x_{1},1), (x_{2},1)\}$ I have to ask; is $X_{0}$ a subset of $X_{0}\sqcup X_{1}$? I just would like to know because I can't tell if there ought to be an inclusion function.
The inclusion function is the identity map $id: x \mapsto x$ but the elements of the disjoint union are indexed...

A: No, formally $X_0$ is not a subset of $X_0\sqcup X_1$. But there is a natural injective function
$$i:X_0\to X_0\sqcup X_1$$
$$i(x)=(x,0)$$
and therefore many authors will treat $X_0$ as a subset of $X_0\sqcup X_1$ via the embedding above, i.e. they will replace $X_0$ with the image $i(X_0)$. This is so natural that most authors will completely forget about indexing.


text:
Q: Head(int main) not being updated after reversing the linked list I have the following code
node* reverse_ll_recr(node* head)
{
if(head->next == NULL) return head;
reverse_ll_recr(head->next);
head->next->next = head;
head->next = NULL;
}

And in main i call it with
head = reverse_ll_recr(head);

Problem is that head is not updated and would only print the last element since it is pointing to NULL after reversal. Does anyone know why this is happening?


text:
Q: Installing wordcloud package for python error pip install wordcloud

This gives me the error "Can't find vcvarsall.bat".
I also tried to install the whl version but everyone I tried gave me the error "not a supported whl on this platform".
Let me know if I need to explain something better.

A: You need to install:
https://www.microsoft.com/en-us/download/details.aspx?id=44266
Then pip should work fine!


text:
Q: Cannot detect SDK path in WebStorm 2016.3 I am trying to create a PhoneGap application using WebStorm 2016.3 IDE.
I am following this link link. I am able to create a project from the steps but while running the app I'm getting errors. While setting emulator I've found that Android SDK was not found.
I am unable to find how can I set that path here and the error I got is:

...and in log cat
"C:\Program Files (x86)\JetBrains\WebStorm 2016.3\bin\runnerw.exe" "C:\Users\Sa E\AppData\Roaming\npm\ionic.cmd" run --emulator android
✗ You cannot run iOS unless you are on Mac OSX.

I've tried some things by google but the data is for old IDE and I can't see such options with my current IDE.

A: I ran into the same issues on Windows. I added a system variable ANDROID_HOME with the address of the sdk folder. In my case it was
c:\Users\Andrew\AppData\Local\Android\sdk
After that, I restarted WebStorm, and it works fine.
PS make sure that you set up the project properly. Try creating a new project with type "PhoneGap/Cordova", then in the terminal type the following commands:
ionic start MyProjectName
ionic serve

If everything works at this point, then proceed:
ionic platform add android
ionic build android
ionic emulate android

You can use run instead of emulate if you have GenyMotion installed and running

A: I used @Andrew's answer, but did not manage to make it work. It appears i needed more Environment variables; so, after many searches, I found this link on Cordova documentation which helped me in making PHPstorm recognize the Android SDK. The question was about Webstorm, but the Cordova plugin requires the same environment variables.
Here's a quote from that site (if you do not know how to set environment variables, follow the above link to get help):

Cordova's CLI tools require some environment variables to be set in order to function correctly. The CLI will attempt to set these variables for you, but in certain cases you may need to set them manually. The following variables should be updated:

*

*Set the JAVA_HOME environment variable to the location of your JDK installation

*Set the ANDROID_HOME environment variable to the location of your Android SDK installation

*It is also recommended that you add the Android SDK's tools, tools/bin, and platform-tools directories to your PATH

A: I faced the same problem with intellij idea ultimate on linux, while trying to run a cordova/phone gap project. Weirdly enough, the commands where running normally from the command prompt and the embedded terminal, however, trying to create a run configuration, I got the infamous errors.
I have the environment variables set correctly, but, I have them set in ~/.bashrc which intellijidea seems not t read.
I tried to add the variables manually in the same screenshot you included, with no success. The solution was to add ANDROID_HOME to the /etc/environment, rebooted, and everything worked as expected.


text:
Q: SignalR issue calling server method from client I have an mvc application and have implemented SignarlR.  The purpose of using SignalR is to allow my back-end controller to send updates to the front end client to inform it of it's progress.  The method on the controller could potentially be a long running process.  I have registered 4 different events on the client that can be called from the controller.  All that is working just fine.
So I determined that I wanted to give my user the ability to cancel the long running process if they wanted to.  So I created another method in the Hub that the client could call and that method would set a flag that the back end could check to see if the process was cancelled.
For some reason, I cannot get the server call from the client to work.  It will NOT call the server method.  I have code snippets of each piece below.
HUB Class
public class ScanInventoryHub : Hub
{
    private string _connectionId = string.Empty;
    private bool _scanCancelled = false;

    public bool ScanCancelled
    {
        get
        {
            return _scanCancelled;
        }
    }

    public ScanInventoryHub(string connectionId)
    {
        _connectionId = connectionId;
    }

    public void SendMessage(string message)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ScanInventoryHub>();
        hubContext.Clients.Client(_connectionId).addNewMessage(message);
    }

    public void SetProgressCount (int count)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ScanInventoryHub>();
        hubContext.Clients.Client(_connectionId).setStatusBar(count);
    }

    public void IncrementItemProgressBar()
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ScanInventoryHub>();
        hubContext.Clients.Client(_connectionId).incrementItemProgressBar();
    }

    public void IncrementProgressBar(int percentage)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ScanInventoryHub>();
        hubContext.Clients.Client(_connectionId).incrementProgressBar(percentage);
    }

    public void CancelScan()
    {
        _scanCancelled = true;
        Debug.WriteLine("Cancel Scan");
    }
}

Client Side Script
    messageHubProxy = $.connection.scanInventoryHub;

    messageHubProxy.client.addNewMessage = function (message) {
        //html stuff is happening here
    };

    messageHubProxy.client.setStatusBar = function (count) {
        //html stuff is happening here
    }

    messageHubProxy.client.incrementItemProgressBar = function () {
        //html stuff is happening here
    }

    messageHubProxy.client.incrementProgressBar = function (percentage) {
        //html stuff is happening here
    }

    $.connection.hub.logging = true;

    $.connection.hub.start().done(function () {
        messageHubId = $.connection.hub.id;

        $.ajax({
            url: Utility.GetBaseUrl() + 'Controller/Action',
            type: 'POST',
            data: {
                connectionId: messageHubId,
                .....
            },
        });
    });

Cancel Button Click Event Handler
    CancelScan: function (e) {
        messageHubProxy.server.cancelScan();
    }

SignalR Log of one of my local runs is below
[14:53:44 GMT-0400 (Eastern Daylight Time)] SignalR: Client subscribed to hub 'scaninventoryhub'.

[14:53:44 GMT-0400 (Eastern Daylight Time)] SignalR: Negotiating with '/signalr/negotiate?
clientProtocol=2.1&connectionData=%5B%7B%22name%22%3A%22scaninventoryhub%22%7D%5D'.

[14:53:44 GMT-0400 (Eastern Daylight Time)] SignalR: Negotiating with '/signalr/negotiate?clientProtocol=2.1&connectionData=%5B%7B%22name%22%3A%22scaninventoryhub%22%7D%5D'.

[14:53:45 GMT-0400 (Eastern Daylight Time)] SignalR: webSockets transport starting.

[14:53:45 GMT-0400 (Eastern Daylight Time)] SignalR: Connecting to websocket endpoint 'ws://localhost:5325/signalr/connect?transport=webSockets&clientProtocol=2.1&connectionToken=UtyYkw5kgPhCQH40iaWKHE2SE4SWGq2q3A0EJQ%2FopAsCPr61jfIBD301cBT3iwxZX9%2Fkk4wuh%2BPljBciCFNYtubMUMnlU1MPF2a88tFRKaDQbebT3OrHuTVLEoY4qLzY&connectionData=%5B%7B%22name%22%3A%22scaninventoryhub%22%7D%5D&tid=6'.
SCRIPT12008: WebSocket Error: Incorrect HTTP response. Status code 302, Redirect

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: Websocket closed.

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: Closing the Websocket.

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: webSockets transport failed to connect. Attempting to fall back.

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: serverSentEvents transport starting.

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: This browser doesn't support SSE.

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: serverSentEvents transport failed to connect. Attempting to fall back.

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: foreverFrame transport starting.

[14:53:46 GMT-0400 (Eastern Daylight Time)] SignalR: Binding to iframe's load event.

[14:53:47 GMT-0400 (Eastern Daylight Time)] SignalR: Iframe transport started.

[14:53:47 GMT-0400 (Eastern Daylight Time)] SignalR: foreverFrame transport connected. Initiating start request.

[14:53:48 GMT-0400 (Eastern Daylight Time)] SignalR: The start request succeeded. Transitioning to the connected state.

[14:53:48 GMT-0400 (Eastern Daylight Time)] SignalR: Now monitoring keep alive with a warning timeout of 13333.333333333332, keep alive timeout of 20000 and disconnecting timeout of 30000

[14:53:49 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'setStatusBar' on hub 'ScanInventoryHub'.

[14:53:49 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:53:49 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:53:49 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:53:51 GMT-0400 (Eastern Daylight Time)] SignalR: foreverFrame transport timed out when trying to connect.

[14:53:55 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:53:55 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:53:56 GMT-0400 (Eastern Daylight Time)] SignalR: Invoking scaninventoryhub.CancelScan

[14:53:59 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:53:59 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:54:02 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:02 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:54:05 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:05 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:54:08 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:08 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:54:10 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:12 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:14 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:16 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:18 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:19 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:19 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:54:22 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:26 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:29 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:32 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:35 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:35 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:54:38 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:42 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementProgressBar' on hub 'ScanInventoryHub'.

[14:54:42 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'addNewMessage' on hub 'ScanInventoryHub'.

[14:54:43 GMT-0400 (Eastern Daylight Time)] SignalR: Triggering client hub event 'incrementItemProgressBar' on hub 'ScanInventoryHub'.

[14:54:44 GMT-0400 (Eastern Daylight Time)] SignalR: scaninventoryhub.CancelScan failed to execute. Error: Error: Send failed.

[14:54:44 GMT-0400 (Eastern Daylight Time)] SignalR: Stopping connection.

[14:54:44 GMT-0400 (Eastern Daylight Time)] SignalR: Stopping forever frame.

[14:54:44 GMT-0400 (Eastern Daylight Time)] SignalR: Fired ajax abort async = true.

[14:54:44 GMT-0400 (Eastern Daylight Time)] SignalR: Stopping the monitoring of the keep alive.


text:
Q: SSH port forwarding with reverse proxy I have the following scenario.

*

*At my workplace a Web Application is running on port 5000 and 5001 (with https).

*There is a little V-Server running OpenSSH + IIS (or NGINGX on Linux)

*I want to access that service through a HTTPS connection with specified domain.

*The V-Server should handle all the SSL Certificate stuff. (We use ACME right now)

I know there are services like ngrok that do exactly fit our needs, but we need many connections, which will get too expensive for us.
Connecting to the V-Server via SSH is the easy part. Opening the port forwarding from localhost:5000 to remote:5000 is also easy.
Now there comes the tricky part. Is it possible to configure e.g. the IIS Server to serve an endpoint (http://mypage.com and https://mypage.com), manage the certificate and transfer the incoming request to the localhost:5000 tunnel? Or is there a IIS extensions that does exactly this operation?
Disclaimer
mypage.com is just a placeholder


text:
Q: Compute shader float arithmetic is really inaccurate I am currently writing a compute shader that requires a simple float multiplication of a float and a uint3, and I am getting really inaccurate results.
for example, uint3(1, 2, 3) * 0.25
expected result: uint3(0.25, 0.5, 0.75)
actual result: uint3(0.3, 0.5, 0.8)
Any idea how to increase the precision somehow?
The compute shader:
[numthreads(X_THREADS, Y_THREADS, Z_THREADS)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    // Fill the array
    uint tid = id.x;
    while (tid < octree_length)
    {
        // Normalize tid
        uint depth = OctreeDepth(tid);
        uint mid = tid - depth_offsets[depth];

        // Compute node data
        float node_size = bounds_size / pow(2, depth);
        float3 node_min = MortonToXYZ(mid) * node_size;

        // Build node
        octree[tid].anchor = node_min;
        octree[tid].size = node_size;

        // Move tid
        tid += total_num_threads;
    }
}

The inaccurate multiplication:
float3 node_min = MortonToXYZ(mid) * node_size;

*

*mid: a Morton code for this thread

*MortonToXYZ: returns uint3 with elements between [0, infinity], this is a decoded Morton code

*node_size: a float between [0, infinity]

The code that launches the shader and reads the data back:
ComputeBuffer BuildOctree(Vector3 boundsMin, float boundsSize, int octreeDepth, Vector3Int numThreadGroups)
{
    // Compute constants
    int totalNumThreads = numThreadGroups.x * numThreadGroups.y * numThreadGroups.z * THREADS_PER_GROUPS;

    // Compute depth offsets and octree length
    int[] depthOffsets = new int[octreeDepth];
    int length = 0;

    for (int i = 0; i < octreeDepth; i++)
    {
        depthOffsets[i] = length;
        length += (int) Mathf.Pow(8, i);
    }

    // Prepare buffers
    ComputeBuffer octree = new ComputeBuffer(length, 4 * sizeof(float), ComputeBufferType.Structured);
    ComputeBuffer depthOffsetsGPU = new ComputeBuffer(octreeDepth, sizeof(int), ComputeBufferType.Structured);

    depthOffsetsGPU.SetData(depthOffsets);
    octree.SetData(new OctreeNode[length]);

    // Load data into shader
    OCTREE_BUILDER.SetBuffer(0, "octree", octree);
    OCTREE_BUILDER.SetBuffer(0, "depth_offsets", depthOffsetsGPU);
    OCTREE_BUILDER.SetInt("total_num_threads", totalNumThreads);
    OCTREE_BUILDER.SetInt("octree_length", length);
    OCTREE_BUILDER.SetFloat("bounds_size", boundsSize);

    // Launch kernal
    OCTREE_BUILDER.Dispatch(0, numThreadGroups.x, numThreadGroups.y, numThreadGroups.z);

    OctreeNode[] output = new OctreeNode[length];
    octree.GetData(output);

    for (int i = 0; i < output.Length; i++)
        Debug.Log("cell[" + i + "]: " + output[i].anchor + ", " + output[i].size);

    // Return octree buffer
    return octree;
}

Note:\

*

*I have tried a minimal example of just computing uint3(1, 1, 1) * 0.25
expected result: uint3(0.25, 0.25, 0.25)
actual result: uint3(0.3, 0.3, 0.3)\

*I am using a RTX 2070

A: As user @bart pointed out, the issue was in the print, unity prints a 2 digit format which rounded my values down, by using ToString("F5") in my print it shows the correct values


text:
Q: Use integration by parts to prove the equality. Let $0<a<b $ and $ f: [a,b] \rightarrow [c,d]$ be an increasing bijection. Prove the following equality by area
$\int_{a}^{b}f(x)dx=bd-ac-\int_{c}^{d}f^{-1}(y)dy$.
Use integration by parts to prove the equality.
I honestly have no idea with this problem. I need full and detailed answer.


text:
Q: Error, me sale un error que no entiendo, estoy iniciando
Parse error: syntax error, unexpected '?> ' in C:\xampp\htdocs\EPWeb\Admin\Presentacion\Aval.php on line 48

Ese error me sale, estoy iniciando en php

Aval

            <button type="submit" class="btn btn-success btn-xs pull-right" value="Añadir" data-toggle="modal" data-target="#modal-default">
                 Añadir</button>

                    #
                    Descripción
                    Acción

                <?php

                $con = ConexionBD();
                $query= "SELECT * FROM aval";
                $ejecutar = mysqli_query($con,$query);

                where($mostrar == mysql_fetch_array($ejecutar)){

                ?>//esta es la linea 48

                        <?php echo $mostar['idaval'] ?>

                        <?php echo $mostar['descripcionaval'] ?>

                <?php
                    }
                  ?>

A: where($mostrar = mysqli_fetch_array($ejecutar)) {//este es tu error

while($mostrar = mysqli_fetch_array($ejecutar)) {//esta es la sintaxis


text:
Q: Authorization via JWT yields an "invalid assertion" error I failed to request an access token.
Following doc to authentification using JWT, I already have my connected app, my JWT Key so I just need to make a POST requestion to : https://test.salesforce.com/services/oauth2/token
Params are on the body :
grant_type : urn:ietf:params:oauth:grant-type:jwt-bearer
assertion : the content of my jwt.key (private key)

I'm having error 400 :
{
"error": "invalid_grant",
"error_description": "invalid assertion"
}

Also added : Content-Type : application/x-www-form-urlencoded
What should I correct/add ?

*

*assertion : the content of my jwt.key (private key) ? shouldn't be the private key of my certificat ?

*add authorization => basic auth and ask my administrator to send me username/password of my connected app ?

A: It seems you haven't followed the JWT bearer flow documentation correctly.
You're not sending the private key directly (and if you have, you should consider it compromised and generate a new keypair and certificate), but rather using it to "sign" a copy of your payload (which, as I understand is hashing with sha256 followed by encrypting with the private key).
Having the certificate in Salesforce is then what allows you (well, Salesforce) to verify the signature (decrypt the signature with the public key in the cert, hash the original data, compare the two hashes, and make a determination whether or not the request was modified in-flight).
The structure of the JWT assertion looks like this

Base64URL({header}).Base64URL({claims}).Base64URL(RSA(SHA256(Base64URL({header}).Base64URL({claims}))))

or grouped a bit differently for readability

encodedHeader = Base64URL({header})
encodedClaims = Base64URL({claims})
token = encodedHeader.encodedClaims
assertion = token.Base64URL(RSA(SHA256(token)))

The private key is used in generating the signature (i.e. the second part of the "assertion"). If your assertion doesn't start with eyJhbGciOiJSUzI1NiJ9 (the Base64 encoded version of {"alg":"RS256"}) then it is wrong.
You also need to ensure the following:

*

*The scopes granted by your connected app include "access and manager your data (api)", "perform requests on your behalf at any time (refresh_token, offline_access)"

*The connected app is installed in your target org

*The connected app is configured to "Use Digital Signatures", and you've uploaded the certificate (.crt file)

*If you're installing the connected app in another org (i.e. the connected app is in your production org and you want to use it to authenticate with a new sandbox), you'll need to go through another OAuth flow (like the Web-Server or User-Agent flows) to avoid the user hasn't approved this consumer error. This question goes into more detail on that.

A: I got the following...
ERROR running auth:jwt:grant:  We encountered a JSON web token error, which is likely not an issue with Salesforce CLI. Here's the error: Error authenticating with JWT config due to: invalid assertion

... which was because I didn't upload my server.crt to the Connected App (or rather, Save didn't take it ;) ).

A: I got this exception, too. In Salesforce the certificate (public key) was missing. Maybe during your tests the certificate was removed.
In connected app form:

*

*Assure that the field Digital Certificate is filled with a valid certificate (not expired)

*Please assure that these flags are set:

*

*Require Secret for Web Server Flow

*We set these flag as well inspite of we don't get an refresh token

*

*Require Secret for Refresh Token Flow


text:
Q: C# HTTPWebRequest.GetResponse() strips out query string I'm almost certain that I'm just misunderstanding how query strings should be passed in using C# HTTPWebRequest/Response, but I can't figure out why when I call (HTTPwebResponse)request.GetResponse(); it strips out the query portion and only gives the resulting HTML of the base URL. What am I doing wrong? Note that I generalized the URL for simplicity but kept the same query string just in case the structure of that is the problem.
string urlQueryString = "https://baseUrl.com/folder1/folder2?status_filter_mode=approved";
var targetUri = Uri.EscapeUriString(urlQueryString);

request = HttpWebRequest.Create(targetUri) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko";
request.Method = "GET";
//set the cookie in the request header
request.Headers.Add("Cookie", cookiedata);

response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
    using (StreamReader reader = new StreamReader(stream))
    {
        htmlResult = reader.ReadToEnd();
    }
}
response.Close();


text:
Q: What is the go_package option used for in a protocol buffer file? I did some research including looking at the official doc from google and I can't find a good explanation of what the go_package option is used for. The official doc states the following:

The .proto file should contain a go_package option specifying the full import path of the Go package that contains the generated code.

I guess what i'm confused with is what they mean by import path. It sounds more like an export path as in where we want to place the generated code? But why would we need this if we can specify the out path during --go_out=? So i'm having trouble grasping why you need to specify an export path in the proto file and at the same time specify an output path in option go_package?

A: Declaring the generated codes expected import path is important for other protobuf files to know how to refer to those types in the generated code.
If all of your protobuf definitions are declared in a single .proto file, the import path means little because they are implicitly sharing the same go package. If you start storing/generating protobuf files in multiple packages, they need to know how to find each other.
Looking at the protobuf "Well Known" types is a good example of this:
https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto
The top of that file has the following package declaration:
option go_package = "google.golang.org/protobuf/types/known/timestamppb";

If I consume that message in another protobuf file using:
import "google/protobuf/timestamp.proto";

message MyModel {
   google.protobuf.Timestamp ts = 1;
}

My generated file for MyModel will contain an import statement at the top of the .pb.go file that looks like:
import timestamppb "google.golang.org/protobuf/types/known/timestamppb"


text:
Q: Update OSM database failing I'm trying to udapte a OSM database that I just imported. After following the steps https://ircama.github.io/osm-carto-tutorials/updating-data
I don't manage to pass the first udpate. I always get the same error:
After setting the configuration file for daily updates:
# The URL of the directory containing change files.
baseUrl=https://planet.openstreetmap.org/replication/day

# Defines the maximum time interval in seconds to download in a single invocation.
# Setting to 0 disables this feature.
maxInterval = 3600

and downloading the state file
wget  -o /osmosis/state.txt "https://planet.openstreetmap.org/replication/day/000/003/524.state.txt"
When executing:
/osmosis/bin/osmosis --read-replication-interval workingDirectory=/osmosis/ \
--simplify-change --write-xml-change - | \
osm2pgsql --append --flat-nodes /data/nodes.bin --database=osm --user=osmuser --host=plot-osm-postgresql --log-level=debug &> /data/osm2pgsql.log

I see the following error:
The replication state doesn't contain a timestamp property
INFO: Reading current server state. [ReplicationState(timestamp=Mon May 30 00:00:00 GMT 2022, sequenceNumber=3547)]
May 30, 2022 1:45:30 PM org.openstreetmap.osmosis.core.pipeline.common.ActiveTaskManager waitForCompletion
SEVERE: Thread for task 1-read-replication-interval failed
org.openstreetmap.osmosis.core.OsmosisRuntimeException: The replication state doesn't contain a timestamp property.
    at org.openstreetmap.osmosis.replication.common.ReplicationState.loadProperty(ReplicationState.java:65)
    at org.openstreetmap.osmosis.replication.common.ReplicationState.load(ReplicationState.java:78)
    at org.openstreetmap.osmosis.replication.common.ReplicationState.<init>(ReplicationState.java:59)
    at org.openstreetmap.osmosis.replication.v0_6.BaseReplicationDownloader.runImpl(BaseReplicationDownloader.java:290)
    at org.openstreetmap.osmosis.replication.v0_6.BaseReplicationDownloader.run(BaseReplicationDownloader.java:372)
    at java.base/java.lang.Thread.run(Thread.java:829)

May 30, 2022 1:45:30 PM org.openstreetmap.osmosis.core.Osmosis main
SEVERE: Execution aborted.
org.openstreetmap.osmosis.core.OsmosisRuntimeException: One or more tasks failed.

Lots of the questions out there point to the missing https in the configuration file but that's already there by default for me.
Any other clue of what could be going wrong?


text:
Q: Is the a way for SQLDelight to allow unrecognized expression? I use SQLDelight's MySQL dialect on my server. Recently I plan to migrate a table to combine many fields into a JSON field so the server code no longer needs to know the complex data structure. As part of the migration, I need to do something like this during runtime - when the sever sees a client with the new version, it knows the client won't access the old table anymore, so it's safe to migrate the record to new table.
INSERT OR IGNORE INTO new_table SELECT id, a, b, JSON_OBJECT('c', c, 'd', JSON_OBJECT(…)) FROM old_table WHERE id = ?;

The only problem is - Unlike the SQLite dialect, the MySQL dialect doesn't recognize JSON_OBJECT or other JSON expressions, even though in this case it doesn't have to - no matter how complex the query is, the result is not passed back to Kotlin.
I wish I could add the feature by myself, but I'm pretty new to Kotlin. So my question is: is there a way to evade the rigid syntax check? I could also retrieve from old table, convert the format in Kotlin, then write to the new table, but that would take hundreds of lines of complex code, instead of just one INSERT.

A: I assume from your links you're on the alpha releases already, in alpha03 you can add currently unsupported behaviour by creating a local SQLDelight module (see this example) and adding the JSON_OBJECT to the functionType override. Also new function types are one of the easiest things to contribute up to SQLDelight so if you want it in the next release

A: For the record I ended up using CONCAT with COALESCE as a quick and dirty hack to scrape the fields together as JSON.


text:
Q: sns.catplot - how can i make my legend bigger? I have this code:
ax = sns.catplot(x='account_name', y='cnt', hue='threat_campaigns',data=df_mitigation,kind='bar', height=15, aspect=3.1, palette='coolwarm' )
ax.fig.suptitle("Accounts' violations disribuation over the last week", fontsize=40)
plt.yscale("log")

plt.xlabel('Account', fontsize=40)
plt.ylabel('Number of requests', fontsize=40)
plt.setp(ax._legend.get_title(), fontsize=40)

plt.show()

see what i get as in screenshot - everything is very small - how can i make it bigger.

A: You can update the rcParams dictionary using an example like with sns.plotting_context(rc={"legend.fontsize":24, "legend.title_fontsize":24}):.
Reproducible example.
df = sns.load_dataset('flights')
with sns.plotting_context(rc={"legend.fontsize":24, "legend.title_fontsize":24}):
    ax = sns.catplot(x='year', y='passengers', hue='month', data=df, kind='bar', height=15, aspect=3.1, palette='coolwarm')
    plt.show()

Before:

After:


text:
Q: How can I put a rectangular photo in a square photo? I have a rectangular photo.
I want to put it in a square photo.
So that the whole rectangle is placed in the square.
(I want to have the entire rectangle image in the square photo!)
I tried this:
$width = 500;
$height = 500;
$img = Image::make($path);
$img->width() > $img->height() ? $width=null : $height=null;
$img->resize($width, $height, function ($constraint) {
    $constraint->aspectRatio();
})->fit(500, 500, function ($constraint) {
    $constraint->upsize();
});

But it cut some portion of main image.
How can I correct that?

A: You can make your image to its original aspect ratio but fit it in the size of the square without crop it. As i see you use Intervention Image so you can try:
$img = Image::make($path)->resize($width, $height, function ($constraint) {
    $constraint->aspectRatio();
});

With that, you tell Intervention to create an image and choose to fit the square as per width if your image's width is bigger than height or per height if your image's height is bigger than width.
If you also want a square around you can use:
$square = Image::canvas($width, $height, '#101010')->insert($img, 'center');


text:
Q: Regular expression to extract either integer or string from JSON I am working in an environment without a JSON parser, so I am using regular expressions to parse some JSON. The value I'm looking to isolate may be either a string or an integer.
For instance
Entry1
{"Product_ID":455233, "Product_Name":"Entry One"}

Entry2
{"Product_ID":"455233-5", "Product_Name":"Entry One"}

I have been attempting to create a single regex pattern to extract the Product_ID whether it is a string or an integer.
I can successfully extract both results with separate patterns using look around with either (?<=Product_ID":")(.*?)(?=") or (?<=Product_ID":)(.*?)(?=,)
however since I don't know which one I will need ahead of time I would like a one size fits all.
I have tried to use [^"] in the pattern however I just cant seem to piece it together
I expect to receive 455233-5 and 455233 but currently I receive "455233-5"

A: (?<="Product_ID"\s*:\s*"?)[^"]+(?="?\s*,)
, try it here.


text:
Q: AWS Codestar Proper Way to Add RDS Postgres Database without Breaking Anything I'm using AWS Codestar setup and I would like to add a database.config to my .ebextentions folder in my rails project.
If you're wondering why I'm not adding database trough console, the Codestar's pipeline fails at the final ExecuteChangeSet stage for CloudFormation changes and throws a 404 error, I assume CodePipeline looking for the previous instance.
Error Message I've been receiving AWS suggests I edit Elastic Beanstalk directly. Really somewhat lost how I can add a database to my project using Elastic Beanstalk while not breaking Codestars CodePipline ExecuteChangeSet.
You specified the 'AWSEBRDSDBInstance' resource in your configuration to create a database instance,
without the corresponding database security group 'AWSEBRDSDBSecurityGroup'. For a better way to add
and configure a database to your environment, use 'eb create --db' or the Elastic Beanstalk console
instead of using a configuration file.

My .ebextensions/database.config file so far.
Resources:
    AWSEBRDSDatabase:
        Type: AWS::RDS::DBInstance
        Properties:
            AllocatedStorage: 5
            DBInstanceClass: db.t2.micro
            DBName: phctest
            Engine: postgresql
            EngineVersion: 10.4
            MasterUsername: username
            MasterUserPassword: password

I could also make a separate RDS database on it's own I thought about that, but like to leave it for Elastic Beanstalk.


text:
Q: How do I make timer wait until done? I have an ASP.NET website where I have to show some data on a Gridview, I need this data to be shown as fast as possible, so I decided to create a timer inside an Update panel and then Refresh the grid over and over, however I see that my timer is not waiting until it was done in order to Tick again, it's executing itself over and over, which is giving me performance issues on the database, how can I tell my timer "hey stop until this process is done, then continue".
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
     <ContentTemplate>
            <asp:Timer ID="Timer1" runat="server" Interval="400" OnTick="Timer1_Tick" EnableViewState="False">
            </asp:Timer>
            <asp:GridView ID="gv_stats" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" ShowHeaderWhenEmpty="True" GridLines="Vertical" Width="562px" OnRowDataBound="gv_stats_RowDataBound" ShowFooter="True" EnableViewState="False" >
                   <AlternatingRowStyle BackColor="#CCCCCC" />
                        <Columns>
                        </Columns>
            </asp:GridView>
     </ContentTemplate>
</asp:UpdatePanel>

I tried this:
     private bool is_refreshing = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
        }
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        Timer1.Enabled = false;
        if(is_refreshing == false)
        BindGrid();
        Timer1.Enabled = true;

    }

   public void BindGrid()
        {

            is_refreshing = true;
            grd.datasource = con.executedt;
            grd.databind();
            is_refreshing = false;
         }

A: When you refresh the grid, you can set a private boolean variable indicating the that the grid is refreshing and before the execution of code that refreshes the grid, you can check this variable.
EDIT - Try using a session variable instead of a private variable. See updated example.
Example -
// code change starts
private bool _isGridRefreshing
{
   get
   {
      var flag = HttpContext.Current.Session["IsGridSession"];
      if(flag != null)
      {
         return (bool)flag;
      }

      return false;
   }
   set
   {
      HttpContext.Current.Session["IsGridSession"] = value;
   }
}
// code change ends

protected void Timer1_Tick(object sender, EventArgs e)
{
   if(_isGridRefreshing == false)
   {
       RefreshGrid();
   }
}

private void RefreshGrid()
{
   _isGridRefreshing = true;

   //code to refresh the grid.
}

Note - I haven't tested the code, but it should give a fair idea of what needs to be done.


text:
Q: The equivalence of two different CNF logical formulas - complexity
We have two different logical formulas (ψ and ϕ). Is there a quick way
  to prove that if the formulas are equivalent (or not)? (if the formula
  ψ is unsat also a formula ϕ is unsat (in SAT problem))

Pre question: The equivalence of two different CNF logical formulas
The current question: Is there a way to do it in polynomial time? (by the number of variables)

A: Assuming we are talking about propositional logic, we know that it can be in in non-polynomial time, but whether it can be done in polynomial time is exactly the question as to whether $P = NP$


text:
Q: Xamarin - binding to variable in datatemplate How do I bind a value from my object property to a variable so that I can pass it as an argument/parameter for my method "setFavoriteProduct(id_product, favnumber) which is triggered by my button "choiceButton". I require the property value "id_product".
When I bind it to Label "id_productLabel" then I can see it in the View just fine but I need to use the string value in my "setFavoriteProduct" function.
listView.ItemTemplate = new DataTemplate(() =>
            {

                Image productImage = new Image();
                productImage.SetBinding(Image.SourceProperty, "imageURL");
                //productImage.HeightRequest = 60;
                productImage.HeightRequest = 120;
                //productImage.WidthRequest = 60;
                productImage.WidthRequest = 120;
                productImage.Aspect = Aspect.AspectFit;

                Label nameLabel = new Label();
                nameLabel.SetBinding(Label.TextProperty, "name");

                Label id_productLabel = new Label();
                id_productLabel.SetBinding(Label.TextProperty, "id_product");
                id_productLabel.IsVisible = true;

                Button choiceButton = new Button();
                choiceButton.Text = "Vali";
                choiceButton.Clicked += (sender, args) => setFavoriteProduct(
                    id_product,
                    favnumber
                );

                return new ViewCell
                {
                    View = new StackLayout
                    {
                        Padding = new Thickness(0, 5),
                        Orientation = StackOrientation.Horizontal,
                        Children = { productImage, id_productLabel , nameLabel, choiceButton }
                    }
                };

A: the simplest way to do this is to get the BindingContext from the sender (button) and then get the property from that
choiceButton.Clicked += (sender, args) => {
  var context = (MyClass)((Button)sender).BindingContext;
  var id = context.id_product;
  setFavoriteProduct(id,favnumber);
};

alternately, you could use the Button's Command and CommandParameter properties instead of the Clicked event


text:
Q: Auto Module Export in NodeJS I have a controller
import fetch from 'node-fetch'
import faker from 'faker'
import bodyParser from 'body-parser'
import request from 'request-promise'
import _ from 'lodash'

async function getAccounts(req, res) {
    try {
        const response = await fetch(`http://www.api.com/accounts`);
        const json = await response.json();
        console.log(`${json}`);
        res.send(json)
    } catch (error) {
      console.log(error);
    }
};

async function getAccount(req, res) {
    try {
        const response = await fetch(`http://www.api.com/account/${req.params.id}`);
        const json = await response.json();
        console.log(`${json}`);
        res.send(json)
    } catch (error) {
      console.log(error);
    }
};

async function store(req, res) {
    try {

        var account = {};
        account.account_id                = Number(req.params.id);
        account.email_address             = faker.internet.email().toLowerCase();
        account.password                  = 'benu123';
        account.account_type              = 'customer';
        account.name_prefix               = faker.name.prefix();
        account.first_name                = faker.name.firstName();
        account.middle_names              = '';
        account.last_name                 = faker.name.lastName();
        account.name_suffix               = faker.name.suffix();
        account.non_person_name           = false;
        account.DBA                       = '';
        account.display_name              = faker.name.firstName() + faker.name.lastName();
        account.address1                  = faker.address.streetAddress();
        account.address2                  = faker.address.secondaryAddress();
        account.address3                  = '';
        account.city                      = faker.address.city();
        account.state                     = faker.address.state();
        account.postal_code               = faker.address.zipCode();
        account.nation_code               = faker.address.countryCode();
        account.phone1                    = faker.phone.phoneNumber();
        account.phone2                    = faker.phone.phoneNumber();
        account.phone3                    = faker.phone.phoneNumber();
        account.time_zone_offset_from_utc = -5;
        account.customer_type             = 4;
        account.longitude                 = Number(faker.address.longitude());
        account.latitude                  = Number(faker.address.latitude());
        account.altitude                  = Number(faker.address.longitude());

        var options = {
            method: 'POST',
            uri: 'http://www.api.com/account',
            body: {
                some: account
            },
            json: true // Automatically stringifies the body to JSON
        };

        request(options)
            .then(function () {
                // console.log(account.getAccounts())
                // res.send(account.getAccounts())

            })
            .catch(function (err) {
                console.log(err)
                res.send(err)
            });

    } catch (error) {
      console.log(error);
    }
};

async function update(req, res) {
    try {
        const response = await fetch(`http://www.api.com/account/${req.params.id}`);
        const json = await response.json();
        console.log(bodyParser.json());
        res.send(bodyParser.json())
    } catch (error) {
      console.log(error);
    }
};

async function destroy(req, res) {
    try {
        const response = await fetch(`http://www.api.com/account/${req.params.id}`);
        const json = await response.json();
        console.log(`${json}`);
        res.send(json)
    } catch (error) {
      console.log(error);
    }
};

module.exports = {
    getAccounts,
    getAccount,
    store,
    update,
    destroy
};

I have 5 functions in NodeJS, at the end I must export them like this
module.exports = {
    getAccounts,
    getAccount,
    store,
    update,
    destroy
};

Is there a way to auto export these with some kind of packages or plugin ?