text:
Q: Converting SQL-Interval-String to minutes using R I am working with R where I have a variable '2 month 3 day 6 hour 70 minute' as string. The variable changes over time and therefore does not have the same length/structure. I need this variable to do a query on a PostgreSQL database by casting it to an interval. This works just fine.
Now I need this interval/string-variable as integer in minutes to do some mathematical calculations.
I thought of using sqldf the following:
library(sqldf)
my_interval = '2 month 3 day 6 hour 70 minute'
interval_minutes <- sqldf(paste("SELECT EXTRACT(EPOCH FROM '",my_interval,"'::INTERVAL)/60"))
interval_minutes_novar <- sqldf("SELECT EXTRACT(EPOCH FROM '2 month 3 day 6 hour 70 minute'::INTERVAL)/60")

but am getting Error: near "FROM": syntax error. From my research I know that sqldf uses SQLite, which does not support EXTRACT().
How can I convert a SQL-Interval to minutes using R?

A: 1) sqldf/gsubfn Using gsubfn replace each word in my_interval with *, the appropriate number of minutes and + .   Remove any trailing + and spaces and then either parse and evaluate mins or substitute mins into the sql statement.  There are 365.25 / 12 days in the average month over 4 calendar years, having one leap year, but if you want to get the same answer as PostgreSQL replace 365.25 / 12 with 30, as noted in the comments.
library(sqldf)  # this also pulls in gsubfn

# input
my_interval = '2 month 3 day 6 hour 70 minute'

L <- list(minute = " +", hour = "*60 +", day = "*60*24 +",
       month = "*365.25 * 60 * 24 /12 +")
mins <- my_interval |>
  gsubfn(pattern = "\\w+", replacement = L) |>
  trimws(whitespace = "[+ ]")

eval(parse(text = mins))
## [1] 92410

fn$sqldf("select $mins mins")
##    mins
## 1 92410

2) Base R This is a base R solution.  Extract the numbers and words into separate vectors, translate the words to the appropriate factors and take their inner product.  The discussion about 30 days months in (1) applies here too.
v <- c(minute = 1, hour = 60, day = 60 * 24, month = 365.25 * 60 * 24 /12)
nums <- my_interval |>
  gsub(pattern = "[a-z]", replacement = "") |>
  textConnection() |>
  scan(quiet = TRUE)
words <- my_interval |>
  gsub(pattern = "\\d", replacement = "") |>
  textConnection() |>
  scan(what = "", quiet = TRUE)
sum(v[words] * nums)
## [1] 92410

3) lubridate   lubridate duration objects can be used.
library(lubridate)
as.numeric(duration(my_interval), "minute")
## [1] 92410

Although lubridate does not handle 30 day months (and Hadley says it is
not planned) we can preprocess my_interval to get the effect.
library(gsubfn)
library(lubridate)

my_interval |>
 gsubfn(pattern = "(\\d+) +month", replacement = ~paste(30*as.numeric(x),"day")) |>
 duration() |>
 as.numeric("minute")
## [1] 91150

A: Adapting my answer here to this, I'll restate a rather gaping problem with this conversion: convert "month" into "seconds" is not constant, as months vary between 28-31 days. If we assume 30, though, for the sake of arguments, then:
func <- function(x, ptn) {
  out <- gsub(paste0(".*?\\b([0-9.]+)\\s*", ptn, ".*"), "\\1", x, ignore.case = TRUE)
  ifelse(out == x, NA, out)
}
res1 <- lapply(c(mon = "month", day = "day", hr = "hour", min = "minute"),
               function(ptn) as.numeric(func(my_interval, ptn)))
res2 <- lapply(res1, function(z) ifelse(is.na(z), 0, z))
res2
# $mon
# [1] 2
# $day
# [1] 3
# $hr
# [1] 6
# $min
# [1] 70
86400 * (res2$mon*31 + res2$day) + 3600*res2$mon + 60*res2$hr
# [1] 5623560

Because I'm using lapply and simple vectorizable operations here, this also works if my_interval is more than one string (of similar format). It is robust to missing variables (presumed 0), and can include "year" (albeit with leap-year inaccuracies) and/or "second" if desired.
intervals <- c("2 month 3 day 6 hour 70 minute", "1 year", "1 hour 1 second")
res1 <- lapply(c(yr = "year", mon = "month", day = "day", hr = "hour", min = "minute", sec = "second"),
               function(ptn) as.numeric(func(intervals, ptn)))
res2 <- lapply(res1, function(z) ifelse(is.na(z), 0, z))
str(res2)
# List of 6
#  $ yr : num [1:3] 0 1 0
#  $ mon: num [1:3] 2 0 0
#  $ day: num [1:3] 3 0 0
#  $ hr : num [1:3] 6 0 1
#  $ min: num [1:3] 70 0 0
#  $ sec: num [1:3] 0 0 1
86400 * (res2$yr*365 + res2$mon*31 + res2$day) + 3600*res2$mon + 60*res2$hr + res2$sec
# [1] 5.6e+06 3.2e+07 6.1e+01

A: My workaround is to use my PostgreSQL connection to do it:
library(sf)
library(RPostgres)

my_postgresql_connection <- dbConnect(Postgres(), dbname = "my_db", host = "my_host", port = 1234, user = "my_user", password = "my_password")
my_interval = '2 month 3 day 6 hour 70 minute'
my_dataframe <- st_read(my_postgresql_connection, query = paste("SELECT EXTRACT(EPOCH FROM '",my_interval,"'::INTERVAL)/60 as minutes"))
my_interval_in_minutes <- as.double(my_dataframe$minutes[1])


text:
Q: OpenCV unhandled exception I am a hardware (arduino hobbyist) programmer trying to get into OpenCV but struggling with a random error.
I have been following Adam Hacks youtibe guide to OpenCV and up to very recently it has worked great. I had compiled OpenCV as 32bit as the prebuilt was only available in x64 and my intended application (driving a set of servos via a FT232H usb to I2C adapter) was in 32 bit.
I typed in his code for "Using OpenCV and Haar Cascades to Detect Faces in a Video [C++]" and it worked fine (see below). It identified my face (some of the time) and drew a box round it. Yeah I was very happy.
The code:
#include <opencv2/opencv.hpp>
#include <vector>
using namespace std;

/* Include D2XX header*/
#include "ftd2xx.h"
/* Include libMPSSE header */
#include "libMPSSE_i2c.h"
#include "FT232.h"

using namespace cv;
int main()
{
    //FT232 ft232;
    //ft232.setUpFT232H();

    double scale = 1.0;
    CascadeClassifier faceCascade;
    faceCascade.load("C:\\OpenCV32\\etc\\haarcascade_frontalface_alt.xml");

    VideoCapture cap(0);
    if (!cap.isOpened())
        return -1;
    for (;;)
    {
        Mat frame;
        cap >> frame;
        Mat grayscale;
        cvtColor(frame, grayscale, COLOR_BGR2GRAY);

        resize(grayscale, grayscale, Size(grayscale.size().width / scale, grayscale.size().height / scale));

        vector  <Rect> faces;

        faceCascade.detectMultiScale(grayscale, faces, 1.1, 3, 0, Size(30, 30));

        for (Rect area : faces) {
            Scalar drawColor = Scalar(255, 0, 0);
            rectangle(frame, Point(cvRound(area.x * scale), cvRound(area.y * scale)),
                Point(cvRound((area.x + area.width-1)*scale), cvRound((area.y + area.height - 1) * scale)), drawColor);
        }

        imshow("Webcam Frame", frame);

        if (waitKey(30) >= 0)
            break;
    }
    return 0;
}

Then with no intentional changes on my part other that swapping about from one haarcascade to another the program stopped working and threw an unhandled error.
Unhandled exception at 0x76979862 in OpenCV_Nerf.exe: Microsoft C++ exception: cv::Exception at memory location 0x00EFF428. occurred
in this part of the system.cpp code
void error( const Exception& exc )
{
#ifdef CV_ERROR_SET_TERMINATE_HANDLER
    {
        cv::AutoLock lock(getInitializationMutex());
        if (!cv_terminate_handler_installed)
        {
            if (param_setupTerminateHandler)
                cv_old_terminate_handler = std::set_terminate(cv_terminate_handler);
            cv_terminate_handler_installed = true;
        }
        cv_terminate_handler_exception = exc;
    }
#endif

    if (customErrorCallback != 0)
        customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(),
                            exc.file.c_str(), exc.line, customErrorCallbackData);
    else if (param_dumpErrors)
    {
        dumpException(exc);
    }

    if(breakOnError)
    {
        static volatile int* p = 0;
        *p = 0;
    }

    throw exc;
#ifdef __GNUC__
# if !defined __clang__ && !defined __APPLE__
    // this suppresses this warning: "noreturn" function does return [enabled by default]
    __builtin_trap();
    // or use infinite loop: for (;;) {}
# endif
#endif
}

the error box pointing to the very last line.
The camera still functions and I have narrowed it down to the line
faceCascade.detectMultiScale(grayscale, faces, 1.1, 3, 0, Size(30, 30));
Build output: (I don't remember the warnings about loss of data first few time,, but I can't be sure)
1>------ Rebuild All started: Project: OpenCV_Nerf, Configuration: Debug Win32 ------
1>Source.cpp
1>D:\Vincent\Documents\Programming\Visual Studio Projects\OpenCV_Nerf\Source.cpp(32,93): warning C4244: 'argument': conversion from 'double' to '_Tp', possible loss of data
1>        with
1>        [
1>            _Tp=int
1>        ]
1>D:\Vincent\Documents\Programming\Visual Studio Projects\OpenCV_Nerf\Source.cpp(32,60): warning C4244: 'argument': conversion from 'double' to '_Tp', possible loss of data
1>        with
1>        [
1>            _Tp=int
1>        ]
1>OpenCV_Nerf.vcxproj -> D:\Vincent\Documents\Programming\Visual Studio Projects\OpenCV_Nerf\Debug\OpenCV_Nerf.exe
1>Done building project "OpenCV_Nerf.vcxproj".

Debug output (last bit as it was over character count)

