Q: No mole class for NativeMethods.cs? I have a class named NativeMethods.cs which contains all extern methods:
internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool wow64Process);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    internal static extern int RegOpenKeyEx(
        IntPtr hKey,
        string subKey,
        int ulOptions,
        int samDesired,
        out int hkResult);
}

The assembly containing this class has a corresponding .Moles file. All other classes included in the assembly can be moled and stubbed properly, except this one.
There is no MNativeMethods that we can use for detouring. Is there a special case against the class name "NativeMethods" (Highly unlikely)? Or a special case against extern methods?

A: Moles is capable of detouring calls to managed code. This class is clearly not dealing with managed code. Try creating a stub for this class, manually.  This means crating an INativeMethods interface, have NativeMethods implement INativeMethods, and then use the interface as the stub, as usual.  Moles will then generate stub type SINativeMethods from the interface, for use in test projects.

A: "Thus, if a method has no body (such as an abstract method), we cannot detour it." - Moles Dev


Q: adb I/O Error, possible corruption I am struggling to fix an issue I have. Basically my Galaxy S3 has just up and decided that Google Calendar will now crash whenever I open it. After examining the system log, stack trace, etc... it appears to be stemming from the app trying to access /data/data/com.google.android.calendar/databases/<database>.db, of course with a specific database name.
When I cd into the folder by using adb in root mode I find the folder lib, cache and a file named databases. The other two folders perform normally but databases is weird, it does not auto-complete with tab and using any form of file operation on it (such as less, rm, etc...) results in an I/O Error.
I think this is an oddly corrupted file that is causing the problem, particularly as it appears to stay even when I uninstall Google Calendar. Any help would be most appreciated in getting this sorted as I could really do with getting my calendar back.
Long display of results:
root@m0:/data/data/com.google.android.calendar # ls
databases
root@m0:/data/data/com.google.android.calendar # rm databases
rm failed for databases, I/O error
255|root@m0:/data/data/com.google.android.calendar # rm -rf databases
rm failed for databases, I/O error
1|root@m0:/data/data/com.google.android.calendar # cd databases
/system/bin/sh: cd: /data/data/com.google.android.calendar/databases: I/O error
2|root@m0:/data/data/com.google.android.calendar #
2|root@m0:/data/data/com.google.android.calendar # sqlite3 databases
SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .databases
Error: unable to open database "databases": unable to open database file
1|root@m0:/data/data/com.google.android.calendar #

Regards,
Ybrad

A: It happened to a friend on his Moto X Force, Instagram kept crashing. He was using LineageOS 7.1, we wiped everything and installed the original firmware (through TRWP) and when we was installing the package, it returned IO Error on "data/data/com.instagram.android/analytics/xxxxxxxx.pending". We formatted the /data partition but the problem persisted.
We installed the original firmware along with Magisk, installed Root Explorer and renamed the "com.instagram.android" folder to "insta.broken", uninstalled and reinstalled the app and voilá, working again.

A: Huh,
Turns out that if you uninstall the app, rename the folder containing the corrupted file and then re-install everything goes swimmingly.
No idea what caused it or even what is wrong but hey, I have my calendar back.


Q: geting maximu value in a table column I am trying to get maximum value of id column
$taskid = (new Query())->select('MAX(id)')->from('member');

echo $taskid;

unfortunate I got the below text
O:12:"yii\db\Query":20:{s:6:"select";a:1:{i:0;s:7:"MAX(id)";}s:12:"selectOption";N;s:8:"distinct";N;s:4:"from";a:1:{i:0;s:21:"member";}s:7:"groupBy";N;s:4:"join";N;s:6:"having";N;s:5:"union";N;s:6:"params";a:0:{}s:18:"queryCacheDuration";N;s:20:"queryCacheDependency";N;s:27:"yii\base\Component_events";a:0:{}s:35:"yii\base\Component_eventWildcards";a:0:{}s:30:"yii\base\Component_behaviors";N;s:5:"where";N;s:5:"limit";N;s:6:"offset";N;s:7:"orderBy";N;s:7:"indexBy";N;s:16:"emulateExecution";b:0;}

please help me out

A: Maximum id value of Member model:
use app\models\Member;
// ...
echo Member::find()->max('id');


Q: Testing RegEx against Null When calling RegEx.prototype.test() on null, JS runtimes appear to convert null into its string form ("null") and then test the regex against that. A few examples:
/[a-z]+/.test(null)
    true

/null/.test(null)
    true

/[0-9]+/.test(null)
    false

/nnull/.test(null)
    false

My questions are:

*

*Why?

*Is this correct behavior according to current specifications?

This behavior is horribly unintuitive. Since null conceptually represents the absence of any object, it conceptually makes sense that a RegEx test against it would fail, because there should be nothing to test against. It doesn't help that a lot of basic RegEx will succeed on testing against "null".
I have confirmed this behavior in Node.js and Firefox Nightly.

A: 21.2.5.13 RegExp.prototype.test( S )

The following steps are taken:

*

*Let R be the this value.

*If Type(R) is not Object, throw a TypeError exception.

*Let string be ToString(S).

*ReturnIfAbrupt(string).

*Let match be RegExpExec(R, string).

*ReturnIfAbrupt(match).

*If match is not null, return true; else return false.

And look at the ToString(S) you will see null = "null" and you get what you see.

A: Yes, this is as specified.
Per §21.2.5.13 "RegExp.prototype.test( S )" in the 2015 version (6th Edition), one of the first few steps is to apply the "ToString" operation to the argument S, and use its result. The "ToString" operation converts various non-string values to string values; null, in particular, is converted to "null".


Q: How can I use matcaffe in Windows? To use caffe in MATLAB, i need matcaffe.
The manual tells me to run "make all matcaffe"
But it does not tell where to command.
I command "run make all" matcaffe by running cmd from the cafe root folder where caffe.exe exists.
But there is an error saying "There is nothing to do for matcaffe"
Is there a clear, specific, and accurate description of how matcaffe can be run?
Thank you.

A: There is an official branch for caffe on Windows. BVLC/caffe
Follow the steps in that repository, like the below
C:\Projects> git clone https://github.com/BVLC/caffe.git
C:\Projects> cd caffe
C:\Projects\caffe> git checkout windows
:: Edit any of the options inside build_win.cmd to suit your needs
C:\Projects\caffe> scripts\build_win.cmd

If you got all the tools successfully installed, you will be able to build it successfully. Then you could find a .mex64 file under the caffe/matlab folder.
Simply add that directory into matlab, you can use matcaffe then.


Q: Issues with macros and formulas in Excel I'm having problems when inserting a formula from a macro in Excel. I managed to insert exactly the same value that I have on another cell where the formula is working perfectly. It always says #¿NAME? unless I press F2 and Enter. I checked and rechecked the calculation mode and is not Manual, is set to automatic but this formulas doesn't work at all. The method SendKeys "{f2}" SendKeys "{enter}" seems to work but it's horrible and not "seamless".
I've tried with different formulas (from simpler to more complex) and every time a tried any function inside my formula just doesn't work. The only way I insert a working formula is just using numbers (ex. "=1+1" and stuff like that) but when using any function for ex. "=SUM(A1:A5)" just don't work (unless pressing F2 and Enter).
I don't understand why having exactly the same "text" inserted as Formula it just don't work.
What can I do to solve this???
Thanx in advance

A: Thanks for your replies!!!
Using FormulaLocal works great!!! What I did was to "translate" the functions names and done!
Cells(LastRow + 1, 3).Formula = "=IFERROR(VLOOKUP(" & "B" & laststr & " , Datos!A2:E52, 3), """")"

A: Please refer to the answer by Monster for the correct solution to the problem.
I have to leave this answer here until it is "unaccepted", and then I will be able to delete it.

To enter locale-dependent formulas, you need to use FormulaLocal:
Cells(LastRow + 1, 3).FormulaLocal = "=SI.ERROR(BUSCARV(B" & laststr & " , Datos!A2:E52, 3), """")"


Q: Eclipse not recognizing my "Main" method I'm trying to write a "Hello, World" variant program in Eclipse, and I can't seem to be able to run my program.
Here's the code:
/**
 *
 */
package GreeterPackage;

/**
 * @author Raven Dreamer
 * Prints out "Hello, World" in three languages:
 * English, French, and Spanish.
 */
public class GreeterProg {

    /**
     * returns "Hello, World" three times, once
     * in English, once in French, and once in
     * Spanish.
     */
    public static void Main(String[] args){
    /** instances of the three greeter
     * classes so the non-static methods
     * can be called.
     */
    EnglishGreeter eng = new EnglishGreeter();
    FrenchGreeter fre = new FrenchGreeter();
    SpanishGreeter spa = new SpanishGreeter();
    System.out.println(eng.greet());
    System.out.println(fre.greet());
    System.out.println(spa.greet());

}
}

And here's my code for SpanishGreeter (French and English greeter are identical, currently)
/**
 *
 */
package GreeterPackage;

    /**
     * @author Raven Dreamer
     * Returns "Hello, World!" but in Spanish!
     */
    public class SpanishGreeter extends greeter {

        /**Spanish string of "Hello, World!"
         */
        private String GREET = "¡Hola, World!";

        /**
         * returns "Hello, World" in Spanish
         */
        public String greet() {
            return GREET;
        }

    }

The code compiles fine with no errors, but when I try to run the program as a java application, I get the following error:

So I am left baffled as to what, exactly, the problem is. Am I missing something salient in terms of how I set the project up in the first place?

A: The problem is that you have Main with a capital letter. Java is case-sensitive.
The full method signature is: public static void main(String [] args)

A: Your main method needs to be a lowercase "main".

A: "main" must be in lowercase only. Java method names are case-sensitive.