'OpenCV_Nerf.exe' (Win32): Loaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'. Symbol loading disabled by Include/Exclude setting.
'OpenCV_Nerf.exe' (Win32): Unloaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'
'OpenCV_Nerf.exe' (Win32): Loaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'. Symbol loading disabled by Include/Exclude setting.
'OpenCV_Nerf.exe' (Win32): Unloaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'
'OpenCV_Nerf.exe' (Win32): Loaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'. Symbol loading disabled by Include/Exclude setting.
'OpenCV_Nerf.exe' (Win32): Unloaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'
'OpenCV_Nerf.exe' (Win32): Loaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'. Symbol loading disabled by Include/Exclude setting.
'OpenCV_Nerf.exe' (Win32): Unloaded 'C:\Windows\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_95bdb3a23d6478de\NvCamera\NvCameraWhitelisting32.dll'
The thread 0x31a8 has exited with code 0 (0x0).
The thread 0x1f70 has exited with code 0 (0x0).
The thread 0x3668 has exited with code 0 (0x0).
The thread 0x3698 has exited with code 0 (0x0).
The thread 0x3a34 has exited with code 0 (0x0).
The thread 0x374 has exited with code 0 (0x0).
The thread 0x5d8 has exited with code 0 (0x0).
The thread 0x3288 has exited with code 0 (0x0).
The thread 0x35bc has exited with code 0 (0x0).
The thread 0x348c has exited with code 0 (0x0).
The thread 0x3968 has exited with code 0 (0x0).
The thread 0x8c0 has exited with code 0 (0x0).
The thread 0x1068 has exited with code 0 (0x0).
The thread 0x1ef8 has exited with code 0 (0x0).
The thread 0x3a30 has exited with code 0 (0x0).
The thread 0x184c has exited with code 0 (0x0).
The thread 0x37f8 has exited with code 0 (0x0).
The thread 0x18b4 has exited with code 0 (0x0).
The thread 0x3380 has exited with code 0 (0x0).
The thread 0x3bf8 has exited with code 0 (0x0).
'OpenCV_Nerf.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvproc.dll'. Symbol loading disabled by Include/Exclude setting.
Exception thrown at 0x76979862 in OpenCV_Nerf.exe: Microsoft C++ exception: cv::Exception at memory location 0x00FCF7EC.
Unhandled exception at 0x76979862 in OpenCV_Nerf.exe: Microsoft C++ exception: cv::Exception at memory location 0x00FCF7EC.

I am completely stumped and would really appreciate any help or pointers I could get.
Regards

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linear programming using Matrices in R I need to solve a linear program in R where the variables are matrices.
More specifically, my optimizing function looks like this.
Max X(A+B)Y - x - y,
where X,Y,A,B are matrices and x,y are scalars. Solve for X,Y,x,y
Subject to bunch of constraints like any linear program
Is there a way to solve this in R?
I checked out linprog and limsolve packages in R. They solve linear programs of scalars.
Is there a way to do the same for matrices in R.
Thanks for your help.

A: Googling for R linear programming matrices yielded a number of interesting links, of which the following might be interesting:

*

*Simplex Method for Linear Programming Problems, for the boot package.


text:
Q: ExtJs third party dependencies do not work by default when using app.json I generated my first application, using sencha CMD tool. Before I built it, I had set some dependencies in my app.json file. I dit it like so:
"js": [
    {
        "path": "app.js",
        "bundle": true
    },
    {
        "path": "resources/ol/ol.js",
        "bundle": false
    }
],
"css": [
    {
        "path": "${build.out.css.path}",
        "bundle": true,
        "exclude": ["fashion"]
    },
    {
        "path": "resources/ol/ol.css",
        "bundle": true
    }
]

As you can see, I try to load OpenLayers library to my application. I do not fix index.html and I do not know whether I should do it or not. But the fact is, when I go to my application in browser like so:
http://localhost/myapp

I see in console, that OpenLayers library is not loaded. When, however, I build my application using CMD and go to
http://localhost/myapp/build/production/myapp/

I see that OpenLayers library gets loaded. So, what is wrong with that and how can I load my dependencies by default, without making a build everytime?


text:
Q: react-intl: Missing locale data for locale: "undefined". Using default locale: "en" as fallback I'm using React v15.4, react-intl v2.2.3
In my /lang/en.json :
{
  "greeting": "Hello, World!"
}

And my /pages/about.js :
import React from 'react'
import {FormattedMessage} from 'react-intl'
import pageWithIntl from '../components/PageWithIntl'
import Layout from '../components/Layout'

export default pageWithIntl(({intl}) => (
  <Layout>

About Page

      <FormattedMessage id='greeting' defaultMessage='Hello, World!' />

  </Layout>
))

When I load the page the "Hello, World!" - Text is correctly displayed.
But in the console I'm getting

[React Intl] Missing locale data for locale: "undefined". Using
  default locale: "en" as fallback.

When I reload the page. How can I add the missing locale data?

A: You should wrap you main component (usually it named <App/ >) into <IntlProvider> middleware and set locale prop.
<IntlProvider locale='en'>
   <App/ >
</ IntlProvider>

or React automatically set locale: 'en' and throw you warning

[React Intl] Missing locale data for locale: "undefined". Using
  default locale: "en" as fallback.


text:
Q: Image inside stackpanel is not getting displayed I am creating stackpanel inside the gridview cell dynamically and placing a image control inside stackpanel but on the window only blank space coming, not the image
here is what i am doing
StackPanel Stkpnl = new StackPanel();

Image BgImg = new Image();
BitmapImage Img = new BitmapImage(new Uri(
    "Images/cellbg.png", UriKind.Relative));
BgImg.Source = Img ;

Stkpnl.Children.Add(BgImg );

A: You need to use a Pack URI. See https://stackoverflow.com/a/1651397/486660
If you have a question as to what your Pack URI should look like, then temporarily add an Image control to your WPF page then goto the Source property and click the "..." button and navigate to your image.  The property's text box will have the Pack URI in it.

A: Your code seems to be correct , have you check that image is existing on the folder or the relative path is correct, if you have added this image later to the image folder than you
have to set "Build Action" of a image to "Resource". right click on the image in solution explorer than you can set this property.
you should also check this question
Setting WPF image source in code

A: StackPanel Stkpnl = new StackPanel();
Image BgImg = new Image();
String packuri = "pack://application:,,,/yourassemblyname;component/cellbg.png";
BgImg.Source = new ImageSourceConverter().ConvertFromString(packuri) as ImageSource;

Stkpnl.Children.Add(BgImg );

PS: To find the assembly name in visual studio 2012 go to "Project" in menu bar -> "setup properties"->Application.


text:
Q: Separar 1 variable en 2 cuando encuentre un Guion JS Cordial Saludo.
Les comento lo que deseo hacer.
Ejemplo, tengo una variable asi:
var id = "673728-882";

Lo que quiero hacer, es que me separe eso en 2 variables donde esta el guion, ejemplo de como deberia quedar:
 var id2 = "673728";
  var id3 = "882";

Espero me entiendan y me puedan ayudar.
Gracias de Antemano

A: intenta con el metodo split de js. casi todos los lenguajes cuentan con ese metodo, solo debes de pasar como parametro la variable que deseas "suprimir"
    var id = "673728-882";
    var res = id.split("-");
// accedes con indices al vector que se creo con la variable res
    console.log(res[0]);
    console.log(res[1]);
    document.getElementById("demo").innerHTML = res[1];

espero haberte ayudado.
saludos!


text:
Q: Next lint not working on files anywhere other than the ones inside the pages folder I have a FRESHLY installed NextJS app with TypeScript. I am using Next V12, when I run yarn lint, it runs next lint and shows no errors.

And now when I add an extra rule in the .eslintrc file like "no-unused-vars": 2 (it means to show an error when there's an un-used variable), and add an un-used variable on purpose in my index.tsx file inside the pages folder so that I can test the linting, it works as expected.

But when I add another folder called hooks and add an index.tsx file with unused variables in it, it doesn't capture the unused variable error in hooks folder, only captures the ones inside pages folder.
My .eslintrc file looks like this -
{
    "extends": "next/core-web-vitals",
    "rules": {
        "no-unused-vars": 2
    }
}

If anyone faced this issue before and knows what I'm doing wrong, please suggest.

A: According to the docs, next lint runs ESLint for files in the following folders: pages, components, and lib.
To run ESLint for other folders as well, you have to use the  --dir flag.
You can either do so directly in the terminal:
yarn run lint -- --dir . //for all folders in your project root directory

yarn run lint -- --dir pages hooks //only for the folders "pages" and "hooks"

Or change the lint script in package.json:
{
  ...
  "scripts": {
    ...
    "lint": "next lint --dir ." //or "next lint --dir pages hooks"
    ...
  }
  ...
}

Note that the above is for development mode.
For production mode, you can add the dirs option to eslint in next.config.js:
module.exports = {
  eslint: {
    dirs: ['.'] //or ['pages', 'hooks']
  }
}


text:
Q: Getting error Terminating app due to uncaught exception of class 'nil' I'm tring to throw the exception here where the values is set in other class .but im getting the error as  Terminating app due to uncaught exception of class 'nil' .can any one tell what is wrong with my code ?
    if ([someNameArray containsObject:name])
    {
        Classname *theclassname=[[Classname alloc]init];
        classinstatce.name1=@"hi";
        classinstatce.name2=@"message";
        @throw theclassname;

    }


text:
Q: Convert Xamarin.Forms.Image to Byte Array Simple Question: I have a Xamarin.Forms.Image called "image". I need it to be a byte array. I feel like this has to be a simple thing but I can't find it on the internet anywhere.
var image = Xamarin.Forms.Image();
image.source = "my_image_source.png";

//Magic code

byte[] imgByteArray = ???

A: Unfortunately, the Image class does not expose methods to access the actual image once loaded.
You will need to read the Image from the file and convert it to the Stream you are expecting.
To prevent reading the image object twice you can set the stream read to your Image control.
var image = Xamarin.Forms.Image();

var assembly = this.GetType().GetTypeInfo().Assembly;
byte[] imgByteArray = null;
using (var s = assembly.GetManifestResourceStream("my_image_source.png"))
{
    if (s != null)
    {
        var length = s.Length;
        imgByteArray = new byte[length];
        s.Read(buffer, 0, (int)length);

       image.Source = ImageSource.FromStream(() => s);
    }
}

// here imageByteArray will have the bytes from the image file or it will be null if the file was not loaded.

if (imgByteArray != null)
{
   //use your data here.
}

Hope this helps.-
Update:
This code will require adding your my_image_source.png as part of the PCL as an embedded resource.


text:
Q: How to limite foreach loop How to print limited data with FOREACH

I have 10 data in db but, i want to print only first 3 data with foreach.
Also i tried and used array_slice() method, but next i got some errors.
Thank you!
@foreach($products as $_product)
  //there is Html code... with variables
@foreach

I tried : @foreach(array_slice($products, 0, 2) as $_product). and i got:

array_slice() expects parameter 1 to be array, object given.

A: You can use limit(3) in your eloquent or take(3)
Or if you need to make it in blade use $loop variable
Like this
@if($loop->iteration <=3)
  @continue

Or in your controller
Product::limit(3)->get();
Product::take(3)->get();

If u use it in controller there will be no need to check in your blade view

A: Just use the @break; statement once you've printed however many you want - it will jump you out of the foreach loop.

A: so something quick i can think of this:
@foreach($products as $_product)
  //there is Html code... with variables
  @if($loop->iteration == 3) //Thanks to the response of @MohammedAktaa
      @break
  @endif
@foreach

Although I think it should be best to limit the results from the query to the database.
Ordering, Grouping, Limit, & Offset


text:
Q: How can I insert values at map to list pair? My container is like this:
map<DWORD, list<pair<string,LARGE_INTEGER>>> map_to_list_items;

This code fails to compile:
map<DWORD, list<pair<string,LARGE_INTEGER>>>::iterator iter_map_to_list_items = map_list_items.find(dwThreadID);
if ( iter_map_to_list_items == map_to_list_items.end() )
{
    map_to_list_itens.insert ( pair<DWORD,pair<string,LARGE_INTEGER>>(dwTheadID, (string("Start"), m_TimePRE)));
}

A: You are trying to insert pair<string, LARGE_INTEGER> as list<pair<string, LARGE_INTEGER>>.
I.e. you have a map<D, list<pair<S, L>> which looks like this:
D1 -> list [pair1, pair2, pair3, ...]
D2 -> list [pair4, ...]
What you are trying to do:
D3 -> pairX,
What you should do:
D3 -> list[pairX]

A: My understanding is that you have two variables like this:
map<DWORD, list<pair<string, LARGE_INTEGER>>> map_to_list_items;
map<DWORD, list<pair<string, LARGE_INTEGER>>> map_list_tempos_threads;

The first thing you can do to simplify your code is to use the new C++11's auto keyword, instead of explicitly typing the whole cumbersome iterator name:
auto it = map_list_tempos_threads.find(dwThreadID);

(Note that you may have some typos in your code, since you had dwTheadID instead of dwThreadID, and ..._itens instead of ..._items).
Then, you can simply use std::map::operator[] overload to insert the new item in the map, if it was not there:
if (it == map_to_list_items.end())
{
    //
    // Insert the new list<pair<string, LARGE_INTEGER>> in the map,
    // assuming:
    //   -  key: dwThreadID
    //   -  string: "Start"
    //   -  LARGE_INTEGER: m_TimePRE
    //

    list<pair<string, LARGE_INTEGER>> l;
    string s = "Start";
    l.push_back(make_pair(s, m_TimePRE))     // I'm assuming m_TimePRE is a LARGE_INTEGER
    map_to_list_items[dwThreadID] = move(l); // Move the list into the map
}

EDIT:
This is a much shorter version for the insertion code:
map_to_list_items[dwThreadID].emplace_back("Start", m_TimePRE);

The key point is that, if dwThreadID (the "key") is not in the map, a default-constructed "value" (i.e. list<pair<string, LARGE_INTEGER>>) is created in the map by the operator[] overload, and a reference to it is returned.
Then, list::emplace_back() is called on that reference, and the new ("Start", m_TimePRE) pair is added to the (previously empty, since default-constructed) list.
With this form there is much less to type, but several operations happen "under the hood"; instead, in the first form, the code and its logical steps are more explicit.

A:
map<DWORD, list<pair<string,LARGE_INTEGER>>> map_to_list_itens;

So you have map, with value of type

list<pair<string,LARGE_INTEGER>>

after you are trying to add to map (as value / "second argument") just a pair (another thing, wrong type).

( pair<DWORD,pair<string,LARGE_INTEGER>>(dwTheadID, (string("Start"), m_TimePRE)));

If you have
 map<T1, list<pair<T2,T3> > > my_map;

you should adding to list otherwise. Like here:
 my_map[T1_object].push_back(make_pair(T2_object, T3_object)); //or
 my_map[T1_object].push_back(T2_T3_pair_object);
 //or in C++11
 my_map[T1_object].emplace_back(T2,T3);

More about it, you can read in reference, map, list. I suggest to start with easier example to understand how it works, like here.


text:
Q: asp.net core: Can't connect to websocket from Unity I just started learning to write a server for my game with asp.net core.
I am trying to establish a websocket connection between the Unity game client and the asp.net core server.
I made a new asp.net core API project and added a new controller with this code in it.
(The code is copied from here)
namespace LazerbaseASPNET.Controllers
{
    public class BrianWebSocketController : ControllerBase
    {
        [HttpGet("/ws")]
        public async Task Get()
        {
            System.Diagnostics.Trace.TraceError("WEBSOCKET!!! GET!!!    WEBSOCKET!!! GET!!!    WEBSOCKET!!! GET!!!    WEBSOCKET!!! GET!!!    ");
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                await Echo(webSocket);
            }
            else
            {
                HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
        }

        private async Task Echo(WebSocket webSocket)
        {
            System.Diagnostics.Trace.TraceError("WEBSOCKET!!! ECHO!!!!!    WEBSOCKET!!! ECHO!!!!!    WEBSOCKET!!! ECHO!!!!!    WEBSOCKET!!! ECHO!!!!!    ");
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!result.CloseStatus.HasValue)
            {
                await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
    }
}

Startup.cs looks like this (I added app.UseWebSockets();)
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseWebSockets();
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

In the Unity client I have the following code...
public async Task Connect ()
{
    _socket = new ClientWebSocket();
    Uri uri = new Uri(@"ws://localhost:44348/ws");
    Debug.Log("start connecting websocket");
    await _socket.ConnectAsync(uri, CancellationToken.None);
    Debug.Log("finished connecting websocket");
    Listen();
}

I press the run with IIS express button in visual studio, which opens a browser window at the local server, the address is https://localhost:44348.
Then I leave that browser open and run the code above in Unity.. Unity never gets to this second debug line.. Debug.Log("finished connecting websocket");
Also in the asp.net program visual studio output window I never see the WEBSOCKET!!! GET!!! log.
I get this error in Unity
WebSocketException: Unable to connect to the remote server
System.Net.WebSockets.WebSocketHandle+<ParseAndValidateConnectResponseAsync>d__28.MoveNext () (at <5a2009c85b134970925993880e2ecb2e>:0)

I have also tried publishing the asp.net program to azure and trying the url there, but I still never see the second debug.log in Unity.
I reckon my Unity code is fine as the same code is able to establish a socket connection and send and receive data from a node.js server I have on Heroku. I just have to change the url.
What am I doing wrong? Thanks!

A: So I got this working. There were two issues

*

*when I added these two attributes to my controller class with the sockets code in it, then I could successfully make a socket connection to server running locally with IIS express on my machine.
 [ApiController]
 [Route("[controller]")]
 public class BrianWebSocketController : ControllerBase
 {

*It still did not work with the published version on azure however.. I searched all the options on azure and eventually found an option for websockets buried in there. It was turned off by default, so I turned it on and then I was able to make a connection to the server from Unity.


text:
Q: jQuery - assigning ID to an element I have a simple menu, that goes like this

Home

About

I need to assign an ID of "nav" to a second div (class="main-menu") and I have to do it by jQuery. Anyone can help with this?

A: You can use:
$('.main-menu').attr('id','sm_id')

for targetting only second element with class .main-menu, you can use eq() selector:
$('.main-menu:eq(1)')

A: use
  $('.main-menu').attr("id","whatever")

A: Try this :
$(function(){
  $('.main-menu').attr('id','nav');

});

A: Here is what you looking for
$('.main-menu').attr('id', 'nav');

Hope this helps....

A: Div class name : main-menu
Attribute name : id
Attribute Value : nav
use :
$('.main-menu').attr( 'id', 'nav' );

result :


text:
Q: C# On (any) window close event save window title in C# I currently want to add an event which will fire when any window gets closed (not only a WPF or forms window). I got that step so far and that works perfectly fine. The SubscribeWindowClose event will be added when another program starts.
I had a look at Microsoft's documentation about the Automation.AddAutomationEventHandler.
In the doc was a description about caching the AutomationElement which I didn't quite get.
I just want to compare the closed window title with window titles I've got in a list (List).
Can anyone help me with this or show me a better way to solve my "issue"?
Thanks in advance!

Code:
     private void SubscribeWindowClose(AutomationElement window) {
            Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent,
                window, TreeScope.Element, OnWindowClose);
        }

        private void OnWindowClose(object src, AutomationEventArgs e) {
            try {
                var element = src as AutomationElement;
                Debug.WriteLine(element);

                if (e.EventId == WindowPattern.WindowClosedEvent) {
                    // if window title is in List, run method
                    return;
                }
            } catch (ElementNotAvailableException) {
                return;
            }
        }

A: The comment from @NetMage was the step in the right direction.
Ended up with a modified version of this excample.
Condition was modified to ControlType.TitleBar and worked like a charm!


text:
Q: How to set low priority while compressing with wzzip.exe I have this in batch and the code works without start /low. While compressing with wzzip the CPU is 100% and all other programs hang.
So to fix this issue I've been trying to either set affinity or priority, but with start /low inserted I continue to get error:

Windows cannot find '-ez'

Any help with this would be appreciated.
for /f "tokens=*" %%a in ('type "%Path%\dirlist.txt"') do (
start /low "c:\program files\winzip\wzzip" -ez -md "%%a.zipx" "%%a"
CLS

Thanks for the feedback. With it I was able to make it run in priority low.
start "" /b /low /wait "c:\program files\winzip\wzzip.exe" -ez -md "%%~a.zipx" "%%~a"

It was very important to use /wait command otherwise if you are using a for loop the program wzzip.exe runs all instances at once instead of running one then waiting for it to complete before running another.
Additionally, I changed the cpu core usage to 1 by using /affinity 0x1
start "" /b /low /affinity 0x1 /wait "c:\program files\winzip\wzzip.exe" -ez -md "%%~a.zipx" "%%~a"

Thanks for all the help.

A: @echo off

set "_wzzip="c:\program files\winzip\wzzip.exe"
for /f tokens^=* %%a in ('type "d:\Folder\Subfolder\dirlist.txt"
')do start "" /b /low /wait /affinity 0x1 "!_wzzip!" -ez -md "%%~a.zipx" "%%~a" && (
"%__APPDIR__%wbem\wmic.exe" process where 'name="wzzip.exe"' CALL setpriority "idle")

About:  Windows cannot find -ez, try to add "" and .exe in:

*

*Edit: Adding @author solution:  /wait /affinity

start "" /b /wait /low /affinity 0x1 "!_wzzip!" -ez -md "%%~a.zipx" "%%~a"
You can replace the %path% variable with the full file dirlist.txt:
for /f tokens^=* %%a in ('type "%path%\dirlist.txt"')

for /f tokens^=* %%a in ('type "d:\Folder\Subfolder\dirlist.txt"')
Start your command by adding pertinent arguments/flags so that it starts in the background:
start "" /b /wait /low /affinity 0x1 "!_wzzip!" -ez -md "%%~a.zipx" "%%~a"
After running the command above in background, make a call to the wmic console setting the wzzip.exe process to idle
"%__APPDIR__%wbem\wmic.exe" process where 'name=wzzip.exe"' CALL setpriority "idle"
[√] Find
[√] Conditional Execution || && ...
[√] wmic in Microsoft Documents /online
[√] wmic setpriority "idle" sources from @Bobs questio and answer


text:
Q: What is the difference between Widget sample and Widget *get* sample? beginner in Flutter here,
Does anybody know the difference, or significance of the keyword get in the context of instantiating a widget?
I'm declaring a widget here
ListTile sampleListTile {
  return ListTile(...);
}

In this scenario, I'm getting an error of Methods must have an explicit list of parameters., to be solved by coding it as a method by adding () to the widgetname.
But here,
ListTile get sampleListTile {
  return ListTile(...);
}

Everything works out alright... I tried searching around but I can't nail down the relevant article.
Please help. thanks.

A: Your first syntax is an "instance method", so the syntax should be (note the extra ()):
ListTile sampleListTile() {
  return ListTile(...);
}

which you call like:
ListTile foo = sampleListTile();

and can have parameters as necessary.
The second syntax is of a getter which are special instance methods that have no parameters. They feel more like "instance variables" in that you use them like:
ListTile bar = sampleListTile;


text:
Q: Why are some images not able to convert from ARGB_8888 to RGB_565? I am working with bitmaps in Android, and I am reading Android documentation about bitmap. There is a parameter in Bitmap.Options called inPreferredConfig
The description of inPreferredConfig shows below:
If this is non-null, the decoder will try to decode into this internal configuration. If it is null, or the request cannot be met, the decoder will try to pick the best matching config based on the system's screen depth, and characteristics of the original image such as if it has per-pixel alpha (requiring a config that also does).
Therefore, I want to know when the image cannot be converted to RGB_565?
I try to set some images with RGB_565 but some of them show ARGB_8888 config. I also know that only ARGB_8888 works with transparency. Another fact is that there is less description in Android documentation about this aspect.


text:
Q: Server side rendering with react, react-router, and express I'm trying to set up server-side rendering for my react app and I'm trying to use the great react-router module to allow it to handle non-js situations (some crawlers, when a user had js turned off for some reason). However, I'm running into trouble. I've been using the great response here https://stackoverflow.com/a/28558545/3314701 as a guide of sorts, but I'm getting strange errors thrown at me. I get a persistent Syntax Error when trying to use react.renderToString(). Am I setting up the server-side rendering incorrectly, missing something obvious, or anything else?
My setup:
Really basic Express server
require('babel/register');

var app = express();

// misc. express config...

var Router = require('react-router'),
    routes = require('../jsx/app').routes,
    React = require('react');

app.use(function(req, res, next) {
  var router = Router.create({location: req.url, routes: routes});
  router.run(function(Handler, state) {
    console.log(Handler);
    var html = React.renderToString(<Handler/>);
    return res.render('react_page', {html: html});
  });
});

Top-level react <App/> component
// Shims
require('intl');
require('es5-shim');

var React = require('react/addons'),
  Router = require('react-router'),
  Nav = require('./nav'),
  injectTapEventPlugin = require("react-tap-event-plugin"),

  window.React = React; // export for http://fb.me/react-devtools

// Intl
var ReactIntl = require('react-intl'),
  IntlMixin = ReactIntl.IntlMixin;

var Route = Router.Route,
  DefaultRoute = Router.DefaultRoute,
  NotFoundRoute = Router.NotFoundRoute,
  RouteHandler = Router.RouteHandler;

var App = React.createClass({
      mixins: [IntlMixin],

      getInitialState: function() {
        return {
          connected: false,
          loaded: false,
          user: true
        };
      },
      render: function() {
          return (

              <RouteHandler/>

      );
  }

});

var routes = (
<Route name="Home" path="/" handler={App}>
    <DefaultRoute name="Welcome " handler={Welcome}/>
    <Route name="Bar" path="/bar" handler={Bar}>
    <Route name="foo" path="/foo" handler={Foo}></Route>
 </Route>
);

Router.run(routes, Router.HistoryLocation , function(Handler) {
  React.render(<Handler/>, document.getElementById('app'));
});

module.routes = routes;

output:
flo-0,1,2 (err):

flo-0,1,2 (err):       ^
flo-0,1,2 (err): SyntaxError: Unexpected token <
flo-0,1,2 (err):     at exports.runInThisContext (vm.js:73:16)
flo-0,1,2 (err):     at Module._compile (module.js:443:25)
flo-0,1,2 (err):     at Module._extensions..js (module.js:478:10)
flo-0,1,2 (err):     at Object.require.extensions.(anonymous function) [as .js] (/Users/user/Code/foobar/apps/flo/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:161:7)
flo-0,1,2 (err):     at Module.load (module.js:355:32)
flo-0,1,2 (err):     at Function.Module._load (module.js:310:12)
flo-0,1,2 (err):     at Function.<anonymous> (/Users/user/.nvm/versions/node/v0.12.4/lib/node_modules/pm2/node_modules/pmx/lib/transaction.js:62:21)
flo-0,1,2 (err):     at Function.cls_wrapMethod (/Users/user/Code/foobar/apps/bar/node_modules/newrelic/lib/shimmer.js:230:38)
flo-0,1,2 (err):     at Function.<anonymous> (/Users/user/Code/foobar/apps/bar/node_modules/pmx/lib/transaction.js:62:21)
flo-0,1,2 (err):     at Module.require (module.js:365:17)
flo-0,1,2 (err):     at require (module.js:384:17)

A: So, I ended up solving this one myself. The error I was getting was from an un-rendered nested component, which is why the js engine was complaining about a random < char.
And now to my express setup. For those who aren't aware of how react can be used with server-side rendering, it's fairly straightforward: Node or io.js can be used to call React's renderToString() method on a component and then sending that to the requesting client. You've probably heard the benefits this approach brings already, but for those who don't know:

*

*you get more SEO-friendliness, even though google can already execute JS in it's crawlers; this is pretty much just a safer bet

*Fallback for non-js situations. If your app script is loading slowly, you can still render the actual page to your client and not make them wait while staring at a blank screen. This also allows someone with JS disabled on their browser to still interact with your app for the most part; links will still work, forms can still submit, &c.

*You can get the additional benefits of code-sharing between the client and server. There's nothing necessarily incredible about this aside from the fact that complexity is decreased and, as such, you get all the benefits of decreased complexity (potentially less coupling, easier maintainability, greater simplicity in structure, isomorphic-ness, &c.)

*A further side benefit is the ability to use react-router's html5 history API instead of the annoying hash-fragment stuff you have to otherwise use.

You could even get crazy with this approach and handle things like placeholders for your app while it loads or provide other feedback mechanisms for a slow-loading state (a la Facebook while it loads).
The basic approach operates roughly in the following manner:

*

*Upon bootstrap, the node app instantiates a react-router instance based on routes.jsx

*Request goes to the server, which then uses express' req.path to provide a route string for react-router to handle.

*React router then matches the provided route and tries to render the corresponding component for express to send back.

*React sends down the html response and your client gets to paint something regardless of the speed of your app script. We serve ours over a great CDN, but even with the best distribution and compression slow networks would still otherwise leave people with a temporarily blank screen.

*Having loaded the needed app script, React can use the same routes.jsx file to take over and generate html with react-router from here on out. Another benefit here is that your app code can be cached and future interactions hopefully won't even have to rely on another call.

One more point worth noting: I use webpack to bundle my react code and now browser.jsx is the entry point. Before refactoring for server-side rendering it was previously app.jsx; you might need to re-configure your structure to accommodate what gets rendered where. :)
le Code:
Browser.jsx
const React = require('react');
const Router = require('react-router').Router;
const hist = require('history');
const routes = require('./routes');

const newHistory = hist.createHistory();

React.render(<Router history={newHistory}>{routes}</Router>, window.document);

App.js (express server):
//...other express configuration

const routes = require('../jsx/routes');
const React = require('react');
const {RoutingContext, match} = require('react-router');
const hist = require('history');

app.use((req, res, next) => {
  const location = hist.createLocation(req.path);
  match({
    routes: routes,
    location: location,
  }, (err, redirectLocation, renderProps) => {
    if (redirectLocation) {
      res.redirect(301, redirectLocation.pathname + redirectLocation.search);
    } else if (err) {
      console.log(err);
      next(err);
      // res.send(500, error.message);
    } else if (renderProps === null) {
      res.status(404)
        .send('Not found');
    } else {
      res.send('<!DOCTYPE html>' + React.renderToString(<RoutingContext {...renderProps}/>));
    }
  });
});

    //...other express configuration

Routes.jsx
<Route path="/" component={App}>
  <DefaultRoute component={Welcome}/>
  <Route path="dashboard" component={Dashboard}/>
  <Route path="login" component={Login}/>
</Route>

App.jsx

  <link rel="stylesheet" href="/assets/styles/app.css"/>

    <Navigation/>
    <RouteHandler/>

helpful links:

*

*https://ifelse.io/2015/08/27/server-side-rendering-with-react-and-react-router/

*https://github.com/rackt/react-router


text:
Q: why element.Text= not work Try to do next - i want to check if some information is already exist if csv file, if yes - open form with label, and put to this label information from file
Code is next:
public void getEventTime(string filePath, string currDate, string currentDateTimeHM)
    {
        //reading the *.csv file and convert to the array of data
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        StreamReader sr = new StreamReader(fs);

        //create array for getting any vlaue from string
        string[] arrOfData = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        sr.Close();

        List<string> lines = new List<string>();
        bool status=false;//variable for showing form if event exist

        foreach (var l in arrOfData)
        {
            if (l.Contains(currDate) && l.Contains(currentDateTimeHM))
            {
                string[] temp = l.Split(',').Take(5).ToArray();
                notLabel.Text = temp[1].ToString();
                status = true;
            }
        }
        if (status)
        {
            //show Notification Form
            Form NotificationForm = new Notification();
            NotificationForm.Visible = true;
        }
    }

all works perfect - if information exist - new form opens, but notLabel.Text = temp[0].ToString(); this part have return nothing. During debuging i got next

means that code is correct but in strange for me reason result in programm - without this text.
where I make some mistake?
Below form with label

checked

few rows from file NotificationDesigner.Form.cs
        this.notLabel.AutoSize = true;
        this.notLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
        this.notLabel.Location = new System.Drawing.Point(12, 22);
        this.notLabel.Name = "notLabel";
        this.notLabel.Size = new System.Drawing.Size(34, 13);
        this.notLabel.TabIndex = 0;
        this.notLabel.Text = "label";

A: where do you call the method getEventTime and what is notLabel.
if the method getEventTime is called and set the notLabel.Text but after that the text is set again to string.Empty that there is the problem, so you should probably search or debug every change to notLabel.Text.
are you sure the it is notLabel the it is shown in the form? you can check that by registering to the mouseDown event and see that it is called when you click on the Label
one more thing, add break;
after your line
status = true;

go to the design and press the label, press F4 and search the name property, i bet it is not notLabel:

EDIT
i think i fount your problem
correct me if i'm wrong but this lines
    if (status)
    {
        //show Notification Form
        Form NotificationForm = new Notification();
        NotificationForm.Visible = true;
    }

are happening after you change the text... when what you meant is:
public void getEventTime(string filePath, string currDate, string currentDateTimeHM)
{
    Form NotificationForm = new Notification();
    //reading the *.csv file and convert to the array of data
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    StreamReader sr = new StreamReader(fs);

    //create array for getting any vlaue from string
    string[] arrOfData = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
    sr.Close();

    List<string> lines = new List<string>();
    bool status=false;//variable for showing form if event exist

    foreach (var l in arrOfData)
    {
        if (l.Contains(currDate) && l.Contains(currentDateTimeHM))
        {
            string[] temp = l.Split(',').Take(5).ToArray();
            NotificationForm.NotText = temp[1].ToString();
            status = true;
        }
    }
    if (status)
    {
        //show Notification Form

        NotificationForm.Visible = true;
    }
}

and in the notification form do
  public string NotText
  {
     set { notLabel.Text = value; }
  }


text:
Q: How do I build a Laravel eloquent query for parent entries that have no child entries? I can't believe I've never had to do this and now I'm realizing I don't actually know how to accomplish it. The basic structure is Parent hasMany Child). I want to periodically query all Parent entries that do not have a Child entry and delete them.
I would think this starts with Parent::with('child')->where...->delete(). But how do I finish this out? Do I need to do this using DB::raw instead?
If you want to help me one step further... I have a function in the Parent model for isExpired(). I really only want to delete the entries where isExpired() is TRUE.

A: You are looking for doesntHave.This will give all the parents which donot have child entries. And delete them.
$parents=Parent::doesntHave('child')->get();
foreach($parents as $parent)
{
     $parent->delete();
}

The relation in Parent Model:
public function child()
{
   return $this->hasMany('App\Child');
}


text:
Q: What does it mean to be cluster-friendly in NoSQL? Also, please explain the common characteristics of NoSQL databases I cannot seem to find much information that explains what exactly cluster-friendly means in NoSQL. I am still relatively new to database management in general even though I've had some experience with MySQL, so I would love someone with the proper knowledge to elaborate this topic to me.
   The common characteristics among NoSQL databases:
Non-relational
Schema-less
Cluster friendly (not always)
Open source (not always)
came out of the 21st century web (there are other non-relational databases that have been around for decades that are not considered NoSQL)

A: "Cluster-friendly" means that the database can easily be distributed on lots of machines.
When a relational database reaches its capacity, you can usually just buy a larger server. Distributing the load of one database on multiple servers is possible with some relational databases, but it usually doesn't scale linearly.
Many NoSQL databases, however, are designed with scalability in mind. When one machine becomes too slow, you can usually add more machines to the cluster with minimal effort to improve performance.


text:
Q: Alternative definitions of the Calabi-Yau manifolds How do we prove that a compact Kahler manifold whose 1st Chern class vanishes admits a globally defined nowhere vanishing volume form? Thanks.

A: One can use Yau's theorem here. It states that $M$ admits a Kahler Ricci flat metric. With this metric, the holomony group lie inside $SU(n)$, thus the standard holomorphic $(n,0)$ form
$$dz^1 \wedge \cdots \wedge dz^n$$
can be extended to the whole $M$. This can be found in the book "Riemannian holomony groups and Calibrated Geometry" by D. Joyce.
Edit: If the first Chern class is defined by the image of boundary homomorphism
$$H^1 (M, \mathbb C^*) \to H^2(M, \mathbb Z)$$
of the anitcanonical line bundle, then your statement is almost trivial as $L \mapsto c_1(L)$ is a one-one correspondence. (I am thinking of $c_1(M)$ as defined by curvature, so it is the torsion free part of the image of the boundary homomorphism)


text:
Q: Binary operators and overloading, addition and so forth I can't add together more then 2 things in each object. for example. I have a xCord, a yCord, a radius, a circumference, and a area. When I add the objects together only the xCords and yCords add together. The rest stay at what they were set to.
The circleT.h file, also my compiler is older so it can't handle having templates in the cpp for some reason. So everything is in the header file if you are wondering.
//  MATHEMATICAL OPERATORS

// BINARY operators
template<typename T>
CircleT<T>  CircleT<T>::operator+(const CircleT<T>& rhs)
{
    CircleT temp;
    CircleT tempC;
    temp.xCord =  this->xCord + rhs.xCord;
    temp.yCord =  this->yCord + rhs.yCord;
    temp.radius = this->radius + rhs.radius;
    return temp;
}

template<typename T>
CircleT<T>   CircleT<T>::operator-(const CircleT<T>& rhs)
{
    CircleT temp;
    temp.xCord =  this->xCord - rhs.xCord;
    temp.yCord =  this->yCord - rhs.yCord;
    return temp;
}
template<typename T>
CircleT<T>   CircleT<T>::operator*(const CircleT<T>& rhs)
{
    CircleT temp;
    temp.xCord =  this->xCord * rhs.xCord;
    temp.yCord =  this->yCord * rhs.yCord;
    return temp;
}
template<typename T>
CircleT<T>   CircleT<T>::operator/(const CircleT<T>& rhs)
{
    CircleT temp;
    temp.xCord =  this->xCord / rhs.xCord;
    temp.yCord =  this->yCord / rhs.yCord;
    return temp;
}

//  UNARY operators
template<typename T>
CircleT<T>&   CircleT<T>::operator+=(const CircleT<T>& rhs)
{
    this->xCord += rhs.xCord;
    this->yCord += rhs.yCord;
    return *this;
}
template<typename T>
CircleT<T>&   CircleT<T>::operator-=(const CircleT<T>& rhs)
{
    this->xCord -= rhs.xCord;
    this->yCord -= rhs.yCord;
    return *this;
}
template<typename T>
CircleT<T>&  CircleT<T>::operator*=(const CircleT<T>& rhs)
{
    this->xCord *= rhs.xCord;
    this->yCord *= rhs.yCord;
    return *this;
}
template<typename T>
 CircleT<T>&  CircleT<T>::operator/=(const CircleT<T>& rhs)
{
    this->xCord /= rhs.xCord;
    this->yCord /= rhs.yCord;
    return *this;
}

 template<typename T>
CircleT<T>&   CircleT<T>::operator=(const CircleT<T>& rhs)
{
    this->xCord = rhs.xCord;
    this->yCord = rhs.yCord;
    return *this;
}

template<typename T>
CircleT<T>  CircleT<T>::operator++(int ignoreThis)
{
    //  this is the   **  POST ** increment
    double tempxCord = xCord;
    double tempyCord = yCord;
    xCord++;
    yCord++;
    return CircleT();
}
 template<typename T>
CircleT<T>   CircleT<T>::operator++()
{
    //  this is the   **  PRE ** increment
    xCord++;
    yCord++;
    return CircleT();
}

 template<typename T>
CircleT<T>   CircleT<T>::operator--(int ignoreThis)
{
    //  this is the   **  POST ** increment
    double tempxCord = xCord;
    double tempyCord = yCord;
    xCord--;
    yCord--;
    return CircleT();
}
template<typename T>
CircleT<T>   CircleT<T>::operator--()
{
    //  this is the   **  PRE ** increment
    xCord--;
    yCord--;
    return CircleT();
}

    // LOGICAL operators
template<typename T>
bool  CircleT<T>::operator==(const CircleT<T>& rhs)
{
    return  (  this->xCord == rhs.xCord  &&  this->yCord == rhs.yCord   );
}
template<typename T>
bool  CircleT<T>::operator!=(const CircleT<T>& rhs)
{
    return  (  this->xCord != rhs.xCord  &&  this->yCord != rhs.yCord   );
}
template<typename T>
bool  CircleT<T>::operator<(const CircleT<T>& rhs)
{
    double areaL = this->xCord * this->yCord;
    double areaR = rhs.xCord * rhs.yCord;
    return  (   areaL < areaR    );
}
template<typename T>
bool  CircleT<T>::operator<=(const CircleT<T>& rhs)
{
    double areaL = this->xCord * this->yCord;
    double areaR = rhs.xCord * rhs.yCord;
    return  (   areaL <= areaR    );
}
template<typename T>
bool  CircleT<T>::operator>(const CircleT<T>& rhs)
{
    double areaL = this->xCord * this->yCord;
    double areaR = rhs.xCord * rhs.yCord;
    return  (   areaL > areaR    );
}
template<typename T>
bool  CircleT<T>::operator>=(const CircleT<T>& rhs)
{
    double areaL = this->xCord * this->yCord;
    double areaR = rhs.xCord * rhs.yCord;
    return  (   areaL >= areaR    );
}

A: Your operator = function only copies the x and y coordinates, not the radius. So even when the + operator works, the assignment does not.


text:
Q: Active Admin - Make a Resource Sortable for Specific Ordering on Front End I'm trying to add ordering/re-ordering to a resource in Active Admin. I understand that you can sort by the different columns for viewing while logged in. What I'd like to do is be able to order items so they display in a specific order on the front end.  Any ideas on how to accomplish this?
I have a sort column in the database already.
Also I'd like to display the items in that specific order on in the admin section.
Anyone have any ideas on how I'd accomplish this?

A: I implemented this recently using a column called position on my HomeSlide model.
ActiveAdmin.register HomeSlide do
  config.sort_order = 'position_asc'

  index do
    column :title
    default_actions
  end

  # This action is called by javascript when you drag and drop a column
  # It iterates through the collection and sets the new position based on the
  # order that jQuery submitted them
  collection_action :sort, :method => :post do
    params[:home_slide].each_with_index do |id, index|
      HomeSlide.update_all(['position=?', index+1], ['id=?', id])
    end
    render :nothing => true
  end

end

Add this to your active_admin javascripts (coffee script)
sendSortRequestOfModel = (model_name) ->
  formData = $('#' + model_name + ' tbody').sortable('serialize')
  formData += "&" + $('meta[name=csrf-param]').attr("content") + "=" + encodeURIComponent($('meta[name=csrf-token]').attr("content"))
  $.ajax
    type: 'post'
    data: formData
    dataType: 'script'
    url: '/admin/' + model_name + '/sort'

jQuery ($) ->

  # home page slides
  if $('body.admin_home_slides.index').length
    $( "#home_slides tbody" ).disableSelection()
    $( "#home_slides tbody" ).sortable
      axis: 'y'
      cursor: 'move'
      update: (event, ui) ->
        sendSortRequestOfModel("home_slides")

A: Do you have a separate frontend controller then? For the activeadmin part of your question:
It is possible to have a
config.sort_order = 'lastname_asc'

or
config.sort_order = 'created_at_desc'

declaration inside the ActiveAdmin.register block of your model / resource.
In your model, you could put something like
default_scope :order => "id DESC"

Reading your question though it seems appropriate for you to read some documentation, Here is a part copied from http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html
class Article < ActiveRecord::Base
  scope :published, where(:published => true)
  scope :featured, where(:featured => true)

  def self.latest_article
    order('published_at desc').first
  end

  def self.titles
    map(&:title)
  end

end

Which allows you to call the methods like this:
Article.published.featured.latest_article
Article.featured.titles

Good luck.


text:
Q: How to switch virtual terminal under Virtualbox on OSX I just installed Ubuntu Jaunty as a guest OS in VirtualBox 3.1, running under OSX. My problem is that I can't switch from X to a virtual terminal, Host+F1 doesn't work (host key being "Left cmd").. Is there another key combination?

A: Just figured it out... fn + host key + Fx


text:
Q: How to correctly center bootstrap wide modal? On mobile devices, Bootstrap modal is not centered correctly when body min-width is wider than 980px.
I tried bootstrap 4, bootstrap 5 and bootstrap 3 modals.
You can see in the screenshot that the modal div is positioned out of the screen and the backdrop doesnt cover the full width, leaving white space on the right.

<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <button class="btn btn-lg btn-primary center-block text-" data-remote="false" data-toggle="modal"
    data-target="#myModal">show modal</button>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

          some content

A: Add mx-auto class to parent div like that class="modal fade mx-auto"


text:
Q: GCM Push Notification icon is not visible in Ionic app I have developed app using Ionic Framework, and implemented GCM push notification using this plugin, it is working fine with the device of android version below 4.4 (kitkat), i am able to see notification icon.
But devices with android version more than 5.x (lolipop) notification icon is not visible.
Here is my ctrl code,
    var pushNotification = window.plugins.pushNotification;
    pushNotification.register(successHandler, errorHandler,
        {
            'senderID': 'xxxx', 'icon': 'icon', 'ecb': 'onNotificationGCM'
        });

   function onNotificationGCM(e) {
    switch (e.event) {
        case 'registered':
            if (e.regid.length > 0) {
                registerDeviceForNotification();
            }
            break;

        case 'message':
            if (e.foreground) {
                // When the app is running foreground.
                }
            }
            $rootScope.notificationCount =  $rootScope.notificationCount + 1;
            break;

        case 'error':
            console.log('Error: ' + e.msg);
            break;

        default:
            console.log('An unknown event was received');
            break;
    }
}