Q: Infinite scrolling I am trying to add some "Infinite Scrolling" to my product pages. However, i can't get it working at all, so i have nothing.
The page currently works, but it just outputs all of the products. I can't get the infinite scrolling scripts i found working, as my query is not always the same.
This is the code that builds my query, using GETs:
$kategori_q = "";
if ($kategori !== "") {
    if ($hkat !== "") {
        $ukator = "";
        $underkategorier = sqlSelect("SELECT * FROM underkategorier WHERE fk_hkategori = '$kategori'");
        while ($row = sqlFetch($underkategorier)) {
            $ukator .= " fk_ukategori = '".$row['underkategori_id']."' OR";
        }
        $kategori_q = rtrim($ukator, "OR");
        $kategori_q = "WHERE ($kategori_q)";
    }
    else {
        $kategori_q = "WHERE fk_ukategori = '$kategori'";
    }
}

$query = "SELECT * FROM annoncer $kategori_q ORDER BY annonce_id DESC";

$soeg = "";
if (isset($_GET['soeg'])) {
    $soeg = $_GET['soeg'];
    if (substr_count($query, "WHERE") == 1) {
        $soeg = " AND (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
    }
    else {
        $soeg = " WHERE (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
    }
}

$query = "SELECT * FROM annoncer $kategori_q $soeg ORDER BY annonce_id DESC";
$q = sqlSelect($query);


Q: JavaScript function not retrieving string from HTML textarea I am learning JavaScript and I am not understanding why my message is not being retrieved by a word count function. When I click the button with a message of multiple words, I am receiving '1' as the word count, which is incorrect. I have tested the calWords function which works correctly when using console.log(calWords(some message));.
This code is written using requirements and I cannot use .split() or regex. Here is a link to the code:
https://jsbin.com/rucicol/edit?html,js,console,output
<form class="userform">
  Enter a Message to Display Statistics

  <textarea type="text" name="message" id='userInput'></textarea>

  <button type="button" onclick="showStats()">Submit</button>
</form>

// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput').value;

// display stats
function showStats() {

   alert(calWords(displayStats));
}

// calculate words
function calWords(str) {

   for(var i = 0; i < str.length; i++) {
     if (str[i] === ' ') {
      numWords ++;
     }
   }
   return numWords + 1;
}

A: This is because, when you create displayStats you take the value of the textarea at the moment of the creation (e.g. nothing).
To make your script working, you can "store" the reference to the textarea in displayStatsand access his value when needed.
This is the corrected script:
// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput');

// display stats
function showStats()
   alert(calWords(displayStats.value));
}

// calculate words
function calWords(str) {
   for(var i = 0; i < str.length; i++) {
     if (str[i] === ' ') {
      numWords ++;
     }
   }
   return numWords + 1;
}

A: Add the code to get the text area content inside the function.
// global variables
var numWords = 0;

// display stats
function showStats() {
  var displayStats = document.getElementById('userInput').value;
  alert(calWords(displayStats));
}

// calculate words
function calWords(str) {

  for(var i = 0; i < str.length; i++) {
    if (str[i] === ' ') {
      numWords ++;
    }
  }
  return numWords + 1;
}

A: The reason being you have initialised the displayStats globally which will be initialised once the page when load will happen. It would be better if you move displayStats inside click handler.
Also, if you are interested in knowing the number of words in the textarea, you should move your numWords inside the calWords, that way you will get the number of words which is present in the textarea.

// display stats
function showStats() {
  var displayStats = document.getElementById('userInput').value;
  alert(calWords(displayStats));
}

// calculate words
function calWords(str) {
  var numWords = 0;
   for(var i = 0; i < str.length; i++) {
     if (str[i] === ' ') {
        numWords ++;
     }
   }
   return numWords + 1;
}
<form class="userform">
  Enter a Message to Display Statistics

  <textarea type="text" name="message" id='userInput'></textarea>

  <button type="button" onclick="showStats()">Submit</button>
</form>