Any help will be appreciated.

A: Android 5+ will take your image and replace all non transparent pixes with white.  If there is no transparency, probably you will see blank image or none.
You can generate your icon using this website.
Then, save the icon in resources folder and run $ ionic resources --icon

A: upper Android M (Api 22) the status bar and notification icons, are supported in B/W PNG 16bit , with other configuration, you can view a strange B/W icon or nothing

A: There's a change with Android 5 regarding the notification icons. Have a look at the following links to get an idea.

*

*https://developer.android.com/design/patterns/notifications.html

*Notification bar icon turns white in Android 5 Lollipop


text:
Q: Checking if user owns child records (MySQL) I am having a quite big problem with the following queries. The tables looks like:
A (Parent)
+------------+---------+
| id | user_id | value |
+------------+---------+
|  1 |     20 |      X |
|  2 |     20 |      Y |
|  3 |     12 |      Z |
+------------+---------+

B (Child)
+------------+-----------+
| id | parent_id | value |
+------------+-----------+
|  1 |         1 |     X |
|  2 |         2 |     Y |
|  3 |         2 |     Z |
+------------+-----------+

C (Childs of the Child records)
+------------+-----------+
| id | parent_id | value |
+------------+-----------+
|  1 |         1 |     X |
|  2 |         1 |     Y |
|  3 |         1 |     Z |
+------------+-----------+

I need two (separate) queries. The first for verification if records in the table B belongs to the user id = X and then if records in the table C belongs to the user id = X. So for example I have got IDs (1, 2, 3, 18, 329) of records from the table C and I need to check if these values belong to the user id = 20. The result should be 1, 2, 3. How can I do this? I don't work with SQL a lot so I am completely lost and I appreciate every help. Thanks

A: You need a Select with 2 joins:
SELECT c.id
FROM c
  INNER JOIN b ON b.id = c.parent_id
  INNER JOIN a ON a.id = b.parent_id
WHERE c.id in (1, 2, 3, 18, 329)
  AND a.user_id = 20 ;


text:
Q: How to print a specific element of an array passed via context api? I am trying to a print a specific element of an array based on the user, How do I get that specific element and print it on the screen  ????
const state = useContext(GlobalState)
const[ulocations]=useState(state.categoriesAPI.locationapi[0])

const [userlist]=useState([{location_id:'5476',name:'John', age:36}])

// ulocations is an ARRAY OF OBJECTS [{...},{...},{...}]

// where an obj contains{_id:'5476',name:'europe'}

  const findspecificcountry=()=>{

                  for(let i=0;i<ulocations.length;i++){

                    if(ulocations[i]._id==myuserlist[0].location_id){
                       return ulocations[i].name
                          }
                          }

    }