Q: Wordpress: register_my_menus / creating a new menu does not work I have prepared a positioning of my own menus. So far the menu only reacts to the styling. Wordpress simply selects any menu. For example, if I create a new footer menu, the actual top menu is replaced. The current solution without further menus:
<?php wp_nav_menu( [ 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?>

The code in the function.php I have used so far:
function register_my_menus() {

  register_nav_menus(

   array( 'top_menu' => __( 'Top Menu', 'test' ),

          'footer_menu' => __( 'Footer Menu', 'test' ))

          'blog_menu' => __( 'Blog Menu', 'test' ))

  );

}

add_action ('init', 'register_my_menus');

The code in the header.php that I have tried so far for positioning:
<?php wp_nav_menu( array( 'theme_location' => 'top_menu', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown' ) ); ?>

A: I love the object-oriented approach:
class Menu_init {

    public function __construct() {
        add_action( 'init', array($this, 'register_menus'));
    }

    public function register_menus() {

        register_nav_menus(

            array(
                'top_menu' => __( 'Top Menu', 'test' ),
                'footer_menu' => __( 'Footer Menu', 'test' )
                'blog_menu' => __( 'Blog Menu', 'test' )
            )

        );

    }

}

new Menu_init();

and for your header of course:
<?php
wp_nav_menu( [
    'theme_location' => 'primary',
    'container_id' => 'main-nav',
    'menu_id' => 'menu-top-menu',
    'menu_class' => 'dropdown'
] );
?>

It is true, you have an extra bracket ( ) ).

A: function register_my_menus() {

    $locations = array(
        'primary'  => __( 'Top Menu', 'test' ),
        'blog' => __( 'Blog Menu', 'test' ),
        'footer'   => __( 'Footer Menu', 'test' ),
    );

    register_nav_menus( $locations );
}

add_action( 'init', 'register_my_menus' );

<?php wp_nav_menu( [ 'theme_location' => 'primary', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?>


Q: Matlab: Creating contour maps/images similiar to SigmaPlot If a = columns, b = rows and c = intensity. How can I create an image of dimensions a by b and for each pixel to have intensity c:
In SigmaPlot, to create a 29x4 image, a , b and c are formatted as follows, how can the data be formatted in Matlab to achieve similar results:
[a, b, c] =

1   1   0
2   1   0
3   1   0
4   1   0
5   1   0
6   1   360.389854270598
7   1   524.553377941978
8   1   587.550618428821
9   1   535.164504523392
10  1   494.350943153525
11  1   509.366595359498
12  1   541.550829317582
13  1   714.122144025010
14  1   807.904727901154
15  1   634.059149684754
16  1   406.202488197581
17  1   338.349519959103
18  1   348.757723417053
19  1   334.118680593247
20  1   375.846361889047
21  1   507.518116274100
22  1   422.583478997748
23  1   0
24  1   0
25  1   0
26  1   0
27  1   0
28  1   0
29  1   0
1   2   0
2   2   0
3   2   0
4   2   0
5   2   0
6   2   222.769016959765
7   2   426.141970064050
8   2   481.453912764027
9   2   517.069153954465
10  2   487.414455654141
11  2   506.604099604784
12  2   514.770604062499
13  2   460.590220686965
14  2   376.241099616609
15  2   337.728227490832
16  2   394.310238250583
17  2   644.982641646965
18  2   856.664806333676
19  2   1040.69617779231
20  2   1128.07830809176
21  2   1070.24104109274
22  2   850.891638429000
23  2   489.144965506451
24  2   0
25  2   0
26  2   0
27  2   0
28  2   0
29  2   0
1   3   0
2   3   0
3   3   0
4   3   0
5   3   0
6   3   0
7   3   337.875341290982
8   3   446.387817855576
9   3   505.667919278579
10  3   474.666874694826
11  3   404.395323496310
12  3   345.514890319901
13  3   367.942209080407
14  3   450.883569030291
15  3   507.808892555292
16  3   498.203471996257
17  3   501.711478584646
18  3   518.354642382383
19  3   596.694216569632
20  3   591.347390565249
21  3   622.610680837716
22  3   667.944336239558
23  3   445.858691175108
24  3   0
25  3   0
26  3   0
27  3   0
28  3   0
29  3   0
1   4   0
2   4   0
3   4   0
4   4   0
5   4   0
6   4   0
7   4   216.608353008468
8   4   375.475770667960
9   4   425.565743597413
10  4   380.722854551759
11  4   317.194831801482
12  4   337.830175882681
13  4   352.530658493000
14  4   352.286503054898
15  4   323.117595263304
16  4   289.104540650745
17  4   259.229945714487
18  4   233.527214821773
19  4   137.305656551259
20  4   1418.69232849777
21  4   1055.72415597513
22  4   818.007236956091
23  4   595.146860875435
24  4   363.440841935283
25  4   0
26  4   0
27  4   0
28  4   0
29  4   0

A: It seems there is an inconsistency in the data definition: you define

*

*a as the columns (ranging from 1 to 29)

*b as the rows (ranging from 1 to 4)

*nevertheless, then you refer to a 29 x 4 matrix, while it should be 4 x 29
A part from that, you have to first re-arrange the definition of the input data as follow:
abc=[
1   1   0
2   1   0
3   1   0
4   1   0
5   1   0
6   1   360.389854270598
7   1   524.553377941978
8   1   587.550618428821
...
all the other data
...
]

that is to include them into [].
Then you can:

*

*extract the intensity data (which are in the third column of the abc matrix

*use the reshape function to convert the intensity array into a matrix

*"automatically" the x and y data by using the unique function

*get the number of row and column using the length function

*use the meshgrid function to generate the XY grid over which to plot the surface

At this point you can:

*

*use the surf function to plot a 3D surface (the z values will be the intensity data)

*create flat surface and use the intensity data as "colour"

*use the contour function to plot a 2D contour plot

*use the contour3 function to plot a 3D contour plot

This solution can be implemented as follows (where abc is your complete data set):
% Get the intensity data
intensity=abc(:,3);
% Get the x and y data
row_data=unique(abc(:,1));
col_data=unique(abc(:,2));
n_row=length(row_data);
n_col=length(col_data);

% Reshape the intensity data to get a 29x4 matrix
z=reshape(intensity,n_row,n_col);
% Create the grid to plot the surface
[X,Y]=meshgrid([1:n_col],[1:n_row])

% Plot a 3D surface
figure
surf(X,Y,z)
shading interp
colorbar

% Plot a flat surface with
figure
% Create a "dummy" zeros matrix to plot a flat surface
Z=zeros(size(X));
surf(X,Y,Z,z)
shading interp
colorbar

% Plot a 2D contour
figure
[c,h] = contour(z);
clabel(c,h)
colorbar

% Plot a 3D contour
figure
[c,h] = contour3(z);
clabel(c,h)
colorbar

Hope this helps.
Qapla'


Q: When do I see "404" in the page? I'm a rookie in nodejs, and I'm learning Koa. I got some problem about this code.
const Koa = require('koa');
const app = new Koa();

app.use(async function(ctx, next) {
  await next();
  if (ctx.body || !ctx.idempotent) return ;
  ctx.status = 404;
});

What is the meaning of await next() and if statement after that ?

A: This works like a "catch all" statement, reading in plain English:

*

*wait for the request to be processed by other parts of the app
(await next())

*when done, check if the app responded with a body or the request does not require a response body

*if none is true, return HTTP code 404 "Not Found"


Q: How to make clipping geometry scale with the target? In the following example whenever Grid size is changed, the clipping region size remains as it is expressed in absolute coordinates.
<Grid Clip="M10,10 L10,150 L150,150 L150,10 Z">
    <Rectangle Fill="Red"/>
</Grid>

Is is possible somehow to clip the region such that the clipping geometry is scaled along with the clipped object?
Code behind solutions are not accepted, because this is to be used in the control template. Also, the region in the example is a simple shape for clarity sake. The actual used region is a complex and asymmetric shape.
EDIT:
It looks like I have to be more specific. This is the snipped that is part of custom control template for ProgressBar. When scaling the outer grid, the PART_Indicator rectangle does not scale its clipping region. The correct composition is when grid is sized 200x200.
<Grid>
    <Path Name="PART_Track"
          Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
          Fill="AliceBlue" Stretch="Fill"/>

    <Rectangle Clip="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
               Stretch="Fill"
               Name="PART_Indicator" Fill="Red"
               Height="100" VerticalAlignment="Top"/>

    <Path Name="Border" Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
          Stretch="Fill" StrokeThickness="3" Stroke="Black"/>
</Grid>

UPDATE:
Rick provided excellent suggestion, though it took time for me to understand how to use it.
Here is the final code.
<Viewbox StretchDirection="Both" Stretch="Fill" >
    <Grid>
        <Path Name="PART_Track"
              Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
              Fill="AliceBlue" Stretch="Fill"/>

        <Border Clip="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
                Height="200" VerticalAlignment="Bottom">
            <Rectangle Name="PART_Indicator" Fill="Red" VerticalAlignment="Bottom"
                       Height="40"/>
        </Border>

        <Path Name="Border"
              Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
              StrokeThickness="3"
              Stretch="Fill" Stroke="Black"/>
    </Grid>
</Viewbox>

A: Put the Grid inside of a Viewbox and change the size of the Viewbox instead of the Grid.
<Viewbox>
    <Grid Clip="M10,10 L10,150 L150,150 L150,10 Z" Width="200" Height="200">
        <Rectangle Fill="Red"/>
    </Grid>
</Viewbox>

A: An alternative approach to this is to define the clipping path using element rather than attribute syntax, and then use the same transformation on the clip as you apply to the element as a whole, e.g.:
<Grid.Clip>
    <PathGeometry FillRule="Nonzero" Transform="{Binding Path=MatrixTransform, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}">
        <PathFigure StartPoint="715, 96.3333" IsClosed="True" IsFilled="True">
            <PolyLineSegment IsStroked="False">
                <PolyLineSegment.Points>
                    <Point X="1255.2526" Y="540" />
                    <Point X="426.3333" Y="1342.3333" />
                     <Point X="64.66666" Y="7356.6666" />
                </PolyLineSegment.Points>
            </PolyLineSegment>
       </PathFigure>
   </PathGeometry>
</Grid.Clip>


Q: Which version of angular-notify is compatible with angular version 15? I use angular version 15.0.0 and tried to install angular-notify version 12, but I got an error while installing process. How can I fix the error and install notify successfully?
Best regards.


Q: How can I return the sum of things counted in xpath for $b in doc ("courses.xml") //Course_Catalog/Department/Course
where count($b/Instructors/Lecturer)=0
return count($b)

This code returns the result: 1 1 1 1 1 1 1 1 1 1.  What I acutally want is all the ones to be added up to return the figure 10.
I would be grateful if somebody can tell me how to achieve this. Thank you in advance for any help offered.

A: Use sum:
sum(
  for $b in doc ("courses.xml") //Course_Catalog/Department/Course
  where count($b/Instructors/Lecturer)=0
  return count($b)
)

A: You actually need the count of all such elements.
Use:
count(doc ("courses.xml")//Course_Catalog/Department/Course[not(Instructors/Lecturer)])


Q: Exit protractor spec without failure Is there a way I can stop protractor from executing more tests in a spec even if there was no failure in the previous tests?
> describe('tests', function () {
>         it('should exit', function () {
>           protractor.stop(); <---- is there a way to prevent executing more tests?
>         });
>         it('should not run', function () {
>           expect(something).toBeTruthy();
>         });
>       });


Q: Rbenv permission denied issue I have trouble getting my Rails app running after I deployed this to my DO droplet.
I deployed (and installed everything including rbenv) following this guide. Rbenv seems to be installed properly but app is not running and nginx error log says "cannot execute /root/.rbenv/shims/ruby permission denied (13)"
I can not get the sense of this error, hope anyone can help with that.

A: Looks like rbenv's installed under root. It should probably be installed under your (or your app user's) home directory, in this case for the user named 'deploy.'
This Passenger configuration line from nginx.conf shows where it's expected to live:
/home/deploy/.rbenv/shims/ruby

So you should probably (re)install rbenv as/under 'deploy.'


Q: How to catch mouse moves outside of screen boundaries My application catpures mouse on down event and relies on mouse movements not directly related to current mouse pointer position (visible pointer). So the math is based on initial point and the relative point of the mouse and has the visual feedback visually not linked to the visible mouse pointer so the pointer might as well be hidden completely. But when I reach the screen boundaries, the incoming coordinates are clipped. It looks reasonable since the pointer don't move either, but I would like to continue getting information about relative mouse movements even if the visible pointer reached the screen boundary. Is this possible? Maybe with access to raw mouse information from the driver?

A: Basically Raw Input Api serves my goal. One needs to register the window with RegisterRawInputDevices and get WM_INPUT message. The incoming data passes relative mouse movements not limited by the screen boundaries.


Q: Why java.util.Optional is not Serializable, how to serialize the object with such fields The Enum class is Serializable so there is no problem to serialize object with enums. The other case is where class has fields of java.util.Optional class. In this case the following exception is thrown: java.io.NotSerializableException: java.util.Optional
How to deal with such classes, how to serialize them? Is it possible to send such objects to Remote EJB or through RMI?
This is the example:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Optional;

import org.junit.Test;

public class SerializationTest {

    static class My implements Serializable {

        private static final long serialVersionUID = 1L;
        Optional<Integer> value = Optional.empty();

        public void setValue(Integer i) {
            this.i = Optional.of(i);
        }

        public Optional<Integer> getValue() {
            return value;
        }
    }

    //java.io.NotSerializableException is thrown

    @Test
    public void serialize() {
        My my = new My();
        byte[] bytes = toBytes(my);
    }

    public static <T extends Serializable> byte[] toBytes(T reportInfo) {
        try (ByteArrayOutputStream bstream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream ostream = new ObjectOutputStream(bstream)) {
                ostream.writeObject(reportInfo);
            }
            return bstream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

A: The Vavr.io library (former Javaslang) also have the Option class which is serializable:
public interface Option<T> extends Value<T>, Serializable { ... }

A: It's a curious omission.
You would have to mark the field as transient and provide your own custom writeObject() method that wrote the get() result itself, and a readObject() method that restored the Optional by reading that result from the stream. Not forgetting to call defaultWriteObject() and defaultReadObject() respectively.

A: This answer is in response to the question in the title, "Shouldn't Optional be Serializable?" The short answer is that the Java Lambda (JSR-335) expert group considered and rejected it. That note, and this one and this one indicate that the primary design goal for Optional is to be used as the return value of functions when a return value might be absent. The intent is that the caller immediately check the Optional and extract the actual value if it's present. If the value is absent, the caller can substitute a default value, throw an exception, or apply some other policy. This is typically done by chaining fluent method calls off the end of a stream pipeline (or other methods) that return Optional values.
It was never intended for Optional to be used other ways, such as for optional method arguments or to be stored as a field in an object. And by extension, making Optional serializable would enable it to be stored persistently or transmitted across a network, both of which encourage uses far beyond its original design goal.
Usually there are better ways to organize the data than to store an Optional in a field. If a getter (such as the getValue method in the question) returns the actual Optional from the field, it forces every caller to implement some policy for dealing with an empty value. This will likely lead to inconsisent behavior across callers. It's often better to have whatever code sets that field apply some policy at the time it's set.
Sometimes people want to put Optional into collections, like List<Optional<X>> or Map<Key,Optional<Value>>. This too is usually a bad idea. It's often better to replace these usages of Optional with Null-Object values (not actual null references), or simply to omit these entries from the collection entirely.

A: A lot of Serialization related problems can be solved by decoupling the persistent serialized form from the actual runtime implementation you operate on.
/** The class you work with in your runtime */
public class My implements Serializable {
    private static final long serialVersionUID = 1L;

    Optional<Integer> value = Optional.empty();

    public void setValue(Integer i) {
        this.value = Optional.ofNullable(i);
    }

    public Optional<Integer> getValue() {
        return value;
    }
    private Object writeReplace() throws ObjectStreamException
    {
        return new MySerialized(this);
    }
}
/** The persistent representation which exists in bytestreams only */
final class MySerialized implements Serializable {
    private final Integer value;

    MySerialized(My my) {
        value=my.getValue().orElse(null);
    }
    private Object readResolve() throws ObjectStreamException {
        My my=new My();
        my.setValue(value);
        return my;
    }
}

The class Optional implements behavior which allows to write good code when dealing with possibly absent values (compared to the use of null). But it does not add any benefit to a persistent representation of your data. It would just make your serialized data bigger…
The sketch above might look complicated but that’s because it demonstrates the pattern with one property only. The more properties your class has the more its simplicity should be revealed.
And not to forget, the possibility to change the implementation of My completely without any need to adapt the persistent form…

A: If you would like a serializable optional, consider instead using guava's optional which is serializable.

A: If you want to maintain a more consistent type list and avoid using null there's one kooky alternative.
You can store the value using an intersection of types. Coupled with a lambda, this allows something like:
private final Supplier<Optional<Integer>> suppValue;
....
List<Integer> temp = value
        .map(v -> v.map(Arrays::asList).orElseGet(ArrayList::new))
        .orElse(null);
this.suppValue = (Supplier<Optional<Integer>> & Serializable)() -> temp==null ? Optional.empty() : temp.stream().findFirst();

Having the temp variable separate avoids closing over the owner of the value member and thus serialising too much.

A: Just copy Optional class to your project and create your own custom Optional that implements Serializable. I am doing it because I just realized this sh*t too late.

A: the problem is you have used variables with optional. the basic solution to avoid this, provide the variable without optional and get them as optional when you call the getter like below. Optional<Integer> value = Optional.empty(); to  Integer value = null;
public class My implements Serializable {

        private static final long serialVersionUID = 1L;
        //Optional<Integer> value = Optional.empty(); //old code
        Integer value = null; //solution code without optional.

        public void setValue(Integer value ) {
           //this.value  = Optional.of(value); //old code with Optional
           this.value  = value ; //solution code without optional.
        }

        public Optional<Integer> getValue() {
            //solution code - return the value by using Optional.
            return Optional.ofNullable(value);
        }
}


Q: Coldfusion Parse URLs in text Can anyone help with a function that will parse all urls into valid html links in a text string?
For example:
"Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com"
would become:
"Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com"
What would be the best way to approach this. Regex (and if so, how?) or loop through each word in the text (would think that's less efficient)
Thanks

A: Again... there may be a more elegant regex...
Certainly feel free to google for "good" regex's for finding URLs if this one falls short.
<cfset myText = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com or at https://foo.com or http://123.com" />

<cfset myNewText = rereplaceNoCase( myText, '((http(s)?://)?((www\.)?\w+\.\w{2,6}))', '\1', 'all' ) />

A: This will parse URL in string that starts with http or www and terminated by a space
<cfset myString = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com">
<cfset URLinString = rereplaceNoCase(myString, '(((http(s)?://)|(www))\.?(\S+))', '\1', 'all')>


Q: TypeError: userAgent.toLowerCase is not a function While running Angular-unit test, using chrome browser, ended up with the error as
TypeError: userAgent.toLowerCase is not a function
    at _isAndroid (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:176:43)
    at new DefaultValueAccessor (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:227:38)
    at NodeInjectorFactory.factory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:254:1)
    at getNodeInjectable (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:3565:44)
    at instantiateAllDirectives (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:10318:27)
    at createDirectivesInstances (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9647:5)
    at ɵɵelementStart (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:14561:9)
    at templateFn (ng:///TodaysMarketMoversComponent.js:397:66)
    at executeTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9618:9)
    at renderView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9421:13)

Most wondering/confusing part to me- toLowerCase function has never been used through out the component/spec file.

A: It looks like the userAgent is being checked by the @angular/forms lib and has been deleted or not provided at all for some reason.
If it's not your code that's changing the userAgent then it's probably some third-party script.
If I were you I'd start with the latest additions in terms of libraries and dependencies and peel them back until I get a unit test running. That will give the clue.


Q: How can I change the CheckBox focus color on Android? I want to change the checkbox "outline" color, which is visible when focusing the checkbox in order to improve the visibility of the currently focused item when using the app with a keyboard or directional pad. How can I do that?
Image of what I mean:
Focused CheckBox on Android
Edit: After finding the correct wording ("ripple color") for what I mean, I managed to change it with:
<item name="colorControlHighlight">#00f</item>

But this only applies to unchecked checkboxes. Does anybody know how to apply it to all (also checked) checkboxes?
Image of colorControlHighlight effect on checked and unchecked checkboxes

A: Thanks to @special N9NE
This works: define an own ripple ripple_bg.xml:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/accent_26" />

And set it as background (globally):
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.DayNight">
        <!-- ... -->

        <!-- custom checkbox style to improve visibility on special (TV) devices -->
        <item name="android:checkboxStyle">@style/MyCheckBoxStyle</item>
    </style>

    <style name="MyCheckBoxStyle" parent="Widget.AppCompat.CompoundButton.CheckBox">
        <item name="android:background">@drawable/ripple_bg</item>
    </style>
</resources>

A: You can check this blog: AppCompat themes
colorControlHighlight is for ripple color

So try to create a ThemeOverlay.AppCompat theme where you will set the value of the color that you want and that will allow you to change the ripple color for that view and its children.
To target ripple in theme use this attribute:

android:colorControlHighlight

A: you can use the theme attribute:
app:theme="@style/MyCheckboxStyle"

then add this in your style.xml file :
<style name="MyCheckboxStyle" parent="AppTheme">
    <item name="colorAccent">@color/colorAccent</item>  // color when checkbox is checked
    <item name="android:textColorSecondary">@color/colorSecondary</item>  // when it is unchecked
</style>


Q: Go: How can I "unpack" a struct? I have a struct:
type mystruct struct {
    Foo string
    Bar int
}

I'd like to create SQL insert statements from the struct which have the following form:
m := mystruct{ "Hello" , 1 }
query := "INSERT INTO mytbl ( foo, bar ) VALUES ( ?,? )"
res,err := db.Exec(query, m.Foo, m.Bar)

Now my question is: how can I make the last line dynamically from the struct (or m) itself? I am able to get the struct names using reflect, but I don't know how to create the []interface{} slice for the db.Exec() call. This is what I have tried: (http://play.golang.org/p/GR1Bb61NFH)
package main

import (
    "fmt"
    "reflect"
)

type mystruct struct {
    Foo string
    Bar int
}

func main() {
    m := mystruct{"Foo", 1}
    fmt.Println(readNames(m))
    x := unpackStruct(m)
    fmt.Printf("%#v\n", x)
}

func unpackStruct(a interface{}) []interface{} {

    // "convert" a to m t

    // doesn't work, from 'laws of reflection'
    s := reflect.ValueOf(&t).Elem()
    typeOfT := s.Type()
    for i := 0; i < s.NumField(); i++ {
        f := s.Field(i)
        fmt.Printf("%d: %s %s = %v\n", i,
            typeOfT.Field(i).Name, f.Type(), f.Interface())
    }

    // this is in principle what I want:
    m := mystruct{"Hello", 2}
    var ret []interface{}
    ret = make([]interface{}, s.NumField())
    ret[0] = m.Foo
    ret[1] = m.Bar
    return ret
}

// works fine:
func readNames(a interface{}) []string {
    s := reflect.TypeOf(a)
    lenStruct := s.NumField()
    ret := make([]string, lenStruct)

    for i := 0; i < lenStruct; i++ {
        ret[i] = s.Field(i).Name
    }
    return ret
}

A: If getting the values of the fields is your issue, this code snippet should help:
s := reflect.ValueOf(a)
ret := make([]interface{}, s.NumField())
for i := 0; i < s.NumField(); i++ {
    ret[i] = s.Field(i).Interface()
}

A: If creating the []interface{} value is your problem, using reflect's slice creation mechanisms should work nicely:
slc := reflect.MakeSlice(InterfaceType, len, cap) // See the link below for creating InterfaceType
slc.Index(0).Set(TargetValue)
return slc.Interface()

(Here's the above-mentioned link).
Modifying the above code to loop over the values in the struct instead of just the 0th index shouldn't be too bad.


Q: Python mysql.connector select without locked rows from transactions I'm currently working on a Project with MySQL-based Jobworkers. In order for them to fetch a new Job i ran into a problem with row locking:
On Native MySQL (ran 2 terminals and executed following):
SELECT id FROM `data` WHERE `status`=0 ORDER BY `created_at` LIMIT 20 FOR UPDATE SKIP LOCKED;

The Select does not lock the rows what so ever (intended to be this way & what I want)
But running the exact same in Python:
import mysql.connector

class DB:
    def __init__(self):
        self.conn = mysql.connector.MySQLConnection(
            host     = "localhost",
            database = "test"
        )

-------------------------

db = DB()
cursor = db.conn.cursor()
cursor.execute("SELECT id FROM `data` WHERE `status`=0 ORDER BY `created_at` LIMIT 20 FOR UPDATE SKIP LOCKED")

Locks all selected Rows even tho no Transaction was ever started for all other Python connections + Native selects in Terminal.
What am I missing here?
Basically all I want is a select to skip locked rows from Python.
Cheers.
Tried enabling autocommit with:
db = DB()
db.autocommit = True

Also tried:
mysql.connector.MySQLConnection
mysql.connector.connect


Q: How to call static func by passing $_GET params? i have got a static function> which is called
regenerateThumbnailsCron()
And I would like to execute this function by GET params, for example>
if($_GET["pass"]=="password")
self::regenerateThumbnailsCron();

But if I tryied to call this function in constructor>
class AdminImages extends AdminTab
...
 public function __construct()
 {
    if($_GET["pass"]=="password")
    self::regenerateThumbnailsCron();
}

I cannot execute this function.
Is any way, how to call this function before __construct to correctly execute?
Thanks very much for any advice.
EDIT>
I tried also with public function>
<?php
include 'AdminImages.php';

$images = new AdminImages();
$images->regenerateThumbnailsCron();

?>

But i got error>
Fatal error: Class 'AdminTab' not found

A: You need to do a include 'AdminTab.php'; as well, since your class extends that

A: Not completely sure I understand your question, are you saying that you have static class "B" which extends class "A", "A" having your regenerateThumbnailsCron() method which you want to call before anything else?
If so then try this:
<?php
class A {
  private function regenerate() {
  .... do something ....
  }
}

class B extends A {
  function __construct() {
    if ($_GET["pass"] == "password") {
      parent::regenerate();
    }
  }

  function regenerateThunbnailsCron() {
  .... do somethinig ....
  }

}

$images = new B();
$images->regenerateThumbnailsCron();
?>

This way, your parent's "regenerate()" function would get called during the constructor.  You can switch this around to be a static class if you want, which if your goal is to compartmentalise any variables and functions away from the global scope would be a better way.


Q: SetProperty of "SelectedItem is not supported on control type: Window while trying to select an item from combo box in windows application error message showing

"SetProperty of "SelectedItem" is not supported on control type: Window"

A: The problem is that you are calling an instance of class Window but not ComboBox. I see to possible reasons why this happens. Either you are referring to the wrong ui property from UIMap or Coded UI Test Builder recorded wrong element or not the whole hierarchy of your wanted test control.
Moreover, if you are trying to select an item in combobox, then just use
comboBox.SelectedIndex = 3; // to select an item by its zero-based index
comboBox.SelectedItem = "Item Text"; // to select an item by its text

If it does not help, provide additional information on the problem, particularly on the technology of your Windows Application (UIA/WPF or MSAA/WinForms).


Q: Java 8 how to check null values and get List of object? I've a below code written in Java and I wanted to use in Java 8. How can I do that?
Below code is within method:
Query query = new Query();
query.fields().include("address");
query.fields().exclude("_id");

List<User> users = mongoTemplate.find(query, User.class);

List<Address> addresses = new ArrayList<>();
if(!users.isEmpty()) {
    for (Address address : addresses) {
        addresses.addAll(country.getSubaddress());
    }
}
return address;

in Java 8
List<List<Address>> values = countries.stream().filter(Objects::nonNull).map(x -> x.getAddresses()).collect(Collectors.toList());

I only want List of Address. How can I do that ?

A: This is one way of solving the problem:
List<Address> addresses = Optional.ofNullable(users)
            .orElseGet(Collections::emptyList)
            .stream()
            .filter(Objects::nonNull)
            .flatMap(x -> x.getAddress().stream())
            .collect(Collectors.toList());


Q: How to continously deploy a feature to karaf? I want to continously deploy a feature to ServiceMix 6.0, which is based on Karaf 3.0.4.
I first tried this using the karaf console. However there are some problems. It is for a standard karaf installation not possible to determine on the karaf console if a feature is already installed (see my other question on this). The other problem with the karaf console is that it doesn't support exit codes. So it is not possible to determine reliably if a feature installation was successfully finished.
I then installed hawtio and tried to use the exposed JMX beans via jolokia/REST that is bundled with hawtio. The problem here is that karaf 3.0.x is unable to update a feature. Therefore features must be uninstalled first. However the FeatureService only offers the possibility to uninstall an explicitly specified feature. But when a previous version of the feature was installed, subfeatures were installed with it. They also need an upgrade and therefore be uninstalled first. So I would need a way to iterate over the subfeatures of a feature, which I do not have.
So how can continous deployment of features to karaf 3.0.x be done?

A: The first try we have implemented is a bash script. The biggest problem is uninstalling the old version. Therefore we have set up a convention for the names of the feature and it's subfeatures. So we can use the following to find already installed features:
features=$(echo "feature:list" | ssh -p $smx_ssh_port $smx_user@$smx_host | grep -h "<feature-name-convention-regex>.*|.*x.*|" | cut -f1 -d" " | tr '\n' ' ')

This can then be passed to feature:uninstall and can also be used for detecting if features were installed after the call to feature:repo-add -i.
The remaining problem is that we are unable to reference 3rd-party subfeatures because they won't be uninstalled when an updated version needs to be installed and we can't be sure if all of the subfeatures have been successfully installed.

A: For karaf 3 there is no good way to update features.
This is already a little better for karaf 4. It allows to update a feature repo and you can then simply install the feature again. It will detect that the feature has changed and do the necessary changes in bundles.


Q: Using cuda thrust::max_element to find max element in array returns incorrect sometimes I have a 2^20 element array being filled on the device; these numbers should be the same every time.
I then move that array over to the host and then search for the max element in the array, this technique works with 2^10 element array but once I begin to get any larger than that I begin to get random answers not sure if thrust is messing up or the device calculations.
The answer max_element should return is 0.094479 usually the first time the program is run the code will output the correct answer then the answer will randomly show up every few times
GPU is tesla k20 running 5.0 also tested on 780GTX; same issue both times
//Host Code
int main( void ) {
    float h_c[TOTAL];
    float *d_c;

    cudaMalloc((void**)&d_c, sizeof(float)*TOTAL);

    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start);

    //Number of threads
    kernel<<<BLOCKS,THREADS>>>(d_c);

    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    float mil = 0;
    cudaEventElapsedTime(&mil, start, stop);

    cudaMemcpy(h_c, d_c, sizeof(float)*TOTAL, cudaMemcpyDeviceToHost);

    for(int y = 0; y < TOTAL; y++){
        printf(" %d: Host C: %f \n",y, h_c[y]);
    }
    float *result = thrust::max_element(h_c, h_c + TOTAL);
    printf("Max is: %f \n", *result);
    printf("Time:  %f \n", mil/1000);
    printf("THREADS:  %d \n", THREADS);
    printf("BLOCKS:  %d \n", BLOCKS);
    printf("TOTAL:  %d \n", TOTAL);
    cudaFree(d_c);
    cudaDeviceReset() ;
    return 0;
}

Device Code
#include <thrust/extrema.h>
#include <math.h>
#include <stdio.h>

#define ARRAYSIZE 15
#define THREADS 1024
#define BLOCKS 32
#define TOTAL THREADS * BLOCKS

__global__ void kernel(float *cc){

//Get thread for summing all elements
int threadId = threadIdx.x + blockDim.x * blockIdx.x;

int decimalNumber,quotient;
//Size of the array
//const int size = 10;
//Holds the binary number in an array
int binaryNumber[ARRAYSIZE];
int i = 0;

int a[ARRAYSIZE] = {1192, 1315, 1462, 1484, 1476, 1443, 1508, 1489, 1470, 1573, 1633, 1539, 1600, 1707, 1701};//, 1682, 1688, 1681, 1694, 1728};
int b[ARRAYSIZE] = {1162, 1337, 1282, 1491, 1508, 1517, 1488, 1513, 1539, 1576, 1626 ,1634, 1573,    1786, 1741};//, 1782, 1755, 1669, 1700, 1826};

//Holds Product from the dot product
int c[ARRAYSIZE];
//Arrays to hold integers to be summed
int aSumArr[ARRAYSIZE];
int bSumArr[ARRAYSIZE];

for(int i = 0; i < ARRAYSIZE; i++){
    c[i] = 0;
    aSumArr[i] = 0;
    bSumArr[i] = 0;
}

//Holds the value for the dot product
int dotSum = 0;
//Holds sum of valid array positions for array a
int aSum = 0;
//Holds sum of valid array positions for array b
int bSum = 0;

//Holds the Value of the arcCos of the dot product / sqrt(array a) * sqrt(array b)
float finalValue = 0;
//printf("ThreadID: %d \n", threadId);
//ALL 1's 1048575 = Threads
decimalNumber = threadId;
//printf("decimal number:  %d \n", decimalNumber);

quotient = decimalNumber;
//Loop to convert decimal into binary and store in array
while(quotient!=0){

    binaryNumber[i++]= quotient % 2;

    quotient = quotient / 2;

}

//Test if conversion from decimal to binary is complete and correct
//printf("Equivalent binary value of decimal number %d: \n",decimalNumber);

//for(int in = size-1; in >= 0;in--){
  //printf("Index: %d | binary number:  %d ----  a:%d || b: %d\n",in,binaryNumber[in],a[in],b[in]);
//}
//printf(" \n ");

//Loop through binaryNumber array
for(int x = ARRAYSIZE-1 ; x >= 0; x--){
    //If index is == 1 Perform calculation
    if(binaryNumber[x] == 1){
        //Multiply numbers at good index
        c[x] = a[x] * b[x];
        //Fill sum arrays at correct index
        aSumArr[x] = a[x];
        bSumArr[x] = b[x];

        //Checks if the loop is executing correctly
        //sumArray[x] = 1;
        //printf("Multiplied - %d * %d = %f\n", a[x], b[x], c[x]);
        //printf("--This should not be run --\n");
    }else{
//          printf("SKIPPED - %d * %d = %f\n", a[x], b[x], c[x]);
    }

}

//Sums up the product array to complete dot product
for(int j = 0; j < ARRAYSIZE; ++j){
    dotSum += c[j];
    //printf("aSumArr %d \n", aSumArr[j]);
    //printf("bSumArr %d \n", bSumArr[j]);
    aSum += powf( aSumArr[j], 2 );
    bSum += powf( bSumArr[j], 2 );
//      printf("aSum: %d +  aSumArr %d \n", aSum, aSumArr[j]);
//      printf("bSum: %d +  bSumArr %d \n", bSum, bSumArr[j]);
}

//printf("\n");
//Print out the dot prudct
//printf("Dot product is: %d \n", dotSum);
//printf("aSum is: %d \n", aSum);
//printf("bSum is: %d \n", bSum);

float sqSum1 = sqrtf(aSum);
float sqSum2 = sqrtf(bSum);
// printf("sqSum1: %f \n", sqSum1);
// printf("sqSum2: %f \n", sqSum2);
float sqSum = sqSum1 * sqSum2;
// printf("sqSum %f \n", sqSum);
float div = dotSum / sqSum ;
// printf("div: %f \n", div);
finalValue = acosf( div ) ;

//Stores the threads final value in array cc, in the respected index
if(finalValue == finalValue){
    cc[threadId] = finalValue;
}else{
    cc[threadId] = -2;
}
//printf("final value is: %f for number %d \n", finalValue, threadId);
}

A: It seems to be a case of using improperly initiialized/uninitialized variables.
After I added the following line:
for(int i = 0; i < ARRAYSIZE; i++){
    c[i] = 0;
    aSumArr[i] = 0;
    bSumArr[i] = 0;
    binaryNumber[i] = 0; // add this line
}

I was no longer able to reproduce the issue.


Q: Set background color of NSWindow with appearance set I am using the following code on my NSWindow so that all my buttons, pop ups, etc. are in a dark mode tint:
[self.window setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];

But I want to set a custom window background color instead of the black color which is set as default for the Vibrant Dark Appearance. Calling this line without the appearance works otherwise fails to set:
self.window.backgroundColor = [NSColor colorWithPatternImage:[NSImage imageNamed:@"backgroundColor"]];

Any ideas?

A: Just add a view with a background color and use It as your window's background.
Take a look at this sample app.


Q: How to run angular test using Cloud Build? I use out-of-the-box Angular testing framework: Jasmine and karma for Unit Test and GCP Cloud Build to deploy the app. However, there is a problem in testing because there is no Chrome installed for the node Docker image.
What is the best way to handle that? Create a customized docker image? Or is there any well-known docker image I can leverage for build and test Angular app in Cloud Build?
cloudbuild.yaml
steps:
  # Install
  - name: node:14
    entrypoint: npm
    args: ["install"]
  #Build
  - name: node:14
    entrypoint: npm
    args: ["run", "build", "--", "--aot"]

  # Test <- This step fails. See the error message below
  - name: node:14
    entrypoint: npm
    args: ["run", "test", "--", "--watch=false"]

  # Deploy to Firebase
  - name: gcr.io/$PROJECT_ID/firebase
    args: ["deploy", "--project=$PROJECT_ID", "--only=hosting"]

Error
Already have image: node:14

> carealth@0.0.0 test /workspace
> ng test "--watch=false"

- Generating browser application bundles (phase: setup)...
18 01 2022 19:22:45.740:INFO [karma-server]: Karma v6.3.11 server started at http://localhost:9876/
18 01 2022 19:22:45.744:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
18 01 2022 19:22:45.749:INFO [launcher]: Starting browser Chrome
18 01 2022 19:22:45.756:ERROR [launcher]: No binary for Chrome browser on your platform.
  Please, set "CHROME_BIN" env variable.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! carealth@0.0.0 test: `ng test "--watch=false"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the carealth@0.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /builder/home/.npm/_logs/2022-01-18T19_22_45_880Z-debug.log

A: If you need headless chrome in your container, choose a container with node14 and headless chrome installed. I found this one with Chrome 89 and released 10 months ago. You could find better source I guess
Else, you can use your node:14 container and, if it's possible, install headless Google Chrome on it (something like that, install work, but I haven't node file to test on it to validate completely that example)
  - name: node:14
    entrypoint: bash
    args:
      - -c
      - |
        wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
        apt update && apt install -y libappindicator1 fonts-liberation ./google-chrome-stable_current_amd64.deb
        npm run test -- --watch=false


Q: What is on my heap? C linux So I called malloc(1024) today to just play around with the heap. I for the most part understand the structure of the heap, so when I printed out what was in memory, I wasn't surprised to see "00000000 00000409 00000000 00000000 ...."
however 1032 bytes later, I expected to find the top chunk of the heap. Instead I found another chunk as if another call of malloc(1024) had happened after my initial one.
In this chunk is the following:
00000000 00000409 30387830 65336234
30203a30 30303030 20303030 30303030
30303030 30303020 30303030 30302030
34303030 33203930 33303330 20303330
30333033 30333032 33343320 33303330
33332030 39333032 000a3233 00000000

which translates to:
08x0e3b40 :00000 00000000000000 000000 040003 903030 03003030302343 303033#09302
23

Does anyone know why this exists? I am sure I am only calling malloc once. And it always seems to be there no matter what size I malloc.

A: malloc reservers a particular amount of memory on the heap and gives back a pointer to this memory block (or NULL, if it was not able to allocate the desired memory block). Note, however, that malloc will not initialise the memory block in any way. It will not fill it with 0 or any other value; it will simply keep it's content as is.
So the question is actually "what is the initial content of the heap when a program starts?". And the answer is: it depends on the operating system, which portion of memory it assigns to a program when executed, and the content of this memory block is very likely to be just "something undefined", not even random. This can be some recurring patterns of values, it can be zeros, it can be everything.
When you look into different portions of a program's heap, you will probably see this "something undefined" content, regardless of whether you have used malloc before or not. You may see recurring patterns as in your case. Note, however, that "looking into" portions of the heap that have not been allocated before is actually undefined behaviour.


Q: Recursively update a State Monad this question is related to this question
I have a state monad. An object provides an update function as in the OOD strategy pattern.

*

*The choice of having a object is that in real, production code, the
class provides an array of operations, all sharing state through the
monad. Inheritance helped me extend the basic functionality and
further customizing the class providing the operations.

*The choice of having a monad instead of a mutable property within the class is that the monad, through proper use of generics, is helping me abstracting and being more flexible on what variables/information must be carried along the computation as "state".

I have a simple toy example:
/////////////////////////////////////////////////////////////////////////////////////
// Definition of the state
/////////////////////////////////////////////////////////////////////////////////////
type StateFunc<'State, 'T> = 'State -> 'T * 'State

/////////////////////////////////////////////////////////////////////////////////////
// Definition of the State monad type
/////////////////////////////////////////////////////////////////////////////////////
type StateMonadBuilder<'State>() =

    // M<'T> -> M<'T>
    member b.ReturnFrom a : StateFunc<'State, 'T> = a

    // 'T -> M<'T>
    member b.Return a : StateFunc<'State, 'T> = ( fun s ->  a, s)

    // M<'T> * ('T -> M<'U>) -> M<'U>
    member b.Bind(p : StateFunc<_, 'T>, rest : 'T -> StateFunc<_,_>) : StateFunc<'State, 'U>  =
        (fun s ->
            let a, s' = p s
            rest a s')

    // Getter for the whole state, this type signature is because it passes along the state & returns the state
    member b.getState : StateFunc<'State, _> = (fun s -> s, s)

    // Setter for the state
    member b.putState (s:'State) : StateFunc<'State, _> = (fun _ -> (), s)

let runState f init = f init

/////////////////////////////////////////////////////////////////////////////////////
// STRATEGY PATTERN
/////////////////////////////////////////////////////////////////////////////////////

let state = StateMonadBuilder<int> ()

// DoubleFunctOne defines standard operations that remain always the same
type Strategy (aFunction) =
    member this.Update (x: int) = state {
        let! currState = state.getState
        let processedx = aFunction x
        do! state.putState (currState + x) }

// Create a function that customizes the strategy
let myFunction x =
    2 * x

// Customize the strategy with the desired function:
let strategy = Strategy (myFunction)

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Update recursively
/////////////////////////////////////////////////////////////////////////////////////////////////////////

// ?? How to run update recursively ??
let result initialCondition =
    initialCondition
    |> (for i = 10 to 100 do
            yield state { do! strategy.Update i } )

My goal is to apply the initial conditions, fetch data and launch recursively (within a for or a while loop or even some functional operation) the functions provided by strategy. Working with the monad, I am not sure how to do this.
Thank you.
Computational Expression For
Inspired by @kvb answer, I have added a for method to the computational expression.
// Loops through seqnc of numbers that constitute an input to func
member b.For (seqnc:_ List, func) =
    seqnc
    |> List.map (fun item -> func item)
    |> List.reduce (fun acc item ->
            (fun s ->
                let _, s' = acc s
                item s' ) )

I run a few tests and I have the impression that this one works.
Thanks.

A: Something like this?
let result initialCondition =
    let rec loop = function
    | 101 -> state { return () }
    | i ->
        state {
            do! strategy.Update i
            do! loop (i+1)
        }
    initialCondition
    |> runState (loop 10)

Alternatively, define a For member on your builder and write it the more imperative way:
let result initialCondition =
    let f = state {
        for i in 10 to 100 do
            do! strategy.Update i
    }
    initialCondition
    |> runState f

Also, note that there is likely a bug in your definition of Strategy.Update: processedx is bound but unused.


Q: Linq to sql Distinct after join I have a join query and i want to filter the result of this query by using distinct. I want to get only one of the shoes which has same brand, model, primary color and secondary color. How can i make this ? Here is my join query.
var query = from b in db.BrandTbls.AsQueryable()
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
            where s.Quantity > 0
            orderby m.ModelName
            select new
            {
                s.ShoeID,
                m.ModelName,
                m.Price,
                b.BrandName,
                i.ImagePath
            };

A: I found the solution. This query does approximately what i want to do
            var query = from b in db.BrandTbls.AsQueryable()
                    join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
                    join s in db.ShoeTbls on m.ModelID equals s.ModelID
                    join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
                    group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.ShoeID,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g
                    select new {g.Key.ShoeID,g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price};

A: Remove price from the output and use Distinct() like this:
var query = (from b in db.BrandTbls.AsQueryable()
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
            where s.Quantity > 0
            orderby m.ModelName
            select new
            {
                s.ShoeID,
                m.ModelName,
                b.BrandName,
                i.ImagePath
            }).Distinct();


Q: API call in ReactJS and setting response to state I have an array with ids like
[123,345,212,232.....]
I have a Rest API that responds the particular product with respect to an id .
So in ReactJS, how would I loop through the array and get the products and store in state
I tried doing this in useEffect{running once as in componentDidMount} but it only stores the first product in array.
Are there better ways to accomplish this?
My Actual Code that has the problem is
useEffect(() => {
    const getBought = async () => {
        user.bought.map(async (boughtID) => {
          let bought = await get(`/bought/${boughtID}`, {}, true);
          let boughtDate = bought.createdAt.slice(0, 10);

          bought.products.map(async (pr) => {
            let product = await get(`product/${pr.product}`);
            let quantityBought = pr.quantity;

            setAllBoughts({
              ...allBoughts,
              [boughtDate]: [
                ...(allBoughts.boughtDate || []),
                {
                  product,
                  quantityBought,
                },
              ],
            });
          });
        });
    };
    getBought();
  }, []);

So I have a user which has arrays of boughtIds in bought key...
so I am looping throughout those bought keys
A bought schema has products which has product id and number of product bought (pr.product and pr.quantity).. So I am hitting the API , and save all the products in a state object.
so allBoughts is state which is an object that has keys as (dates) as in the code .createdAt.slice(0,10) which gives me date removing rest of stuffs mongodb added.
But everytime I do it, there are few things that happen.
Either only the first item is saved, and rest are not
Either the same item gets overwritten
or the page reloads infinitely(especially whrn I try to remove dependency array from useEffect)

A: setAllBoughts({
  ...allBoughts,
  [boughtDate]: [
    ...(allBoughts.boughtDate || []),
    {
      product,
      quantityBought,
    },
  ],
});

allBoughts is the state that existed when this effect ran. Ie, it's the empty state, with no results in it yet. So every time a result comes back, you are copying the empty state, and adding one entry to it. This erases any results you have.
Instead, you need to use the most recent version of the state, which you can do with the function version of set state:
setAllBoughts(prevState => {
  return {
    ...prevState,
    [boughtDate]: [
      ...(prevState.boughtDate || []),
      {
        product,
        quantityBought,
      },
    ],
  };
})

A: From what you're saying, it seems to me that you're erasing the previous stored result in the state (You get result for id 123, store it, then result of 345, store it and erase the previous value). Or you're just not looping through the array.
Here is an example of how to GET multiple times in a useEffect and assign all the results in the state.
Fully working example at Codesandbox
export default function App() {
  const ids = useRef([1, 3, 5]);
  const [items, setItems] = useState([]);

  useEffect(() => {
    const promises = ids.current.map((id) => fetchData(id));

    Promise.all(promises).then((responses) => {
      setItems(responses);
    });
  }, []);

  async function fetchData(id) {
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/posts/${id}`
    );
    return response.json();
  }

  return (

      {items.map((item) => (

          {item.id} - {item.title}

      ))}

  );
}


Q: How do I prefix my log messages with the current date and time? I'm using Python 3.9 and Django 3.2. I have logging configured in my settings.py file
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}

When I do logging in one of my classes, I do it like so
import logging
...
class TransactionService:
    def __init__(self):
        self._logger = logging.getLogger(__name__)

    def my_method(self, arg1, arg2):
            ...
        self._logger.info("Doing some logging here.")

How do I configure my logger such that when the message is printed out, it is prefixed by the current date and time?

A: This worked for me (adapted from thorndeux's answer):
import logging.config

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'prepend_date': {
            'format': '{asctime} {levelname}: {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'prepend_date',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}

logging.config.dictConfig(LOGGING)
logging.info('foo')
logging.warning('bar')

prints
2021-11-28 16:05:13,469 INFO: foo
2021-11-28 16:05:13,469 WARNING: bar

A: Add a formatter to your logger. For example:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'prepend_date': {
            'format': '{asctime} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'prepend_date',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}

A: The answer to your question can be found in the official documentation, please read the full article.
import logging

FORMAT = '%(asctime)s  %(message)s'
logging.basicConfig(format=FORMAT)

logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info("Doing some logging here.")

This would print:
2021-11-29 14:06:59,825  Doing some logging here.

A: What is missing in your example is formatters (add to LOGGING dict following):
LOGGING = {
    ...
    "formatters": {"console": {"format": "%(asctime)s %(message)s"}},
    # and add it to handlers
    "handlers": {"console": {"class": "logging.StreamHandler", "formatter": "console"}},
    ...
}

Another thing that you may want to change logging setup in classes to something like
import logging
logger = logging.getLogger(__name__)
...
class TransactionService:

    def my_method(self, arg1, arg2):
        ...
        logger.info("Doing some logging here.")

You can also find full example in official Django documentation (last of examples in that subsection):
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'filters': {
        'special': {
            '()': 'project.logging.SpecialFilter',
            'foo': 'bar',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['special']
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
        'myproject.custom': {
            'handlers': ['console', 'mail_admins'],
            'level': 'INFO',
            'filters': ['special']
        }
    }
}


Q: jQuery FullCalendar Plugin not Showing Events I'm using the FullCalendar plugin in a CodeIgniter application.  I'm retrieving event objects with a GET request server side and the events do not show on the calendar using a similar approach to the events as a function example with a callback.  I have verified that the GET request returns json properly.
Here is the json returned by my request...
[{"id":"1","title":"2011 Acura Integra (1)","start":1313996400,"color":"red"}, {"id":"15","title":"2011 Acura Integra (1)","start":1314774000,"color":"red"}]

My call is as follows...
    var year = $("#year").text();
    var month = $("#month").text();

    $maintenance_schedule_calendar_table = $("#vehicles_maintenance_schedule_calendar").fullCalendar({
        year: year,
        month: month -1,
        header: {
            left: 'prev,next today',
            center: 'title',
            right: ''
        },
        editable: true,
        disableResizing: true,
        events: function(start, end, callback) {
            var start_timestamp = Math.round(start.getTime() / 1000);
            var end_timestamp = Math.round(end.getTime() / 1000);
            var url = "/tripsys/new_admin/vehicles/get_maintenance_schedule_data/" + start_timestamp + "/" + end_timestamp;

            $.get(url, function(events) {
                callback(events);
            });
        }
    });

The strange thing is that the previous call fetches the json properly and the callback seems to process the events because if I call the .fullCalendar('clientEvents') it shows the json that I passed into the events method, but they do not render.
However if I pass this same json into my initial FullCalendar call directly the events do render...
    var year = $("#year").text();
    var month = $("#month").text();

    $maintenance_schedule_calendar_table = $("#vehicles_maintenance_schedule_calendar").fullCalendar({
        year: year,
        month: month -1,
        header: {
            left: 'prev,next today',
            center: 'title',
            right: ''
        },
        editable: true,
        disableResizing: true,
        events: [
            {"id":"1","title":"2011 Acura Integra (1)","start":1313996400,"color":"red"},
            {"id":"15","title":"2011 Acura Integra (1)","start":1314774000,"color":"red"}
        ]
    });

Does anyone have any idea why the first example is not rendering the events on my calendar?

A: Turns out that the problem was caused by me requesting the data with $.get instead of with $.getJSON
This is the correct call...
    var year = $("#year").text();
    var month = $("#month").text();

    $maintenance_schedule_calendar_table = $("#vehicles_maintenance_schedule_calendar").fullCalendar({
        year: year,
        month: month -1,
        header: {
            left: 'prev,next today',
            center: 'title',
            right: ''
        },
        editable: true,
        disableResizing: true,
        events: function(start, end, callback) {
            var start_timestamp = Math.round(start.getTime() / 1000);
            var end_timestamp = Math.round(end.getTime() / 1000);
            var url = "/tripsys/new_admin/vehicles/get_maintenance_schedule_data/" + start_timestamp + "/" + end_timestamp;

            $.getJSON(url, function(events) {
                callback(events);
            });
        }
    });


Q: Bootstrap MultiSelect Options list need to hide while scroll the window

<!DOCTYPE html>

<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>

<select id="multi-select-demo" multiple="multiple">
    <option value="jQuery">jQuery tutorial</option>
    <option value="Bootstrap">Bootstrap Tips</option>
    <option value="HTML">HTML</option>
    <option value="CSS">CSS tricks</option>
    <option value="angular">Angular JS</option>
</select>

In multiselect, we have a bunch of options. These options need to hide while user scrolls the window. The list is contained in a ul with class name "multiselect-container".

A: Triggering a click outside the element should do the trick.
$(document).click();
There is no official way to 'close' the bootstrap dropdown, however, the above one is a workaround to handle that. It basically triggers a fake click outside the dropdown, therefore, closing it.
If you want it to close every time user starts scrolling, then:
$(window).on('scroll',function(){
    $(document).click();
});

A:

var prev = 0;
var $window = $(window);
var nav = $('.nav');

$window.on('scroll', function(){
  var scrollTop = $window.scrollTop();
  nav.toggleClass('hidden', scrollTop > prev);
  prev = scrollTop;
});
@import bourbon

body
  font-family: helvetica neue, helvetica, arial, sans-serif
  height: 8000px

.nav
  background: #111
  text-align: center
  color: #fff
  +padding(20px null)
  +position(fixed, null 0px 0px 0px)
  +transition(transform 1s $ease-in-out-quint)

.nav.hidden
  +transform(translateY(100%))

p
  margin: 0
  +padding(20px)

Scroll to show/hide this bar!

They see me scrolling...

A: <!DOCTYPE html>

    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css"
          rel="stylesheet"/>

        <select id="multi-select-demo" multiple="multiple">
            <option value="jQuery">jQuery tutorial</option>
            <option value="Bootstrap">Bootstrap Tips</option>
            <option value="HTML">HTML</option>
            <option value="CSS">CSS tricks</option>
            <option value="angular">Angular JS</option>
        </select>


Q: Bootstrap responsive: How to fix a non-responsive element? I've enabled the responsive feature in twitter bootstrap, using nested fluid grid. When viewed on small mobile, every single spans are stacked. However, I'd like to keep the "maincontent" unstacked and shown in horizontal layout. I've tried display:inline-block; and min-width but both didn't work. Any recommendations? Thank you.

2

8

2

A: Give something like this a shot:

2

8

2

            sidebar

You'll want to tweak and play with the % to fit your needs, and eventually move those inline styles out into a stylesheet. You may need to slap !important on them to keep them from being overriden by the fluid twitter bootstrap classes. The reason they were stacking with your setup is that the fluid styles took over despite the non-fluid container/row classes you used, and changed them to float: none, width: 100%; display: block divs.


Q: YouTubeAPI v3 - "Daily Limit Exceeded" error before my app reaches API quota limit Daily, between 11:00PM and 2:00AM EDT, my requests to the YouTube v3 API start failing the "dailyLimitExceeded" error, status code 403. The error always stops at 3:00AM EDT. My app hasn't actually yet reached the 50,000,000 units limit. Any idea why this could be happening?
{
    "error": {
        "errors": [
            {
                "domain": "usageLimits",
                "reason": "dailyLimitExceeded",
                "message": "Daily Limit Exceeded"
            }
        ],
        "code": 403,
        "message": "Daily Limit Exceeded"
    }
}

This started occurring on May 19th, though my app's API usage hasn't really changed since a few weeks before the 19th. Since the issue started, the most API units my app has used is 44,995,660 out of the allowed 50,000,000. The app usually ends each day between 42,000,000 and 45,000,000 units used. My per-user-limit is 3,000 requests/second/user (I highly doubt the API calls from my users are that dense this late at night).
Any ideas on why this could be happening would be greatly appreciated.
EDIT: I should note that this doesn't affect all of my users when it happens (I believe less than half), many are able to continue using the app without issue while others are receiving the error.

A: YouTube Data API Errors -> Global Domain Errors

dailyLimitExceeded402 A daily budget limit set by the developer has
  been reached.

Billing status
This API is limited by the free quota shown below.   Apply for higher quota

Quota summary
     Daily quota resets at midnight Pacific Time (PT).
  Free quota  50,000,000 units/day
  Remaining   50,000,000 units/day   100% of total
  Per-user limit 3,000 requests/second/user

The current quota displayed to you in the Google Developer console is a estimate it is not 100% accurate.  If you are getting the error dailyLimitExceeded it means that you have reached your limit for the day and will have to wait until midnight PT time to run again.    This is something you can test by running the request again and seeing that suddenly you have access again.
You need to either extend your quota or reduce the number of requests you make.


Q: Exception in thread "main" cucumber.runtime.CucumberException I am getting Exception in thread:
Exception in thread "main" cucumber.runtime.CucumberException: No back ends were found. Please make sure you have a backend module on your CLASS PATH.

I am new for Cucumber BDD framework ,running following feature file.
Feature: feature to test login scenario

Scenario: Check login is successful with valid credentials
Given User is on login page
When User enters login and password
And Clicks on login button
Then User navigated to home page

I have added following dependencies, tried with different adding version, but still not working.
Kindly provide your help.


Q: how to find draggable product related values name, price I have tried drag and drop using jquery UI , i have updated this into fiddle
JSFIDDLE:
http://jsfiddle.net/GPBUn/
JQUERY CODE:
//draggable start
            $(function () {

        // jQuery UI Draggable
                $(".products-grid .item a img").draggable({

                    // brings the item back to its place when dragging is over
                    revert:true,

                    // once the dragging starts, we decrease the opactiy of other items
                    // Appending a class as we do that with CSS
                    drag:function () {
                        $(this).addClass("active");
                        $(this).closest(".products-grid .item a img").addClass("active");
                    //  $('.hover').css("display","none");

                    },

                    // removing the CSS classes once dragging is over.
                    stop:function () {
                        $(this).removeClass("active").closest(".products-grid .item a img").removeClass("active");
                    }
                });

                // jQuery Ui Droppable
                $(".basket").droppable({

                    // The class that will be appended to the to-be-dropped-element (basket)
                    activeClass:"active",

                    // The class that will be appended once we are hovering the to-be-dropped-element (basket)
                    hoverClass:"hover",

                    // The acceptance of the item once it touches the to-be-dropped-element basket
                    // For different values http://api.jqueryui.com/droppable/#option-tolerance
                    tolerance:"touch",
                    drop:function (event, ui) {

                        var basket = $(this),
                                move = ui.draggable,
                                itemId = basket.find("ul li[data-id='" + move.attr("data-id") + "']");
                                 var param = $(ui.draggable).attr('id');

                        // To increase the value by +1 if the same item is already in the basket
                        if (itemId.html() != null) {
                            itemId.find("input").val(parseInt(itemId.find("input").val()) + 1);
                            var price=move.find(".itemprices").html();

                        }
                        else {
                            // Add the dragged item to the basket

                            //alert(p);
                            addBasket(basket, move);

                            // Updating the quantity by +1" rather than adding it to the basket
                            move.find("input").val(parseInt(move.find("input").val()) + 1);
                        }
                    }
                });

                // This function runs onc ean item is added to the basket
                //+ '1'
                function addBasket(basket, move) {
                        var val=move.find(".product-name").html();
                        //alert(val);
                    basket.find("ul").append('
'
                            + '' + move.find(".product-name").html() + ''
                            + '' + move.find(".itemprices").html() + ''
                            + '<input class="count" value="1" type="text" id="count">'
                            + '<button class="total">'+ (move.find(".itemprices").html())*($(".count").val())+'</button>'
                            + '<button class="delete">✕</button>');

                }

                $("#count").on('change', function(){
                var v=$("#count").val();
                //  alert(v);
                });
                // The function that is triggered once delete button is pressed
                $(".basket ul li button.delete").live("click", function () {
                    $(this).closest("li").remove();
                });

            });
            //draggable ends

here drag and drop functionality is working fine , but how do i get the product title and price ,any help ?

A: For price =>
 $(".itemprices").text();

For title =>
   $(".product-name").prop('title');

//NEW CODE
See if you have multiple products ,Assign separate ID to every Product DIV (you already have class assigned to it).Then use # instead of '.' (DOT) . So use
var idStored=$(this).attr('id');
idStored.text();

idStored.text().prop('title');

And then Call these Manipulation on Hover of the div ,Or onClick

A: Try the following:
In your addBasket(basket, move) function add the following line:
var currentLIelement = $(move).parents('li');

So, currentLIelement will be your parent
 element of dragged element.
Now, to get the title you need to call this:
$(currentLIelement).find('.product-name').prop('title')

And to get the price you need to call this:
$(currentLIelement).find('.itemprices').text()

NOTE: In your code I found live() method - As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.


Q: How to validate AzureAD accessToken in the backend API I just wanted to know how can we validate the azure ad access token in a backend API in my case i.e. Django rest framework.
Consider that I have a single page app or a native app and a backend API (django rest framework) completely independen of each other. In my case if my single page app/native app wants to access certain data from the backend API, and inorder to access the API, user should be logged in the backend API.
So what my approch is to make use of MSAL library to get the access token from the SPA/native app and then once token is acquired, pass that token to backend API, validate it, get the user info from graph api. If user exists in the DB then login the user and pass the required info. If user info doesn't exist then create the user, login and pass the info from the  API.
So my question is when I pass the access token to my backend api, how can I validate that the token that a user/SPA/native app has passed to backend API is valid token or not?
Is it just we need to make an API call to graph API endpoint with accessToken that user/SPA/native passed and if it is able to get the user data with the accessToken then then token is valid or if it fails then the accessToken is invalid.
Is it the general way to validate the token or some better approach is there? Please help

A: Good day sir, I wanna share some of my ideas here and I know it's not a solution but it's too long for a comment.
I created a SPA before which used msal.js to make users sign in and generate access token to call graph api, you must know here that when you generate the access token you need to set the scope of the target api, for example, you wanna call 'graph.microsoft.com/v1.0/me', you need a token with the scope 'User.Read, User.ReadWrite' and you also need to add delegated api permission to the azure app.
So as the custom api of your own backend program. I created a springboot api which will return 'hello world' if I call 'localhost:8080/hello', if I wanna my api protected by azure ad, I need to add a filter to validate all the request if has a valid access token. So I need to find a jwt library to decode the token in request head and check if it has a token, if the token has expired and whether the token has the correct scope. So here, which scope is the correct scope? It's decided by the api you exposed in azure ad. You can set the scope named like 'AA_Custom_Impression', and then you can add this delegate api permission to the client azure ad app, then you that app to generate an access token with the scope of 'AA_Custom_Impression'. After appending the Bearer token in calling request, it will be filtered by backend code.
I don't know about python, so I can just recommend you this sample, you may try it, it's provided by microsoft.

A: I've solved the similar issue. I don't found how to directly validate access token, but you can just call graph API on backend with token you've got on client side with MSAL.
Node.js example:
class Microsoft {

  get baseUrl() {
    return 'https://graph.microsoft.com/v1.0'
  }

  async getUserProfile(accessToken) {
    const response = await got(`${this.baseUrl}/me`, {
      headers: {
        'x-li-format': 'json',
        Authorization: `Bearer ${accessToken}`,
      },
      json: true,
    })
    return response.body
  }

  // `acessToken` - passed from client
  async authorize(accessToken) {
    try {
      const userProfile = await this.getUserProfile(accessToken)
      const email = userProfile.userPrincipalName

      // Note: not every MS account has email, so additional validation may be required
      const user = await db.users.findOne({ email })

      if (user) {
        // login logic
      } else {
        // create user logic
      }
    } catch (error) {
      // If request to graph API fails we know that token wrong or not enough permissions. `error` object may be additionally parsed to get relevant error message. See https://learn.microsoft.com/en-us/graph/errors
      throw new Error('401 (Unauthorized)')
    }
  }
}

A: Yes we can validate the Azure AD Bearer token.
You can fellow up below link,
https://github.com/odwyersoftware/azure-ad-verify-token
https://pypi.org/project/azure-ad-verify-token/
We can use this for both Django and flask.
You can directly install using pip
but I'm not sure in Django. If Django install working failed then try to copy paste the code from GitHub
Validation steps this library makes:
    1. Accepts an Azure AD B2C JWT.
         Bearer token
    2. Extracts `kid` from unverified headers.
         kid from **Bearer token**
    3. Finds `kid` within Azure JWKS.
         KID from list of kid from this link `https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys`
    4. Obtains RSA key from JWK.

    5. Calls `jwt.decode` with necessary parameters, which inturn validates:

        - Signature
        - Expiration
        - Audience
        - Issuer
        - Key
        - Algorithm