return(

userlist.map(a=>{

 a.name

a.age

 {findspecificcountry()}
 // doesnt print the value europe ????? nothing appears
})

)

A: If you are trying to retrieve your locations from the GlobalState context, you would do so with:
const { state, dispatch } = useContext(GlobalState)
const ulocations = state.categoriesAPI.locationapi[0] // Assuming this is your location list

It looks like your user list should just be a constant here also. No need for the useState hook:
const userlist = [{location_id:'5476',name:'John', age:36}]

When you map over your userlist, you can then pass the user's location ID to your function:
userlist.map(a => {
  ...

 {findspecificcountry(a.location_id)}

})

The function would then accept that location parameter:
const findspecificcountry = (id) => {}

I don't know the format of your API data, so I leave updating the function to you.


text:
Q: Did Draco Malfoy know that he is related to Sirius Black? Sirius Black is Draco Malfoy's first cousin once removed. According to an answer in Quora:

Since, the Malfoy and Black were all about pure blood and stuff, they also married in pure bloods. Narcissa, cousin of Sirius and Regulus Black married Lucius Malfoy.

And at this answer.
Regardless with the answer, did Draco know that Sirius is his cousin or even related to him?

A: I can't imagine he doesn't know, and he certainly knows after events in the fifth book.
To all wizards, at least the pure-bloods (except oblivious Harry), it's well known that all pure-blood wizarding families are interrelated. When Harry finds out Sirius and Draco are related, Sirius just shrugs it off.

Harry, however, did not laugh; he was
too busy staring at the names to the right of
Andromeda's burn mark. A double line of gold
embroidery linked Narcissa Black with Lucius Malfoy,
and a single vertical gold line from their names led to
the name Draco.

"You're related to the Malfoys!"

"The pure-blood families are all interrelated," said
Sirius. "If you're only going to let your sons and
daughters marry purebloods your choice is very
limited, there are hardly any of us left. Molly and I are
cousins by marriage and Arthur's something like my
second cousin once removed. But there's no point
looking for them on here — if ever a family was a
bunch of blood traitors it's the Weasleys."

Sirius is the black sheep in the Black family; they were mostly followers of Voldemort, and some of them even Death Eaters. Both the Blacks and the Malfoys were very old wizarding families, and the fact that Narcissa's maiden name was Black couldn't have escaped Draco for long if he even put the least effort into his own genealogy.
Of course, it is possible that Narcissa Malfoy (née Black) has neglected to mention to her son Draco that she and Sirius Black are first cousins. Sirius was disowned by the Black family, after all, and his portrait burned off the Black family tapestry in Grimmauld Place 12.
Even if she never told him and nobody else did either, Draco would certainly be aware of it after the following interview was published in The Daily Prophet after the mass Azkaban breakout in The Order of the Phoenix:

Speaking to reporters in his private office, Cornelius
Fudge, Minister of Magic, confirmed that ten high security
prisoners escaped in the early hours of
yesterday evening, and that he has already informed
the Muggle Prime Minister of the dangerous nature of
these individuals.

"We find ourselves, most unfortunately, in the same
position we were two and a half years ago when the
murderer Sirius Black escaped," said Fudge last night.
"Nor do we think the two breakouts are unrelated. An
escape of this magnitude suggests outside help, and
we must remember that Black, as the first person ever
to break out of Azkaban, would be ideally placed to
help others follow in his footsteps. We think it likely
that these individuals, who include Black's cousin,
Bellatrix Lestrange, have rallied around Black as their
leader. We are, however, doing all we can to round up
the criminals and beg the magical community to remain
alert and cautious. On no account should any of these
individuals be approached."

It was certainly no secret to Draco that Bellatrix Lestrange was Narcissa's sister, and his aunt. Although she was locked into Azkaban for most of Draco's life, they spent quite an amount of time together after she escaped, and killing her cousin was on top of her to-do list and probably something she bragged about afterwards (she usually called him her "dear cousin" derisively).


text:
Q: Emmett и notepad++ Доброго времени суток. Долгое время я использовал notepad++ в связке с emmett. Однако в последнее время раскрытие тегов стало тормозить при больших кусках кода. Потом я перешел на Atom, в котором с этим делом все хорошо. Однако сама скорость работы атома несколько медленней, чем работа того же нотепада. Собственно вопрос. Можно ли ускорить работу emmett в связки с notepad++? Ну или посоветуйте редактор для верстки  с возможность работать с файлами по ftp и подобием эмметта. Спасибо.

A: pspad + emmet. много лет сижу - ненарадуюсь
сейчас вам будут всякие модные сублимы советовать, но если notepad++ вам роднее, то они вам не подойдут

A: Попробуйте, Sublime Text 3 в связке с тем же эмметом. Работает шустро. Сам переходил с плюсов на него


text:
Q: Message queue with conditional notifyer Lets say that I have a message queue which receives messages which have the members name, type and so on.
Is there a name for a type of observer on this queue which expects a message with a certain content?
if (message.name.equals(observer.wantedName) {
  observer.notify();
}

A: The following is just an example in pseudo code how to solve the problem. The MessageQueue has a hashtable which keys are the message types and values arrays with listeners for this message type. Also you'll need an additional argument to YourMessageQueue:observe() that describes the condition.
class YourMessageQueue extends /* or implements */ EventDispatcher {

    function addMsg(msg) {
        foreach(this.listeners[msg.type] as listener) {
            listener.notify(msg, this);
        }
    }
}

class YourObserver implements Observer {

    function createMesssageQueue() {
        msgq = new MessageQueue();
        msgq.addObserver(this, 'foo');
    }
}

class EventDispatcher {

    protected hashtable observers;

    function addObserver(Observer observer, string eventType) {
        this.observers[eventType].push(observer);
    }
}

interface Observer {

    function notify($data, $sender);
}


text:
Q: Rails not recognizing inherited class method I am writing a rails application which is an API. I am bypassing active record writing my own super class which is responsible for making api calls.
It appears that Rails does not like certain method names in the parent and accepts others. When I call ModelClass.parent_method, I get a NoMethodError (undefined method parent_method' for ModelClass:Class):
My code is structured like this:
 #./lib/accounts_api
 module AccountsAPI
   class SomeOtherClass
     . . .
   end

   class AccountModel
     class << self

       #this method works without fail:
       def get id
        url = "path to fetch object"
        response = HTTParty.get(url)
        return self.new response.parsed_response
       end
       # this method cannot be found
       def update_existing options
        url = "path to update object"
        response = HTTParty.put(url, :body => options)
        return self.new response.parsed_response
       end
    end
 end

And then, a derived class:
class BankAccount < AccountsApi::AccountModel
  attr_accessor :id, :customer_id, :reference
  def initialize(options={})
    if options.respond_to? :each
      options.each do |key,val|
        target = "#{key}=".to_sym
        self.send(target, val) if self.respond_to?(target)
      end
    end
  end
end

And my controller, where the error is originating from:
class BankAccountsController < ApplicationController
  #Works just fine without fail
  def show
    @bank_account = BankAccount.get params[:id]
    respond_to do |format|
      format.json { render :json => @bank_account, :status => :ok }
    end
  end
  #Throws:
  # NoMethodError (undefined method `update_existing' for BankAccount:Class):
  # app/controllers/bank_accounts_controller.rb:21:in update
  # without fail
  def update
    @bank_account = BankAccount.update_existing params[:bank_account]
    respond_to do |format|
      format.json { render :json => @bank_account, :status => :ok }
    end
  end
end

Note: I've ommited some internals from the methods (error handling, validations, assignment etc.) for clarity.
A Workaround Fix:
If I change the update_existing method name to something more railsy, like put, it works just fine.
What else is weird, is that there is no Stacktrace. I'm just seeing the Rendered rescues layout messages in the logs:
Rendered /home/eggmatters/.rvm/gems/ruby-2.1.1@my-gemset/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.6ms)
Rendered /home/eggmatters/.rvm/gems/ruby-2.1.1@my-gemset/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.7ms)
Rendered /home/eggmatters/.rvm/gems/ruby-2.1.1@my-gemset/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (7.0ms)
Rendered /home/eggmatters/.rvm/gems/ruby-2.1.1@my-gemset/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (16.6ms)

More weirdness, Calling the method from the irb works just fine:
> options = {:id => "23", :customer_id => "123", :reference => "update"}
> BankAccount.update_existing options
=> (:bank_account => { {:id => "23", :customer_id => "123", :reference => "update"}, :id => "23"}

So I'm guessing, I'm messing with Rails messaging. I'm also guessing that my AccountModel parent class needs to inherit something from ActiveRecord or another rails lib but, this is too much of a bizarre edge case (to me) to research it.
Note: The AccountsAPI module is set to include in my app/initializers directory.
Also, I forgot to mention, restarting Passenger and or Apache has no effect.
UPDATE: Strike the Temporary Fix / workaround. Changing the method name to put still does not work. I can get it to update if I restart passenger a bunch of times, but it will only work once or twice and then back to the issue.
UPDATE: I cannot call a method on the child model either. In the model, I added the method:
class BankAccount < AccountsApi::AccountModel
  . . .
  def self.update_wrapper options
    return self.update options
  end
  . . .
end

Now throws:
NoMethodError (undefined method `update_wrapper' for BankAccount:Class):

A: Looks like the inclusion of the parent class within the module was somehow messing up the way rails was mapping methods. Pulling it out (and restarting Passenger) seemed to work:
class BankAccount < AccountModel
  . . .
end

and the parent:
module AccountsAPI
  class SomeOtherClass
  . . .
  end
end

class AccountModel
  class << self
    def get id
    . .
    end

   def update_existing options
       . . .
   end
end

Looks like it works. Not sure why though. I've seen the: class Child < Module::Parent pattern before. As I hinted at in my post, I'm missing some Railsy (possibly ruby) configuration aspect of this.
I caught this as another model (that just calls get) actually is an instance of the "SomeOtherClass" so, it would be exposed to the class within the module. I'm still open to suggestions!

A: Looks like Passenger was globally caching the module and not updating it on application restart. Moving the two classes to their own respective scripts in the lib folder as well as the module declaration altogether worked:
# ./lib/some_other_class.rb
class SomeOtherClass
  . . .
end

# ./lib/account_model.rb
class AccountModel
 . . .
end

Rails apparently maps these to the application level namspace so a declaration like:
class MySomeOtherClassModel < SomeOtherClass

and
class MyAccountModel < AccountModel

are found by rails as inclusion of the named libraries ensured inclusion by the application on load (i.e. server start)


text:
Q: $x^p-a$ irreducible?
Assume $F$ is a subfield of the complex numbers containing the $p$-th roots of unity. If $\alpha$ is a root of $x^p-a$ for some $a\in F$, and $\alpha \not\in F$ then $x^p-a$ is irreducible.

To me it seems obvious that the polynomial $f$ of smallest degree in $F[x]$ such $f(\alpha)=0$ is $x^p-a$. Proving that however has been a challenge. Given another polynomial $g(x)\in F[x]$ with $deg(g)<p$ and $g(\alpha)=0$ what contradiction could I arrive at?

A: If $a\in F$, it's known that for $p$ a prime, $X^p-a$ has no root in $F$ iff $X^p-a$ is irreducible over $F$. A proof on this site can be found here, and in other linked duplicates.
The roots of $X^p-a$ in a splitting field are of form $\zeta^k\alpha$ for $0\leq k\leq p-1$, where $\zeta$ is a primitive $p$-th root of unity. If $F$ contains any of these roots, then since $F$ contains $\zeta$, it must also contain $\alpha$, a contradiction. So $X^p-a$ has no root in $F$, so by the linked result, it must be irreducible.


text:
Q: Incrementing a foreach loop and only showing one child I'm creating a custom Google map that plots multiple markers.
View the link as it will make it easier to explain what is happening and what I want
If you click on each marker it shows company names that are grabbed from the child pages. At the moment it's showing ALL the company names on each marker. How can I show just one company name per marker? i.e So one say "MediWales" and the other says "Teamworks Design & Marketing", and so on when I add more companies.
Here's the code controlling the little popup:
<?php $pages = get_pages(array('child_of' => 1873, 'sort_column' => 'menu_order'));
$counter = 1;
foreach($pages as $post)
{
setup_postdata($post);
$fields = get_fields(); ?>

<?php $counter++; echo $fields->company_name;?>

<?php } wp_reset_query(); ?>

Once it's looped through once, the next time it loops through I need it to start on the next child and not show the first one.
UPDATE:
It seems like it's very close, it's showing one company but the same one on both markers.
<?php
$counter = 1;
$pages = get_pages(array('child_of' => 1873, 'sort_column' => 'menu_order', 'offset' => $counter, 'number' => 1));
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields(); ?>

<?php echo $fields->company_name; echo $counter; ?>

<?php $counter++; }
wp_reset_query(); ?>

A: Your issue is the fact that PHP is by nature preprocessed. JavaScript doesn't run that PHP everytime you click that marker.
Your best bet is to output a JSON object from PHP containing all the markers and their attributes, then parse it dynamically with JavaScript.


text:
Q: Paypal Return Message 3005 on Sandbox Account I am using Paypal sandbox for recurring payment system. my  express check out payment for initial payment is working proper and also create Recurring Payments Profile in sandbox. But when i searching the transaction i am getting the below error.
Sorry — your last action could not be completed
If you were making a purchase or sending money, we recommend that you check both your PayPal account and your email for a transaction confirmation after 30 minutes.

If you came to this page from another website, please return to that site (don't use your browser's Back button) and restart your activity.
If you came from PayPal's website, click the PayPal logo in the upper-left corner to return to our home page and restart your activity. You might have to log in again.
We are sorry, we are experiencing temporary difficulties. Please try again later. If this error occurred while making a payment, avoid duplicate payments by checking your Account Overview before resending a payment.
For some browsers, this problem can be resolved by clearing or deleting cookies.
Message 3005
I have also enable recurring payment in seller account.


text:
Q: Spring ReflectionUtils#findMethod cannot find java.lang.String#codePointBefore how to find method String#codePointBefore, i tried
ReflectionUtils.findMethod(String.class, "codePointBefore");
ReflectionUtils.findMethod(String.class, "codePointBefore", Integer.class);

it's not work.
test environment:

*

*jdk11

*spring-core 5.3.12

A: Thanks to @VGR
ReflectionUtils.findMethod(String.class, "codePointBefore", Integer.TYPE);
ReflectionUtils.findMethod(String.class, "codePointBefore", int.class);


text:
Q: Translate Animation stuck the code game I have serious problem in my game which I'm developing right now in android studio. The problem is as follow:
I have 2 activities, one the activity of the game, and the other is the activity of the menu.
When the activity of the menu is created, I have translate animation which starting right in the onResume() method of the activity. This is the animation:
TranslateAnimation outAnim = new TranslateAnimation(0f, w, 0f, 0f);
    outAnim.setInterpolator(new LinearInterpolator());
    outAnim.setRepeatCount(Animation.INFINITE);
    outAnim.setDuration(10000);
    mBackGround1.startAnimation(outAnim);

The problem happens when I go from the game activity to the menu activity( using startActivity(new Intent(...) ), and then the game activity does not get closed until the animation is finished !! ( It supposed to get closed because I used startActivity Method) e.g, the onPause() method of the activity is called, but the onStop() method is not called !! It is called only after the first animation repeat is finished, meaning after 10 sec.
And this is causing me a lot of problems because if the user wants to go back to the activity of the game, while it is not closed, the lifecycle is getting crazy, and I cant understand nothing.
So my question is:
Why does the animation block,stop, and make the code "stuck" for 10 sec ? how can I make the animation to not stuck the code, if its even possible ?
More info:
When I disable the code of the animation, the onStop() method is getting called right after the game activity is closed, which confirm to me that the animation is the problem.


text:
Q: Need HELP! with - SQL Plus Select multiple columns Hi I am using sql plus and I need to select 5 columns from 4 tables and show the result. This is the code that i used and the error I get.
SELECT CustomerID, OrderID, AircraftID, Quantity, TotalCost
FROM Customer_Table, Order_Table, Aircraft_Table, Orderline;

ERROR at line 1:  ORA-00918: column ambiguously defined

What is the code to get these columns and display them from multiple tables. Please help with this.

A: The reason is  that you tried to execute an SQL statement that joined two or more tables, where a column with the same name exists in both tables.
Exemple with this SQL query
SELECT suppliers.supplier_id, quantity
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;

Since the supplier_id column exists in both the suppliers and orders table, you need to prefix the column with the table name as follows:
Moreover you need to link your tables between them. If I take the example above you should do this kind of thing
WHERE suppliers.supplier_id = orders.supplier_id;

Means you link the table suppliers with the table orders by the column supplier_id
This article may help you to understand about your issue:
http://www.sitepoint.com/understanding-sql-joins-mysql-database/

A: I don't know SQL plus specifically but in most SQL variants you should specify a table name then a column name. Such as SELECT Customer_Table.CustomerID ...... this will disambiguate which column should be used in the result projection.

A: The error means one or more of those columns exist with the same name in those tables. Thats why it does not know which column to select from what table. If you could specify the table name and then the column, I think this should go away.


text:
Q: How do I establish a connection to MySQL via VB & display simple query results on a form? I have a project in Visual Studio 2008 and there is a working data connection to a MySQL database.  In other words, I can query the db directly from Visual Studio and it will display the results.
I've tried a couple of approaches that I found online for writing a connection string and accessing the db, but no luck yet.
All I'm trying to do is code a button to query the db and then reset the text property of a label/textbox to display the results based upon another label/textbox value.
The pseudo-code I am imagining is something like this:
    Private Sub query_submit_button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles query_submit_button.Click
        result_textbox.Text = SELECT field FROM table WHERE otherfield = key_textbox.Text
    End Sub

I didn't see any related questions posted on SO - forgive me if I missed one that already exists and this is a dupe.
What is the correct way to accomplish this?

EDIT
Using MySQL 5.1

A: You can download the ODBC Provider and then reference, import, and use it to query the database through a ODBCCommand instance.
'Put this at the very top of your .VB file...
Imports System.Data.ODBC

'Put this in some method in your code when you are ready to query the DB...
Using connection As New OdbcConnection(connectionString)
    Dim command As New OdbcCommand(strSqlQuery, connection)
    connection.Open()
    result_textbox.Text = command.ExecuteScalar.ToString
End Using

A: i used DaMartyr's answer to get 99% there, but needed to add this declaration:
Dim connectionString As String = "driver={MySQL ODBC 5.1 Driver};server=SERVER;uid=USERID;pwd=PASSWORD;database=DATABASE"

just replace the SERVER, USERID, PASSWORD, & DATABASE with your personal settings


text:
Q: .htaccess rewrite links and src I currently have an imported a site from a server which has its resources something like this:
<img src="/dir/bunch_of_diff_stuff">
<script src="/dir/bunch_of_diff_stuff">
<link href="/dir/bunch_of_diff_stuff">

Basically, I access this site on my local environment like this in the browser:
localhost/~username/folder/project-1/html/

However, since the resources are written with the "/" directory prefix, it's loaded as:
localhost/dir/bunch_of_diff_stuff

What should I write in my .htaccess so the resources will be loaded as:
localhost/~username/dir/project-1/html/dir/bunch_of_diff_stuff

A: You can use this rule in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteRule ^(dir/.*)$ /~username/$1 [L,NC,NE,R=302]


text:
Q: Is $[1,\infty ) $closed? If $(-\infty ,1) $ is open, then the compliment should be closed. Right?
I'm asking because the interval otherwise looks like a half-open interval.
Thanks in advance!

A: It depends from the topological space. If you are talking about the usual topology in $R$, then it is a closed set.

A: Hint:

*

*If an interval is open, every point of that interval is an interior point.

*If it is closed, it contains all its limit points.

A: A set is closed iff it contains all its limit points.
A limit point is a point $x$ in the set such that $\forall \epsilon > 0$ there exists a $y$ also in the set such that $y \neq x$ and $|y-x |< \epsilon $.
So, if $x \in (1, \infty)$, then by the denseness property of the reals we may take $\epsilon$ sufficiently small so that there exists a $y \in (1,\infty)$ such that $|y-x|<\epsilon$.
Similiarly, if $x=1$ there exists a $y \in (1, \infty)$ such that $y-x < \epsilon$


text:
Q: Returning the last two set of records mySQL well, i'm new to MySQL Database and i got a problem, i need to get the last two set of records from a table ( the records are automatically added to this table every week) i need to use to find the growth that an entity did during the last week.
can any one help plz.
here is what i wrote, i tested it on my local host and it worked :D, but when we installed it online, it crashed :(
select pages.*, new.* from (
select id, tableone.page_id, one, two,(two - one) as diff from
(SELECT id, page_id, likes as two FROM `page_records` WHERE id IN ( SELECT max( id )    FROM `page_records` GROUP BY page_id )) as tableone left join
(SELECT page_id , likes as one  FROM `page_records` where id in ( SELECT max(id) FROM   `page_records` where id not in (select max(id) from `page_records` group by page_id) group      by page_id))
as tabletwo
on tableone.page_id = tabletwo.page_id
order by tableone.page_id asc) as new inner join pages on pages.id = new.page_id

Thanks in advance.

A: try:
    SELECT id, page_id, likes FROM page_records order by id desc limit 0, 2

A: Try this:
SELECT * FROM table_name
ORDER BY id DESC
LIMIT 0, 2

Thanks!


text:
Q: how to handle non-periodic timeseries in bfast (R) my problem is the following : I have a Landsat NDVI time series that is non-periodic/doesn't have a homogenous frequency. However, the error code I receive is
Error in stl(Yt, "periodic") : series is not periodic or has less than two periods
after having tried to convert my data into a timeseries without explicitely setting a frequency :
test_timeseries <-ts(test$nd, start = c(1984,4), end = c(2011,10)). when I try to calculate the frequency or deltat with the help of the functions frequency() or deltat(), it both leads to 1 - which I don't understand , as I have non-periodic data for nearly every month and not only once a year.
So my question is, how to set the frequency in this case and how to deal with this circumstance of non-periodicity ? It seems like, without setting a frequency, I cannot use the function bfast().
sorry if the answer is obvious, I'm very new to timeseries analyses.

A: Please read the help file. It helps. In this case, it describes the following argument.

season : the seasonal model used to fit the seasonal component and detect seasonal breaks (i.e. significant phenological change). There are three options: "dummy", "harmonic", or "none" where "dummy" is the model proposed in the first Remote Sensing of Environment paper and "harmonic" is the model used in the second Remote Sensing of Environment paper (See paper for more details) and where "none" indicates that no seasonal model will be fitted (i.e. St = 0 ). If there is no seasonal cycle (e.g. frequency of the time series is 1) "none" can be selected to avoid fitting a seasonal model.

So set season = "none" in bfast().


text:
Q: Google Analytics Measurement Protocol and Enhanced e-commerce not capturing revenue I'm trying to use the measurement protocol to record an offline purchase on our backend system. The problem is, after I send the Measurement Protocol request, the goal conversion is captured correctly in GA's reports, but the revenue earned from the purchase is always displayed as 0.00 in the reports, even though I am sending a value of 500.00 in the revenue parameter.
Here is the request I am sending to the measurement protocol:
https://www.google-analytics.com/collect?
v=1
&tid=UA-XXXXXXXXXX
&cid=XXXXXXX.XXXXXX
&uid=123
&t=pageview
&dh=http://example.com
&dp=order/thank_you
&dt=thank+you
&ti=127210
&ta=offline+conversion
&tr=500.00
&pa=purchase
&pr1id=1864
&pr1nm=Abc+Program
&pr1ca=Software
&pr1pr=500.00
&cu=CNY
&sc=end
&aip=1

The next day, when I check GA's Conversions reports, the goal conversion is tracked successfully, but the e-commerce report always displays the revenue earned for this purchase as 0.00, even though I've specified the price to be 500.00 in the request.  I've already tried the following tasks to resolve the problem, but to no avail:

*

*Double-check that Enhanced E-commerce is enabled in GA (it is).

*Change &t=pageview to &t=transaction, but this modification results in neither the goal nor the revenue to be captured in GA.

*Re-constructed the request in Google's Hit Builder and validated the hit (it is valid)

*Sent the request to /debug/collect to validate the hit (it is valid). Below is the response:
 "hitParsingResult": [ {
    "valid": true,
    "parserMessage": [ {
      "messageType": "INFO",
      "description": "IP Address from this hit was anonymized to 106.111.63.0.",
      "messageCode": "VALUE_MODIFIED"
    } ],
    "hit": "/debug/collect?v=1\u0026tid=UA-XXXXXXXX-X\u0026cid=XXXXXXXXX.XXXXXXXXXX\u0026uid=123\u0026t=pageview\u0026dh=http%253A%252F%252Fmydomain.com\u0026ti=127210\u0026ta=offline%20conversion\u0026tr=500.00\u0026pa=purchase\u0026pr1id=1864\u0026pr1nm=Abc%20Program\u0026pr1ca=Software\u0026pr1pr=500.00\u0026cu=CNY\u0026sc=end\u0026aip=1"
  } ],
  "parserMessage": [ {
    "messageType": "INFO",
    "description": "Found 1 hit in the request."
  } ]

Here is the screenshot of the above purchase in GA's conversion reports:

As shown above, the revenue from the purchase is 0.00, even though the revenue I sent to GA is 500.00.
Any idea why Google is not tracking the revenue?
Would also appreciate any thoughts on how to better troubleshoot this issue... because Google's /debug/collect script is not providing much insight into the problem. Any idea what other approaches to take for troubleshooting this?
Thanks!

A: Okay, found the problem. I didn't include the quantity of product purchased in the request data. In order for revenue to be tracked, you not only have to provide the product price (pr1pr), you also have to provide the product quantity (pr1qt).
So, I added the following parameter into the Measurement Protocol request:
&pr1qt=1

And now revenue is being tracked successfully.


text:
Q: How to remove the WordPress logo from login and register page? I want to remove WordPress logo from login and register page. I think I have to make some changes in .css file for this. So I want to know in which css file do I have to make the changes?

A: You can add a filter to login_head. As explained in the Codex, add this to your code:
function my_custom_login_logo() {
    echo '<style type="text/css">
    h1 a {background-image:url(http://example.com/your-logo.png) !important; margin:0 auto;}
    </style>';
}
add_filter( 'login_head', 'my_custom_login_logo' );

A: To remove the WordPress logo, paste the below code in functions.php of the theme directory.
function remove_logo() { ?>
<style type="text/css">
    .login h1 a { display: none; }
</style>
<?php }

add_action( 'login_enqueue_scripts', 'remove_logo' );

A: Go to your website Editor using > Appearance > Editor > function.php and add this before the last line "?>":
/* Remove WP logo from login page */

function custom_login_logo() {
    echo '<style type ="text/css">.login h1 a { display:none!important; }</style>';
}

add_action('login_head', 'custom_login_logo');

A: You can replace the logo using built-in theme editor as explained
in this post.
Step 1:
Login to your WordPress site as admin and go to Media -> Add New to upload a new image and copy the image url.
You can also upload your new logo to the theme's images directory or you can create a new directory to upload the logo. This can be done with the help of web hosting control panel or FTP.
Step 2:
Go to the Admin Dashboard -> Appearance -> Theme Editor.
Step 3:
When the editor opens, find and select functions.php from the right side of the page and add the following code to the end of the page.
function my_custom_logo() { ?>
     <style type="text/css">
         #login h1 a, .login h1 a {
             background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png);
             height:100px;
             width:100px;
             background-size: 100px 100px;
             background-repeat: no-repeat;
             margin-bottom: 10px;
         }
     </style>
 <?php }
add_action( 'login_enqueue_scripts', 'my_custom_logo' );

Replace logo.png with the name of the file you have uploaded. If you have uploaded the new logo with WordPress, modify the background-image property as shown below.
background-image: url(url copied in step 1);

A: You don't need to go through the coding, use Custom Login plug-in to do that

A: It's best to run this after login_enqueue_scripts as mentioned by @ashin above
I'll post this since it relates to changing the logo.
To change the URL from wordpress.org to your own (along with the links title attr), use this:
    function my_login_logo_url() {
        return home_url();
   }
    add_filter( 'login_headerurl', 'my_login_logo_url' );

    function my_login_logo_url_title() {
        return 'Your Site Name and Info';
    }
    add_filter( 'login_headertitle', 'my_login_logo_url_title' );

If you want to get crazy with styling, here is the css used to edit the entire login page:
body.login {}
body.login div#login {}
body.login div#login h1 {}
body.login div#login h1 a {}
body.login div#login form#loginform {}
body.login div#login form#loginform p {}
body.login div#login form#loginform p label {}
body.login div#login form#loginform input {}
body.login div#login form#loginform input#user_login {}
body.login div#login form#loginform input#user_pass {}
body.login div#login form#loginform p.forgetmenot {}
body.login div#login form#loginform p.forgetmenot input#rememberme {}
body.login div#login form#loginform p.submit {}
body.login div#login form#loginform p.submit input#wp-submit {}
body.login div#login p#nav {}
body.login div#login p#nav a {}
body.login div#login p#backtoblog {}
body.login div#login p#backtoblog a {}


text:
Q: updating blackberry playbook app on store We have our "Hello-Hello Spanish" application ready for sale on blackberry  app world. Earlier, We have created this application by using  flex builder. Since now playbook OS 2.0 comes out, we are planning to convert our existing  android application :- "Hello-Hello Spanish"  to blackberry playbook app using app player.
We have already repackage the application from android to blackberry and want to send as a update for our existing  app on app world.But we are getting the following error while uploading:-"File bundle (Hello_Hello_Spain.bar) has been rejected. Package ID is required for all .bar file. If this is an upgrade, Package ID must match Package ID in original file bundle."
This error clearly show that our new app product ID does not match with the existing app product ID on app world. but we can not put the same product ID as we have in our existing app. because in our earlier app we have the product ID:- "HHSpanish" but in  our latest version app product ID name is:- "com.hello-hello.HHSpanish". We can not change this android app Product ID as android  project need  product ID at least in 2 segment( for example:- com. abcd).So we are not able to put the same Product ID as we have before.
How can we solve this problem and can send our application as an updated to our existing app?
Another question is:- Does blackberry  playbook have any kind of promo code of app or any gift mechanism  that we can give it to our users so that they can download  our  paid app for free from app world? if not,  please tell us  how can i gift my app to user for free?

A: There is actually no way to gift your app to customers through AppWorld, BTW, it would have been preferable to post each question in a separate thread.