text:
Q: key: highway from pbf format file of OSM map I downloaded a PBF format of a region of OSM map. Is it possible to extract the value of KEY:HIGHWAY from this file using osmosis. The situation is I will give a location in lat/log (output of GPS) and I need to get the value of key HIGHWAY from the file. Is it possilbe? If anyone have the codes please provide it.

A: The OSM wiki has osmosis example usages. This paragraph also mentions how to extract all highways:
osmosis --read-xml city.osm --tf accept-ways highway=* --used-node --write-xml highways.osm

Don't use this approach for an interactive router. Extracting these information on the fly will be slow and inefficient. Instead do this step once (including all information relevant for routing, not just highway tags) and calculate a routing graph on top of these ways. Or better just use one of the existing end user routing softwares for OSM.


text:
Q: Multiple signals requires multiple filters? So, this might seem rather basic, but I'm going to pose it in the hope that I can save some work. So, I have a series of electrodes that are sensitive to voltage fluctuations, but, before I pass the data into the Arduino and then into the computer, I wanted to create a circuit that acts as a bandpass filter in order to reduce 60hz noise from appliances as well as to limit the read frequencies.
Though, I plan on using a good number of electrodes (either 16 or 32 as of right now) so, rather than running each individual electrode through a separate bandpass filter, is it possible to apply these filters by passing multiple electrode signals through a single or a smaller number of filters rather than having to build one filter for every input? Thanks in advance for any insight you guys can provide.

A: The only possible way you could to that is through a technique called Time Division Multiplexing.
This involves you having a set of analog switches to select one of your incoming signals at a time for filtering. You can only read one signal at a time, and each one for a period longer than you need for the filtering to have any effect.
Also this would probably increase your noise in your signal in the first place.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VerticalSrollBar is incrementing value twice in vb.net Public Class Form1
    Dim val As Integer = 0
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        VScrollBar1.Minimum = 0
        VScrollBar1.Maximum = 100
        VScrollBar1.Value = 0
    End Sub
    Private Sub VScrollBar1_Scroll(sender As Object, e As ScrollEventArgs) Handles VScrollBar1.Scroll
        If val < 101 Then
            val = val + 10
            TextBox1.Text = val
            VScrollBar1.Value = val
            TextBox1.Font = New Font("Microsoft Sans Serif,", VScrollBar1.Value)
        Else
        End If
    End Sub
End Class

This code has one more issue, value is incrementing no matter you are scrolling upward or downward.
I Have tried to debug it by placing Vscroll value in textbox. May you please help me to solve this issue.

A: You are only telling it to increment val with val = val + 10. The ScrollEventArgs can be used to determine if the scrollbar is scrolling upwards or downwards.
Private Sub VScrollBar1_Scroll(sender As Object, e As ScrollEventArgs) Handles VScrollBar1.Scroll
    If e.Type = ScrollEventType.LargeIncrement OrElse e.Type = ScrollEventType.SmallIncrement Then
        val = val + 10
    Else
        'Decrement val or do nothing here. I've assumed that you are wanting to decrement val

        val = val - 10
    End If

    TextBox1.Text = val
    TextBox1.Font = New Font("Microsoft Sans Serif,", VScrollBar1.Value)
End Sub

A: *

*You're changing the VScroll value in the Scroll event which makes no sense! You're supposed to read the scroll value in this event or to undo the new value. Check the e.OldValue and e.NewValue properties.

*Make sure that you assign a valid value for the Minimum property of the VScroll that respects the minimum size of the font which is not equals 0. At least 1.
Trying to Guess what are you trying to do, I'd suggest the following:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    VScrollBar1.Minimum = 1
    VScrollBar1.Maximum = 109
    VScrollBar1.Value = Font.Size
End Sub

Improved version by jimi
Private Sub VScrollBar1_Scroll(sender As Object, e As ScrollEventArgs) Handles VScrollBar1.Scroll
   Dim fs As FontStyle = Font.Style

   TextBox1.Font.Dispose()

   TextBox1.Font = New Font("Microsoft Sans Serif", e.NewValue, fs, GraphicsUnit.Point)
End Sub

Good luck.

A: This code is correct, I have achieved what I wanted to achieve. Now, this code is increasing And decreasing TextBox font size, smoothly.
Public Class Form1
    Private Sub VS_Scroll(sender As Object, e As ScrollEventArgs) Handles VS.Scroll
        txtbx.Font = New Font("Microsoft Sans Serif", VS.Value)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        VS.SmallChange = 5
        VS.LargeChange = 20
        VS.Minimum = 10
        VS.Maximum = 100
    End Sub
End Class


text:
Q: Parsing out everything between characters X number of times I have a table (AW) with a field in which I need to parse out everything between the pipe '|' for each RecordID and find out if any of the parses start with an S. Since this field has a varied amount of strings between the pipes '|' how would I programatically do this without assuming the number of parses need to be done.
select RecordID, DealID from AW

|-RecordID-|------------------------DealID----------------------------------|
3000449*1   66411/10*ACME01*PLI*PY**|94084/10*ACME01*PLI*PY**
2703781*90  91715/10*P8*PLI*FFR**CS|91719/10*P8*PLI*FFR**CS
2703781*7   91715/10*P8*PLI*FFR**CS|91719/10*P8*PLI*FFR**CS|S118849.13/10**PM*22076*01*CS
CM2903835*1 106834/10*FT*PM*FT*01*CS|108807/10*FT*PM*FT*01*CS
3000801*19  S124374.52/10*DM*PM*00080*01*CS
3004043*9   91714/10*P8*PLI*DR**CS|84767/10*P8*PLI*DR**CS
3004043*130 S119765.34/10*P8*PM*38808*01*CS|91714/10*P8*PLI*DR**CS|84767/10*P8*PLI*DR**CS

This is using SQL Server


text:
Q: Correct way to cache data in vuex I am trying to asynchronously load data into vuex that is static but is used by multiple routes.I only want to fetch the data once and only when a route that needs it is visited. This is what I'm currently doing but I'm not sure if this is the correct convention or if there is a better/more Vueish way.
// store.js

export default new Vuex.Store({
  state: {
    _myData: null,
  },
  getters: {
    myData: (state) => new Promise((resolve,reject) => {
      if(state._myData){
        resolve(state._myData);
      } else {
        axios.get('http://myData.com/')
        .then(myData => {
          state._myData = myData;
          resolve(state._myData);
        });
      }
    })
  }
});

// ProfilePage.vue

<template>

{{myData}}

</template>

// AboutPage.vue

<template>

{{myData}}

</template>

A:
Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call context.commit to commit a mutation, or access the state and getters via context.state and context.getters.
  https://vuex.vuejs.org/guide/actions.html

try this:
// AnyPage.vue

<template>

{{myData}}

</template>

in store file:
// store.js

export default new Vuex.Store({
  state: {
    myData: null,
  },
  mutations: {
    SET_DATA(state, data) {
      state.myData = data
    }
  }
  actions: {
    getData({ context }){
        if (context.state.myData === null) {
            axios.get('http://myData.com/')
            .then(res => {
                context.commit('SET_DATA', res)
            })
        }
      }
    }
  }
});

A: There is a correct way to do what you want but it is not the way you are doing it. Vue is quite strict on "Do not mutate vuex store state outside mutation handlers."
This means you should only alter the store state through a mutation, then use your getter only to get the data. You should also use an action to commit the mutation. So for what you are trying to do you should try it like this.
// AnyPage.vue

<template>

{{myData}}

</template>

then in your store:
// store.js

export default new Vuex.Store({
  state: {
    _myData: null,
  },
  getters: {
    myData: (state) => state._myData,
  }
  mutations: {
    SET_DATA(state, data) {
      state._myData = data
    }
  }
  actions: {
    getData({ context }){
        axios.get('http://myData.com/')
        .then(res => {
          context.commit('SET_DATA', res)
        })
      }
    }
  }
});

You should read up in the docs which covers it all pretty well.


text:
Q: Kotlin multiplatform, iOS/Android. Использование платформенных типов в актуальных реализациях Теоретическая часть вопроса.
У меня есть общий data-класс со свойством, реализация класса которого зависит от платформы
class Accident(
    ...
    val location: AccidentLocation
)

expect class AccidentLocation {
    fun distanceTo(point: AccidentLocation): Double
}

У android'a и у iOS'а свой подход к работе с местоположением и было бы логично использовать нативные классы/методы для реализации актуальных классов.
Например для android'a
actual class AccidentLocation(val location: Location, val address: String) {
    actual fun distanceTo(point: AccidentLocation): Double {
        return location.distanceTo(point.location)
    }
}

Вопрос: я правильно понимаю принцип мультиплатформенности от Kotlin?
Практическая часть вопроса.
Я никак не могу добиться того, чтобы в android-части мультиплатформенного модуля были видны необходимые библиотеки.
gradle.build для общего кода (по сути копипаста из руководства)
apply plugin: 'kotlin-multiplatform'

kotlin {
    targets {
        final def iOSTarget = System.getenv('SDK_NAME')?.startsWith("iphoneos")  \
                               ? presets.iosArm64 : presets.iosX64

        fromPreset(iOSTarget, 'iOS') {
            compilations.main.outputKinds('FRAMEWORK')
        }

        fromPreset(presets.jvm, 'android')
    }
    sourceSets {
        commonMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib-common'
        }

        androidMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib'
            api "com.google.android.gms:play-services-location:16.0.0"
        }
    }
}

configurations {
    compileClasspath
}

Студия в упор не видит содержимого com.google.android.gms:play-services-location:16.0.0 и, соответственно, импортировать Location никак не получается.
Вопрос: Что я делаю не так?

A: Этот класс, нормально себе импортируется.
https://developer.android.com/reference/android/location/Location
И вот этот из com.google.android.gms:play-services-location тоже

com.google.android.gms.location.FusedLocationProviderClient

Не то или не там ищете, похоже.


text:
Q: Add item to Owner Window ListBox i'm actually trying to do add an element to an ListBox wich is in the Owner Window
I tried to use the Owner Windows property but i can't access my ListBox.
Window parent = this.Owner;
parent.toto.Items.Add();

I also tried to add a public property in my Owner Window class (and add the item on the set method), but i can't access it neither.

A: The type of the Owner property is Window.  The compiler doesn't know that it is actually the type you created.  If you perform a cast, and your ListBox is exposed publicly, you should be able to access it:
YourWindowType parent = (YourWindowType)this.Owner;
parent.toto.Items.Add(...);

A: Try

Window parent = this.ActiveForm;


text:
Q: android trigger another project activity This problem freak me out
I have an application and now i want to transer data between client android application and localhost tomcat 7 server, i did that many times ago, now when i want to send data from client to server it works well and i can see the data on the server, but something happend and the android application is trying to trigger an activity from another project i deleted that project then still try to trigger activty form another project
my actiivty name is "Signup", and the android client trying to trigger activiteis with the same name from another projects.

A: as in log :

NumberFormatException: unable to parse
  '[Lorg.apache.http.Header;@44ee4c10' as integer

means you are trying to parse wrong string to Integer . wrap casting code inside try/catch block to avoid NumberFormatException as :
String str_NumberOfCities="";
 Header[] headers = response.getAllHeaders();
  for (int i=0; i < headers.length; i++) {
         Header h = headers[i];
          Log.i(TAG, "Header names: "+h.getName());
          if(h.getName().toLowerCase().contains("NumberOfCities".toLowerCase()){
                str_NumberOfCities=h.getValue();
           }
      Log.i(TAG, "Header Value: "+h.getValue());
  }
int numberOfCities=0;
 try {
       numberOfCities = Integer.parseInt(str_NumberOfCities);
   } catch (NumberFormatException e) {
       numberOfCities=0;
    }
Data.cities = new String[numberOfCities];
///....your code


text:
Q: 2100 error on lenovo e550 laptop, But linux lives boots each time Before mark this question as duplicate Please read it completely.
I have a lenovo thinkpad e550 and I encounter this error in boot time:
2100: Detection error on HDD0 (Main HDD)
Press Esc to continue.

I read about this problem in this question on same site. But my case is a little different. I Asked a question on askubuntu about this about two weeks ago. heynnema's solution worked this two weeks, But again the problem happend.
In My case I can Boot Live Linux on USB and DVD very well each time. I live Linux I tested the hard partitions they were working well. I could write and read on them. I reinstalled my ubuntu. But the problem persists and I can just boot live Linux and after that I can retrieve my hard drive data in it. (I tried windows bootable disk, it even not booted)
Can Bios be the problem? Cause I really Don't think Hard Disk has any problem.
Any help will be appreciated.

A: I Am not sure why this happens!!!!
After I open my laptop, (just first part for HDD and RAMS), I take out the hard drive and place it back again! It worked! I hadn't any other problem with boot since last month!


text:
Q: react redux useSelector rerender even when data does not change I am using react with redux and redux thunk.
I have an action where I am making a network request.
With the useSelector I am getting the data from redux store.
I have a problem that the component rerenders every time when I dispatch the action.
I want that the component only rerenders when data changes.
I tried already use shallowEqual as the second argument for useSelector. But it does not work.
I have compressed it to minimal example in this sandbox. In the console you can see that the component rerenders with every network request.
Here is the codesandbox:
https://codesandbox.io/s/useselector-js6j0?file=/src/App.js:885-1294
here is the code:
function LevelThree() {
  console.log(`Level three calls: ${++levelThreeCalls}`);
  const contextData = useSelector(state => state.data);
  console.log(contextData);
  const dispatch = useDispatch();
  useInterval(() => {
    dispatch(updateData());
  }, 1000);

  return (
    <div>
      <button onClick={() => dispatch(updateData())}>Change context</button>
      {contextData[0].userId}
    </div>
  );

}

A: When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render

A: The reason that your component is re-rendering on every update is because you are fetching the data again and updating it in redux store,
Since the reference of data changes, the useSelector function returns you a new value and re-renders the component.
You can pass a deepEqual comparison function as a second argument to useSelector to avoid re-rendering it data hasn't changed
import _ from 'underscore';
...
const contextData = useSelector(state => state.data, _.isEqual);

However, you must carefully use this and measure how frequently your data will be updated otherwise you will add an added calculation in your code which won't even prevent a re-render many times
Working demo


text:
Q: How to create a checklist with a bat file/batch script in the console window? I'm looking to create a checklist in a console window to help users choose certain options they would like to install. This kind of output:
Please select options to install:
[x]Option 1
[ ]Option 2
>[x]Option 3
[x]Option 4

Where the user can move the cursor throughout the list and select the options.
I have a very, very vague idea of how I might do this code, testing with just two options. But if there is anyone who already has a solidified idea of how this would work and could share I would be very appreciative!
Test code for those who want to see it:
@echo off

call:main
end /b 0

:main
set /p choice= "Would you like to enable option one? (yes/no): "echo(
if %choice%==yes (
    set option1=1
)
if %choice%==no (
    set option1=0
)
call:mod1
set /p choice= "Would you like to enable option two? (yes/no): "echo(
if %choice%==yes (
    set option2=1
)
if %choice%==no (
    set option2=0
)
call:mod2

:mod1
if %option1%==1 (
echo [x] Option 1
)
if %option1%==0 (
echo [ ] Option 1
)

:mod2
if %option2%==1 (
echo [x] Option 1
)
if %option2%==0 (
echo [ ] Option 1
)

A: You could try this:
@echo off
setlocal EnableDelayedExpansion

for /f %%A in ('"prompt $H &echo on &for %%B in (1) do rem"') do set BS=%%A
set "getKeyMacro=powershell -noprofile "^
    while (-not (37..40+13).contains($x)) {^
        $x = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode^
    }^
    if ($x -eq 13) {^
    'enter'^
    }^
    ('left','up','right','down')[$x - 37]^
""

set "option1=0"
set "option2=0"
set "option3=0"
set "option4=0"
set "selected=1"
:select
cls
echo use ^<right^> arrow to continue, ^<up^> and ^<down^> to select, and ^<enter^> to toggle
FOR /L %%G IN (1,1,4) DO (
set "display=[ ]"
if !option%%G! equ 1 set "display=[x]"
if %%G equ !selected! set "display=^>!display!
echo !display! Option %%G
)
FOR /F "delims==" %%G IN ('%getKeyMacro%') DO set "key=%%G"
if "%key%"=="up" set /a "selected-=1"
if "%key%"=="down" set /a "selected+=1"
if %selected% lss 1 set "selected=1"
if %selected% gtr 4 set "selected=4"
if "%key%"=="enter" goto toggle
if "%key%"=="right" goto OK
goto select

:toggle
set /a "option%selected%+=1"
set /a "option%selected%=!option%selected%!%%2"
goto select

:OK
FOR /L %%G IN (1,1,4) DO (
if !option%%G! equ 1 (
echo %%G selected
)
)
pause

Note that this is very heavily dependent on Delayed Expansion, so you might want to read up on it here.
Second note: this needs powershell so you can use up and down arrow keys to select options, enter to toggle currently selected option, and right arrow to continue.
EDIT
Updated version, this allows you to set the display names for the options, but you need to specify the amount of options aswell:
@echo off
setlocal EnableDelayedExpansion

for /f %%A in ('"prompt $H &echo on &for %%B in (1) do rem"') do set BS=%%A
set "getKeyMacro=powershell -noprofile "^
    while (-not (37..40+13).contains($x)) {^
        $x = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode^
    }^
    if ($x -eq 13) {^
    'enter'^
    }^
    ('left','up','right','down')[$x - 37]^
""

set "option1=0"
set "option2=0"
set "option3=0"
set "option4=0"
set "option1name=Install thing 1"
set "option2name=Do thing 2"
set "option3name=Execute thing 3"
set "option4name=Run thing 4"
set "maxOptions=4"
set "selected=1"
:select
cls
echo use ^<right^> arrow to continue, ^<up^> and ^<down^> to select, and ^<enter^> to toggle
FOR /L %%G IN (1,1,%maxOptions%) DO (
set "display=[ ]"
if !option%%G! equ 1 set "display=[x]"
if %%G equ !selected! set "display=^>!display!
echo !display! !option%%Gname!
)
FOR /F "delims==" %%G IN ('%getKeyMacro%') DO set "key=%%G"
if "%key%"=="up" set /a "selected-=1"
if "%key%"=="down" set /a "selected+=1"
if %selected% lss 1 set "selected=1"
if %selected% gtr %maxOptions% set "selected=!%maxOptions%!"
if "%key%"=="enter" goto toggle
if "%key%"=="right" goto OK
goto select

:toggle
set /a "option%selected%+=1"
set /a "option%selected%=!option%selected%!%%2"
goto select

:OK
FOR /L %%G IN (1,1,%maxOptions%) DO (
if !option%%G! equ 1 (
echo %%G selected
)
)
pause

EDIT #2
Now uses the for loop by @Aacini to initiate the variables so this only needs to happen once, and so there is no need for a manual maxoption any more:
@echo off
setlocal EnableDelayedExpansion

set "getKeyMacro=powershell -noprofile "^
    while (-not (37..40+13).contains($x)) {^
        $x = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode^
    }^
    if ($x -eq 13) {^
    'enter'^
    }^
    ('left','up','right','down')[$x - 37]^
""

set "num=0"
for %%a in ("Install thing 1"
            "Do thing 2"
            "Execute thing 3"
            "Run thing 4") do (
   set /A num+=1
   set "option!num!=0"
   set "option!num!name=%%~a"
)
set "maxOptions=%num%"
set "selected=1"
:select
cls
echo use ^<right^> arrow to continue, ^<up^> and ^<down^> to select, and ^<enter^> to toggle
FOR /L %%G IN (1,1,%maxOptions%) DO (
set "display=[ ]"
if !option%%G! equ 1 set "display=[x]"
if %%G equ !selected! set "display=^>!display!
echo !display! !option%%Gname!
)
FOR /F "delims==" %%G IN ('%getKeyMacro%') DO set "key=%%G"
if "%key%"=="up" set /a "selected-=1"
if "%key%"=="down" set /a "selected+=1"
if %selected% lss 1 set "selected=1"
if %selected% gtr %maxOptions% set "selected=!%maxOptions%!"
if "%key%"=="enter" goto toggle
if "%key%"=="right" goto OK
goto select

:toggle
set /a "option%selected%+=1"
set /a "option%selected%=!option%selected%!%%2"
goto select

:OK
FOR /L %%G IN (1,1,%maxOptions%) DO (
if !option%%G! equ 1 (
echo %%G selected
)
)
pause

A: @echo off
setlocal EnableDelayedExpansion

rem Define the text for the options
set "num=0"
for %%a in ("First option"
            "Second option"
            "Third option"
            "Fourth option") do (
   set /A num+=1
   set "msg[!num!]=%%~a"
   set "opt[!num!]= "
)
set "digits=0123456789"

:select
   (cls
   echo Press digit to mark/unmark options, or X to end
   echo/
   for /L %%i in (1,1,%num%) do echo !digits:~%%i,1!. [!opt[%%i]!]  !msg[%%i]!
   )
   choice /C !digits:~1,%num%!X /N > NUL
   if %errorlevel% gtr %num% goto endSelect
   set "sel=%errorlevel%"
   if "!opt[%sel%]!" equ "X" (set "opt[%sel%]= ") else set "opt[%sel%]=X"
goto select
:endSelect

echo/
echo/
for /L %%i in (1,1,%num%) do (
   if "!opt[%%i]!" equ "X" (
      echo %%i selected
   )
)


text:
Q: Bott-Samelson theorem for simplicial sets Let $X\in \mathrm{sSet}$ and $FX$ be the Milnor's construction (model for $\Omega\Sigma |X|$) - in each dimension $n$ this is the free group on $X_n$ with one relation $*=1$. I'm interested in $\mathbb Z FX$ - the level-wise group ring on this construction - which homotopy groups gives the integral homology of $FX$. From the classical Bott-Samelson theorem we know that (over the field) homology of $\Omega\Sigma |X|$ as Hopf algebra is isomorphic to the tensor algebra on reduced homology of $X$ (as far as I understand, restriction to field here is given only to ensure Hopf algebra structure on homology). I'm trying to trace this fact back to simplicial level. Note that $\mathbb Z FX$ is also a Hopf algebra (comultiplication is given by diagonal) and homotopy groups of  the abelianization of Milnor's construction are exactly reduced homology of $X$. So my question here: is there a (canonical!) morphism of simplicial Hopf algebras $T(FX_{ab}) \to \mathbb Z FX$ (or in another direction) which is homotopy equivalence on the underlying simplicial sets?
Few observations here:

*

*By Magnus-Witt, associated graded $\bigoplus I^k/I^{k+1}$ of $\mathbb Z FX$ is isomorphic to the tensor algebra $T(FX_{ab})$ as algebras (here $I^k$ are powers of augmentation ideal). Also this augmentation ideal filtration give rise to the cobar spectral sequence $E^1_{p,q}=\pi_p(I^q/I^{q+1})\Rightarrow \pi_{p+q}\mathbb Z FX$. Curtis used the same spectral sequence for Kan's construction $GX$ to compute homology of loop spaces. So, if my question have positive answer, the corresponding spectral sequence should collapse on first page and all extensions should be trivial. Not sure, how to see this and how to extract homotopy equivalence from this spectral sequence. Also, Hopf algebra structure here is a mystery for me. Advantage of this approach is that we would have combinatorial control over elements like $g^{-1}$ in group ring and their image in tensor algebra, since  $g^{-1}-1=-g-1 \ \mathrm{mod} \ I^2$.

*From the short exact sequence of free abelian groups $I\to \mathbb Z FX\to \mathbb Z$ we can choose a splitting (even naturally with respect to $X$ since it serves as a basis) which will give the isomorphism of abelian groups $\mathbb Z FX\cong \mathbb Z\oplus I$. We can continue this process and get an isomorphism of abelian groups between the group ring and it's associated graded. Not sure if homotopy magic will help to turn this "map" to isomorphism of Hopf algebras.

*Another point of view is an isomorphism of simplicial algebras $\mathbb Z JX\cong T(FX_{ab})$, here $JX$ denote free simplicial monoid on $X$ (aka James construction). Now, by theorem of Quillen, group completion $JX\to FX$ is a homotopy equivalence, so looks like we done. But in this approach the inverse of homotopy equivalence is untrackable, so one really can not understand images in tensor algebra of elements like $g^{-1}$ from group ring.
So, all of these observations are different pieces of same puzzle which I can not put together. Will appreciate any help!


text:
Q: why does the union of a generic filter cannot be the zero function? I'm trying to understand some concept of the forcing idea, but I'm having trouble with two questions.
assume that M is countable s.t. $M\models ZFC$, $\mathbb{P}$  is  cohen forcing,  $\mathbb{P}\in M $,and G is an $\mathbb{P}$-genric filter over M.

*

*i already know that $\bigcup G$ is a function $f:\omega \to 2$, why does $f$ cannot be the zero function?

*why does $G\notin M$?

for 1 i know that  $$D=\left\{ p\in\mathbb{P}:1\in\text{rng}\left(p\right)\right\} $$ is dense in $\mathbb{P}$ but i was unable to proof that $D\in M$.
$$$$
Thanks a lot

A: Density, density, density. Almost all forcing arguments of this sort boil down to finding the appropriate dense sets.
For example, why isn't $f$ constant? Because given any $p$, there is an extension of $p$ which takes both $0$ and $1$, which one? Well, for example, just add "on top" of $p$ these two values.
Therefore, the set $\{p\mid \operatorname{rng}(p)=\{0,1\}\}$ is dense. Since it is definable from a formula, this dense set is in the ground model, so $G$ meets it, and therefore some $p\in G$ must have both $0$ and $1$ in its range. Therefore $f$ is not constant.
Similarly, $G$ can't be in $M$ itself, because if $r\in M$, then $\{p\mid\exists n: p(n)\neq r(n)\}$ is a dense set, for the same reason as above. And it is in $M$ because it is definable from $r$, and $M$ is a model of $\sf ZF$, or at least a large enough fragment of it. So this dense set is in $M$, and therefore it meets $G$, and therefore $f$, the generic real, must be different from $r$, for any $r\in M$, and so $f\notin M$.


text:
Q: How to make design css for UI mobile layout in portrait and landscape mode Sample image here
*NB : - The red color is background
      - The blue color is image
How to code the UI from portrait mode to landscape mode in mobile view using CSS/Bootstrap or something else, I'm using ionic to developed this.
this is my code :
<ion-view view-title="Home">
    <ion-content class="padding" style="background-color:#616161">

    </ion-content>
</ion-view>

A: Portrait/Landscape depends upon the device screen-width. When you shift device into Landscape mode its dimensions get reversed i.e, height becomes width and width becomes height. So in order to achieve the above image you need to write  two different "MEDIA QUERIES" with  two different screen width to make it responsive. Post your code.

A: You can use media query for this

Following works on portrait view

@media only screen and (max-width: 640px) and (orientation: portrait) {
   /* Add css here */
}

Following works on landscape view

@media only screen and (max-width: 640px) and (orientation: landscape) {
   /* Add css here */
}

For more detail please visit :
media for orientation
media query


text:
Q: Store values from a loop I am simulating dice throws, and would like to save the output in a single object, but cannot find a way to do so. I tried looking here, here, and here, but they do not seem to answer my question.
Here is my attempt to assign the result of a 20 x 3 trial to an object:
set.seed(1)
Twenty = for(i in 1:20){
  trials = sample.int(6, 3, replace = TRUE)
  print(trials)
  i = i+1
}
print(Twenty)

What I do not understand is why I cannot recall the function after it is run?
I also tried using return instead of print in the function:
Twenty = for(i in 1:20){
  trials = sample.int(6, 3, replace = TRUE)
  return(trials)
  i = i+1
}
print(Twenty)

or creating an empty matrix first:
mat = matrix(0, nrow = 20, ncol = 3)
mat
for(i in 1:20){
  mat[i] = sample.int(6, 3, replace = TRUE)
  print(mat)
  i = i+1
}

but they seem to be worse (as I do not even get to see the trials).
Thanks for any hints.

A: Usually, in most programming languages one does not assign objects to for loops as they are not formally function objects. One uses loops to interact iteratively on existing objects. However, R maintains the apply family that saves iterative outputs to objects in same length as inputs.
Consider lapply (list apply) for list output or sapply (simplified apply) for matrix output:
# LIST OUTPUT
Twenty <- lapply(1:20, function(x) sample.int(6, 3, replace = TRUE))

# MATRIX OUTPUT
Twenty <- sapply(1:20, function(x) sample.int(6, 3, replace = TRUE))

And to see your trials, simply print out the object
print(Twenty)

But since you never use the iterator variable, x, consider replicate (wrapper to sapply which by one argument can output a matrix or a list) that receives size and expression (no sequence inputs or functions) arguments:
# MATRIX OUTPUT (DEFAULT)
Twenty <- replicate(20, sample.int(6, 3, replace = TRUE))

# LIST OUTPUT
Twenty <- replicate(20, sample.int(6, 3, replace = TRUE), simplify = FALSE)

A: There are several things wrong with your attempts:
1) A loop is not a function nor an object in R, so it doesn't make sense to assign a loop to a variable
2) When you have a loop for(i in 1:20), the loop will increment i so it doesn't make sense to add i = i + 1.
Your last attempt implemented correctly would look like this:
mat <- matrix(0, nrow = 20, ncol = 3)
for(i in 1:20){
     mat[i, ] = sample.int(6, 3, replace = TRUE)
}
print(mat)

I personally would simply do
matrix(sample.int(6, 20 * 3, replace = TRUE), nrow = 20)

(since all draws are independent and with replacement, it doesn't matter if you make 3 draws 20 times or simply 60 draws)

A: You can use list:
Twenty=list()
for(i in 1:20){
  Twenty[[i]] = sample.int(6, 3, replace = TRUE)
}


text:
Q: Why does the Laplace transform shift theorem not work with a positive shift? I am trying to compute the integral
$$ I = \int\limits_1^\infty e^{-t x} \sqrt{t} J_1\!\left(2 \sqrt{t}\right) \mathrm{d} t $$
which I encountered in my research. Now, I noticed that it has the same form as the Laplace transform, if only that lower integration limit were 0 instead of 1. I thought I could apply the shift theorem:
$$ f\!\left(t\right) = \sqrt{t} J_1\!\left(2 \sqrt{t}\right) $$
$$ I = \int\limits_1^\infty e^{-t x} f\!\left(t\right) \Theta\!\left(t\right) \mathrm{d} t = e^{-x} \int\limits_0^\infty e^{-t x} f\!\left(t + 1\right) \Theta\!\left(t + 1\right) \mathrm{d} t $$
My logic is that, in the first integral, since $t > 0$ always, it doesn't matter if we insert the Heaviside theta function; the second step is just a linear change of variables.
As far as I can tell, this is the right form for the Laplace transform of a shifted function except that the shift $a$ is supposed to satisfy $a > 0$ where $f\!\left(t - a\right)$ is the shifted function. Numerically, if I choose a value for $x$, I can do this integral, and the formula above holds:
(* the target function *)
f[t_] := Sqrt[t] BesselJ[1, 2 Sqrt[t]]

(* the original integral *)
With[{x = 1},
 NIntegrate[Exp[-t x] f[t], {t, 1, Infinity}, AccuracyGoal -> 5]]

(* the shifted integral *)
With[{x = 1},
 Exp[-x] NIntegrate[
   Exp[-t x] f[t + 1] HeavisideTheta[t + 1], {t, 0, Infinity},
   AccuracyGoal -> 5]]

>> 0.175032
>> 0.175032

However, the Laplace transform of $f\!\left(t\right)$ is given by
$$ F\!\left(x\right) = \frac{e^{-1/x}}{x^2} $$
and the Wikipedia table says that
$$ \mathcal{L}\!\left[f\!\left(t - a\right) \Theta\!\left(t - a\right)\right] = e^{-a x} F\!\left(x\right) $$
The factors of $e^{-x}$ and $e^x$ cancel, and I'm left with
With[{x = 1}, Exp[-1/x] / x^2 // N]

>> 0.135335

I get a different answer. I suspect this all has something to do with my shift being positive, but I don't understand conceptually why that should be a problem, since I never assumed $a > 0$ explicitly. I appreciate any help solving this problem.

A: The Laplace transform of $t \mapsto u(t-c) f(t)$ for $c>0$ has no simple relationship with that of $f$, intuitively because some of the information about $f$ on $[0,\infty)$ has been destroyed. The shift theorem applies to $u(t-c) f(t-c)$.

A: Just for the integral of your interest.
$$I = \int\limits_1^\infty e^{-t x} \sqrt{t}\, J_1\!\left(2 \sqrt{t}\right) \,dt=\int\limits_0^\infty e^{-t x} \sqrt{t}\, J_1\!\left(2 \sqrt{t}\right) \,dt-\int\limits_0^1 e^{-t x} \sqrt{t}\, J_1\!\left(2 \sqrt{t}\right) \,dt$$
As you wrote, assuming $x >0$,
$$\int\limits_0^\infty e^{-t x} \sqrt{t}\, J_1\!\left(2 \sqrt{t}\right) \,dt=\frac{e^{-1/x}}{x^2}$$ Now, for the second integral, use
$$\sqrt{t}\, J_1\!\left(2 \sqrt{t}\right)=\sum_{n=1}^\infty (-1)^{n+1}\frac {t^n}{n! \,(n-1)! }$$ which makes
$$\int\limits_0^1 e^{-t x} \sqrt{t}\, J_1\!\left(2 \sqrt{t}\right) \,dt=\sum_{n=1}^\infty (-1)^n \frac{\Gamma (n+1,x)-\Gamma (n+1,0)}{n!\,(n-1)! }\, x^{-(n+1)}$$  For $x=1$, the partial sums (from $n=1$ to $n=p$) converge extremely fast
$$\left(
\begin{array}{cc}
 p & \sum_{n=1}^p \\
 1 & 0.2642411177 \\
 2 & 0.1839397206 \\
 3 & 0.1934337990 \\
 4 & 0.1928238246 \\
 5 & 0.1928485823 \\
 6 & 0.1928478886 \\
 7 & 0.1928479028 \\
 8 & 0.1928479026
\end{array}
\right)$$


text:
Q: Canny transform VS threshed image for HoughCircle I'm try to build a robust coin detection on images using HoughCircle with these params :
blured_roi = cv2.GaussianBlur(region_of_interest, (23, 23), cv2.BORDER_DEFAULT)
rows = blured_roi.shape[0]
circles = cv2.HoughCircles(blured_roi, cv2.HOUGH_GRADIENT, 0.9, rows/8,
param1=30, param2=50, minRadius=30, maxRadius=90)

The region of interest could be (300x300) or (1080x1920). So the minRadius and maxRadius aren't really helping here. But they are approximately the size of my coin in each type of image shape.
So to achieve that I tried many things. First of all, using simple GRAY image with a GaussianBlur filter.
It works on most of cases but if my coin border are similar tint as the background, the GRAY scale image will not really help to detect the right radius of my circle take a look at this example :

In second time, I tried to use edges of the coin to detect circles with Canny Transform, but as you can see above the Canny filter not works as I hoped. So I applied a GaussianBlur of (13, 13).
I also know that there is another canny transform call inside the HoughCircle method, but I wanted to be sure I'll get edges of the coin, because I'm losing them while blurring with GaussianBlur.
Finally I tried using a threshed image, but I can't understand why it didn't works as well as excepted, because on this image we can hope there will never have any noises because it's only black&white (?), and the circle is almost perfect. And applied a GaussianBlur of (9, 9).

Here you can see it failed to detect the coin on the threshed image, but it works with the canny edges image. But in many other cases Hough Transform on edges detection give an unperfected result, and I feel confiant about threshed image which as you can see reveal a nice circle.
I would like to understand why it didn't works on the threshed image (like the example above), and what I could do to make it works.
EDIT 1: So I discovered the different type of BORDER to specify in the GaussianBlur method. I thought it would be really useful to improve the hough circle detection on the Threshed image, but it didn't goes as well as excepted.


text:
Q: gcc can compile a variadic template while clang cannot I'm reading some slides named An Overview of C++11 and C++14 presented by Mr. Leor Zolman. At Page 35 he introduces a way to do the sum operation with decltype.
struct Sum {
  template <typename T>
  static T sum(T n) {
    return n;
  }
  template <typename T, typename... Args>
  /// static T sum(T n, Args... rest) {
  static auto sum(T n, Args... rest) -> decltype(n + sum(rest...)) {
    return n + sum(rest...);
  }
};

When using this snippets forSum::sum(1, 2.3, 4, 5); clang-3.6(from svn) fails to compile this with -std=c++11/-std=c++1y but gcc-4.9 succeeds. Of course without type deduction for the return type both compile, but that involves type conversion and cannot get the expected result.
So does this indicate a clang bug, or is because of a gcc extension(in respect of c++11 or c++14)?

A: Clang's behavior is correct. This is a GCC bug (and the claim in the presentation is also incorrect). §3.3.2 [basic.scope.pdecl]/p1,6:

1 The point of declaration for a name is immediately after its
  complete declarator (Clause 8) and before its initializer (if any),
  except as noted below.
6 After the point of declaration of a class member, the member name can
  be looked up in the scope of its class.

And §3.3.7 [basic.scope.class]/p1 says

The following rules describe the scope of names declared in classes.
1) The potential scope of a name declared in a class consists not only
  of the declarative region following the name's point of declaration,
  but also of all function bodies, default arguments,
  exception-specifications, and brace-or-equal-initializers of
  non-static data members in that class (including such things in nested
  classes).

trailing-return-types are not in that list.
The trailing return type is part of the declarator (§8 [dcl.decl]/p4):
declarator:
    ptr-declarator
    noptr-declarator parameters-and-qualifiers trailing-return-type

and so the variadic version of sum isn't in scope within its own trailing-return-type and cannot be found by name lookup.
In C++14, simply use actual return type deduction (and omit the trailing return type). In C++11, you may use a class template instead and a function template that simply forwards:
template<class T, class... Args>
struct Sum {
    static auto sum(T n, Args... rest) -> decltype(n + Sum<Args...>::sum(rest...)) {
        return n + Sum<Args...>::sum(rest...);
    }
};

template<class T>
struct Sum<T>{
    static T sum(T n) { return n; }
};

template<class T, class... Args>
auto sum(T n, Args... rest) -> decltype(Sum<T, Args...>::sum(n, rest...)){
    return Sum<T, Args...>::sum(n, rest...);
}


text:
Q: Solving inequalities and drawing graph I have the question " Find the set of values of X for which X^2 - 6X + 5 > 0"
I have solved this and got X = 1 or 5.
My question is when drawing the graph is 5 the y-intercept ?so does the curve cut through the y-axis at the point 5 or is 5 not the y intercept and if so where does should the curve cut the y - axis or does it not cut through the y - axis at all ?

But the solutions say the answer should be :

A: it is equivalent to $$(x-1)(x-5)>0$$ thus we get $$x<1$$ or $$x>5$$

A: Look at the graph.It helps you understand the answer very easily.
When you plot $x^2-6x+5$ on the graph what you really mean is $y=x^2-6x+5$.Plugging in a particular value of $x$ gives you a corresponding value of $y$.
This type of thing is called a function.Its like an input output machine.
You need to find the set of all $x$ such that $x^2-6x+5>0$.So, this is equivalent to find all $x$ such that $y>0$.On the graph,the vertical axis is taken as $y-axis$ where the values of $y$ are shown for corresponding values of $x$.
Looking at the graph, we find between $1$ and $5$ the value of $y$ is below the origin,so $y$ is negative.And at $1$ and $5$,$y=0$.So,$y$ is clearly positive for all $x$ values which do not range from $1$ to $5$.
So,all real values of $x$ which do not range from $1$ to $5$ satisfies the equation.
Mathematically this can be written as $x<1$ and $x>5$.(Why? and How?)

A: I'm not too sure how the $y$-intercept helps with answering the question, but never the less, it is part of your problem.

Question 1: When drawing the graph, is $5$ the $y$-intercept? So does the curve cut through the $y$-axis at the point $5$, or is $5$ not the $y$-intercept?

Yes, the parabola intercepts the $y$-axis. An easy way to find it is to set $x=0$, and see what's left.
(Note: You can just instead, look at the $c$ term in $ax^2+bx+c$. See if you can show it!)

Question 2: Find the set of $x$ values such at $x^2-6x+5>0$

Graphing the polynomial, you will see that the values for which $y>0$ is when we have $(-\infty, 1]\cup [5,+\infty)$


text:
Q: Choosing a member function based on a string I have a set of hardware handler classes, all derived from a base class, which have to respond to an incoming data packet. Part of this packet is an ASCII string, which determined which member function of the hardware handler is used to process the packet (for example "fan" would execute the ToggleFan() function.
class HardwareHandler {
    virtual void dispatchCommand(const String& cmd) = 0;
}

class FooblerHandler : public HardwareHandler {

    void toogleFan();

    void dispatchCommand(const String& cmd) {
        //is this a "good" way to do this?
        if (cmd == "fan")
            toggleFan();
    }
}

I am using JUCE as a framework, which means I have things like templated HashMaps and String.
However, I'm having trouble coming up with a tidy way of selecting the right handler function based on this string. The construct
if (str == "hello")
    FooCommand();
else if (str == "bar")
    BarCommand();

looks pretty ugly to me conceptually as there are a lot of relatively expensive string comparisons in there. However, the code is easy to write and the logic is kept in a single place per class.
Another alternative I have tried is to make a hash-map of the strings to an enum and use that a the switch statement:
switch (str.getHash())
{
case CmdFoo:
    FooCommnad();
    break;
....and so on
}

However this also requires me to set up a static hash-map, as well as maintain the switch to match.
Something else I tried is a hash-map form the string to the member function pointer itself, hoping to be able to jump directly from the string to the member function without having list them in a case statement, and also allows a very generic dispatch function, as it just needs to look up in the hash-map, it doesn't even need to know all the options - they can be contained solely in the hash-map, allowing me to maybe push the dispatch function into the base handler class and not repeat myself in each specific device handler. However, this method has stumped me as I can't quite work out how to do it correctly, or even if it is possible to do this with a static hash-map and member-functions.
Is there an idiomatic way to dispatch to member functions based on a string (or similar hard-to-compare type), preferably with as much logic able to be genericised and moved to the parent class as possible?

A: Here is my try. You can encapsulate the mapping mechanism into a class:
#include <iostream>
#include <string>
#include <functional>
#include <map>

class X;

template<class X>
class handler_factory;

template<>
class handler_factory<X>
{
private:
    using HandlerType = void (X::*)();
public:
    handler_factory();

    HandlerType get(const std::string& name) const
    {
        if (handlers.find(name) == handlers.end())
            return nullptr;
        else
            return (*handlers.find(name)).second;
    }
private:
    std::map<std::string, HandlerType> handlers;
};

class X
{
public:
    friend class handler_factory<X>;
private:
    void f();
    void h();
};

handler_factory<X>::handler_factory()
{
    handlers["f"] = &X::f;
    handlers["h"] = &X::h;
}

void X::f() { std::cout << "X::f();"; }
void X::h() { std::cout << "X::h();"; }

And your dispatch method can be implemented as:
void dispatch_method(const std::string& name)
{
    if (find_handler(name))
        (this->*find_handler(name))();
}

int main()
{
    X().dispatch_method("f");
}

Where find_handler is defined as a private helper method:
private:
    auto find_handler(const std::string& name)
        -> decltype(handler_factory<X>().get(name))
    {
        return handler_factory<X>().get(name);
    }

A: I think the most efficient way to deal with the problem is creating a std::map that would map your strings into appropriate functions. The method is fast (due to the logarithmic searching algorithm), easy and safe.
class FooblerHandler : public HardwareHandler {
   typedef void (HardwareHandler::*function)();
   map<string,function> commandMap;

   void dispatchCommand(const string& cmd) {
      if(commandMap.count(cmd))
         (this->*commandMap.find(cmd)->second)();
      else
         cout << "No command found with name \"" <<cmd<< "\"." << endl;
   }
};

And of course you should init the map inside the constructor (or somewhere before using it):
commandMap["fan"] = &FooblerHandler::toogleFan;
commandMap["someOtherCommand"] = &FooblerHandler::otherFunction;

Maps and included in the Standard Template Library (STL) which nearly all IDE's supply.
EDIT:
I didn't quite read the text at the end. Well - now you know the syntax :)


text:
Q: ruby why 0 || 1 is 0 AND operator return second value when the first is true, the first one  when it's false
1 && 2 ---> 2
0 && 1 ---> 0

why OR operation not return second value when the first one is false, but return the first one when it's true
0 || 1 ---> 0
1 || 0 ---> 1

A: Both OR and AND are short-circuit evaluated, as soon as they know the value of the expression they give it to you.
In Ruby both 0 and 1 are true, they are truthy values. So
0 || 1 is 0
because 0 is true.
Just nil || 1 or false || 1 would return 1.

A: Ruby only evaluates as much as it needs to in an expression like this and then stops, what you are seeing returned is just the last part of the expression that it evaluated.
So for your && case, it always has to run right to the end in case a later clause returns false and which would cause the AND to be false.
And actually your example is wrong:
irb> 0 && 1
=> 1

Which is expected since 0 is truthy in Ruby, not as false like in C.
For the OR case, it can stop as soon as it hits anything that is truthy and doesn't need to bother with the rest.
0 || false      # => 0
false || 0      # => 0
false || 0 || 2 # => 0

If you want to force an expression like this to a boolean this is how you often see it done:
!!(expression)
!!(0 || 1)        => true
!!(nil || false)  => false

A: || is a logical operator, not a bitwise operator.  Unlike other languages for e.g C, 0 is not a "falsey" value in ruby.
Because || is a short-circuit logical operator, you have the following equivalent statement:
defined value "0" || defined value "1"
Which ruby is correctly evaluating as truthy expression A || truthy expression B and returning truthy expression A i.e. 0.
See here: https://gist.github.com/jfarmer/2647362
for a good overview of "Truthy" and "Falsey" values in Python and Ruby.

A: There are two things going on in here:

*

*Unlike in other languages, in Ruby, 0 is truthy (which means it is evaluated a s true in a boolean context).

*The OR operator in Ruby (||) shortcuts and returns the left argument if it is truthy.

Put these two together, and you get that 0 || 1 returns 0


text:
Q: changing the URI pattern of Generate REST APIs form SAOP methods in WSO2 api manager 4.1.0 I'm using from WSO2 API Manager 4.1.0 and I need to change URI pattern of methods that Generated REST APIs form SAOP endpoint (There is no problem in rest services with rest Endpoint).
for example I have method with /mutliply URI pattern and I want to change /api/multiply after change API Definition and save and deploy I get the following error:
api-manager_1  | [2023-02-28 09:13:01,036] ERROR - GlobalThrowableMapper An unknown exception has been captured by the global exception mapper.
api-manager_1  | java.lang.ClassCastException: class [Ljava.lang.String; cannot be cast to class [B ([Ljava.lang.String; and [B are in module java.base of loader 'bootstrap')
api-manager_1  |        at org.wso2.carbon.apimgt.persistence.RegistryPersistenceImpl.getSoapToRestSequences(RegistryPersistenceImpl.java:3581) ~[org.wso2.carbon.apimgt.persistence_9.20.74.jar:?]
api-manager_1  |        at org.wso2.carbon.apimgt.persistence.RegistryPersistenceImpl.getPublisherAPI(RegistryPersistenceImpl.java:706) ~[org.wso2.carbon.apimgt.persistence_9.20.74.jar:?]
api-manager_1  |        at org.wso2.carbon.apimgt.impl.APIProviderImpl.getAPIbyUUID_aroundBody506(APIProviderImpl.java:8318) ~[org.wso2.carbon.apimgt.impl_9.20.74.jar:?]
api-manager_1  |        at org.wso2.carbon.apimgt.impl.APIProviderImpl.getAPIbyUUID(APIProviderImpl.java:8315) ~[org.wso2.carbon.apimgt.impl_9.20.74.jar:?]
api-manager_1  |        at org.wso2.carbon.apimgt.impl.UserAwareAPIProvider.getAPIbyUUID(UserAwareAPIProvider.java:1) ~[org.wso2.carbon.apimgt.impl_9.20.74.jar:?]
api-manager_1  |        at org.wso2.carbon.apimgt.rest.api.publisher.v1.impl.ApisApiServiceImpl.getAPIByID(ApisApiServiceImpl.java:3959) ~[?:?]
api-manager_1  |        at org.wso2.carbon.apimgt.rest.api.publisher.v1.impl.ApisApiServiceImpl.createAPIRevision(ApisApiServiceImpl.java:4164) ~[?:?]
api-manager_1  |        at org.wso2.carbon.apimgt.rest.api.publisher.v1.ApisApi.createAPIRevision(ApisApi.java:339) ~[?:?]
api-manager_1  |        at jdk.internal.reflect.GeneratedMethodAccessor654.invoke(Unknown Source) ~[?:?]
api-manager_1  |        at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
api-manager_1  |        at java.lang.reflect.Method.invoke(Method.java:566) ~[?:?]
api-manager_1  |        at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:179) ~[?:?]
api-manager_1  |        at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96) ~[?:?]
api-manager_1  |        at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:201) ~[?:?]
api-manager_1  |        at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:104) ~[?:?]
api-manager_1  |        at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59) ~[?:?]
api-manager_1  |        at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96) ~[?:?]
api-manager_1  |        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:265) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:225) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:304) ~[?:?]
api-manager_1  |        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:217) ~[?:?]
api-manager_1  |        at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-servlet-api_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:279) ~[?:?]
api-manager_1  |        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.wso2.carbon.identity.context.rewrite.valve.TenantContextRewriteValve.invoke(TenantContextRewriteValve.java:107) ~[org.wso2.carbon.identity.context.rewrite.valve_1.4.52.jar:?]
api-manager_1  |        at org.wso2.carbon.identity.authz.valve.AuthorizationValve.invoke(AuthorizationValve.java:110) ~[org.wso2.carbon.identity.authz.valve_1.4.52.jar:?]
api-manager_1  |        at org.wso2.carbon.identity.auth.valve.AuthenticationValve.invoke(AuthenticationValve.java:102) ~[org.wso2.carbon.identity.auth.valve_1.4.52.jar:?]
api-manager_1  |        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:101) ~[org.wso2.carbon.tomcat.ext_4.6.3.jar:?]
api-manager_1  |        at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:49) ~[org.wso2.carbon.tomcat.ext_4.6.3.jar:?]
api-manager_1  |        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62) ~[org.wso2.carbon.tomcat.ext_4.6.3.jar:?]
api-manager_1  |        at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:146) ~[org.wso2.carbon.tomcat.ext_4.6.3.jar:?]
api-manager_1  |        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:58) ~[org.wso2.carbon.tomcat.ext_4.6.3.jar:?]
api-manager_1  |        at org.wso2.carbon.tomcat.ext.valves.RequestCorrelationIdValve.invoke(RequestCorrelationIdValve.java:126) ~[org.wso2.carbon.tomcat.ext_4.6.3.jar:?]
api-manager_1  |        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat_9.0.58.wso2v1.jar:?]
api-manager_1  |        at java.lang.Thread.run(Thread.java:829) [?:?]

Even after getting the error I'm not able to open the api!
Thank you for helping me

A: It's not a straight forward task to change a resource of a SOAP to REST API. Since resources are generated according to the operations present in the WSDL and there is an internal mapping that uses the paths, and parameters of the REST API to generate the backend SOAP envelop, you can't simply update the resource name from the API definition.
If you proceed to the resources section, you can see that there is a synapse sequence created with each resource. This is the mapping logic that generates the SOAP envelop according to the request parameters. Since this API is governed by the WSDL, I don't think you can change the resource name.
You have to either proxy this API with another REST API and change the resource and map, or you have to use specialized tools such as micro integrator and integration studio for such usecases.


text:
Q: Should packages on CTAN be widely applicable? I have a couple 'packages' (more appropriately called styles) that I'd like to painlessly distribute to my classmates.  The most straightforward way to do this is via CTAN, but I'm not sure if it is appropriate to upload the style since it is only applicable to a very small group of people, and possibly only for a few years.
Has this sort of thing been done before?
If I put these styles on CTAN, would angry TeXers show up at my door
  bearing pitchforks full of burning hay, chanting curses upon my family and descendants,
  for cluttering their filesystem with useless-to-them styles?

A: I've been encouraged by the Great Old Ones of the TeX world to submit when I have something usable.  Your style file may seem to you like a tool of limited application; but it could wind up being exactly what somebody needed for some unforeseeable reason.  Furthermore, even if people don't use your package for its intended purpose, it's quite possible that they can skim it for ideas or for specific code.
When we submit to CTAN, in other words, we're enriching each other; as long as your package works and solves a real problem, I'd say submit it.


text:
Q: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted) I'm writing a site on Flask and I came across the problem that when sending emails to email users there is such an error.
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials i1-20020ac25221000000b00478f5d3de95sm4732790lfl.120 - gsmtp')

I searched Google for a solution to the problem, but it said that you need to disable a feature that has not been supported by GMAIL recently. Maybe someone knows how to solve this problem now?
Here is my config connection:
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD')

Help me please

A: Since You can't use the less secure app now as the deadline was 30th May 2022.
An alternative way to send Gmail via flask using an App password
Before generating the APP password your google account must enable the 2FA.
If the 2FA is enabled then you can hop on to the security section in the manage accounts and there you can see the APP password section.
For generating the APP password you also can read -> here
The below code I tried and it's working
I have used python another dependencies
pip install Flask-Mail

from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)
mail= Mail(app)

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'someone@gmail.com'
app.config['MAIL_PASSWORD'] = 'YOUR_APP_PASSWORD'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)

@app.route("/")
def index():
   msg = Message('Hello', sender = 'someone@gmail.com', recipients = ['someone@gmail.com'])
   msg.body = "Hello Flask message sent from Flask-Mail"
   mail.send(msg)
   return "Sent"

if __name__ == '__main__':
   app.run(debug = True)


text:
Q: Number of processes spawned by a Django [+Celery] application I have developed a Django application and now I want to host it somewhere. I found an interesting offer that is based on processes. The two offers I am considering are as follows:

*

*
6 processes with 64MB of address space
  6 processes with 48MB of
  address space (suggested for cron and ssh)

*
9 processes with 64MB of address space
  6 processes with 48MB of
  address space (suggested for cron and ssh)

Considering that my application runs as follows:

*

*supervisord is run first to manage other processes. It starts:

*

*nginx

*uWSGI

*redis (needed by RQ)

*rqworker (from django-rq, which is the bridge between Django and RQ)

And I use PostgreSQL as database. Do you think it can fit in the first offer? If I count processes correctly they're 6, but in the wiki I read:

PostgreSQL requires 8 64MB processes.

If that's true, I think I need to switch to the second offer, because my application would not fit in the first one anymore. In addition to that, I must have a process left to run ssh.
Alternatively, I can go for the Container approach, which means I can choose how much physical memory the container should have and run all my processes inside it.
What approach do you think it's better for my application?
Thank you,
rubik


text:
Q: Recursive call causing IndexError in Class function The goal of my program is to have the computer ask a user questions, and return some specifications for a computer that would fit their needs. Right now I am working on QuestionAsker, which is responsible for, as the class name suggests, asking the user questions. I've been hung up on the 4th line of AskQuestion() function. Before I tell you the problem, take a look at the code:
from question import Question

class QuestionAsker():
    questions = [
        Question("At minimum, what should your game be running on?", ["Low", "Medium", "Ultra"]),
        Question("On a scale of 1-3, how much flair do you want on your computer?", ["Low", "Medium", "Ultra"]),
        Question("Money doesn't grow on trees. How much money is in your budget?", ["$500", "$1000", "$2000+"]),
        ]

    index = 0
    def AskQuestion(self):
        userInputForQuestion = raw_input(self.questions[self.index].question + " ")

        if userInputForQuestion not in self.questions[self.index].answers:
            print("Try again.")
            self.AskQuestion()

        self.questions[self.index].selectedAnswer = userInputForQuestion

        self.index += 1;

    def resetIndex(self):
        self.index = 0

    def ReadQuestions(self):
        pass

I was testing this code by calling AskQuestion a couple of times (to loop through all the questions), and to make sure this code was tippy top, I supplied multiple answers that returned "Try again," as it should. The issue is that if I supplied more than 1 wrong answer to a question, but then if I answered correctly after multiple wrong answers, I would get the following error message:
IndexError: list index out of range

I immediately suspected the [self.index] of the self.questions[self.index], so I began printing out the index to the console. I thought that the issue was that the AskQuestion was magically incrementing the self.index, on the final line of the AskQuestion function, but no. It kept printing a consistent number, in the case of the first question, 0!
I'm at my wits end here, and the other questions I've seen on this haven't served much help. Hopefully you guys can help, thanks!

A: Please take care that in your function body, when a wrong answer is given, the function does not end. It makes a recursive call. When that call ends, the index is still incremented. So the wrong answers still mess the index up.
You should end the function after the wrong call is made, for what you want to happen.
if userInputForQuestion not in self.questions[self.index].answers:
    print("Try again.")
    self.AskQuestion()
    return None

or use else.
if userInputForQuestion not in self.questions[self.index].answers:
    print("Try again.")
    self.AskQuestion()
else:
    self.questions[self.index].selectedAnswer = userInputForQuestion
    self.index += 1;

Also please note that using recursion in such a way is not very common. Which made you make the mistake anyway.


text:
Q: update query "You can't specify target table 'a' for update in FROM clause" I am trying to add new column and wants update its value based on some condition but it does not allow me to do that it says "You can't specify target table 'a' for update in FROM clause"
Any Idea, how to do that?
mysql
ALTER TABLE test ADD COLUMN step1_pincode VARCHAR(20);

UPDATE test a SET a.step1_pincode =
(
SELECT CASE WHEN b.RetailerPincode IS NOT NULL
       THEN RetailerPincode
       ELSE b.StorePartyPincode
END AS step1_pincode1
FROM test b
);

A: In MySQL, you cannot specify the same table in SET clause during UPDATE. Moreover, you don't really need a subquery in your case; you can simply use the conditional CASE .. WHEN expression directly. Try the following:
UPDATE test a
SET a.step1_pincode = CASE WHEN a.RetailerPincode IS NOT NULL
                           THEN a.RetailerPincode
                           ELSE a.StorePartyPincode
                      END

As @TimBiegeleisen rightly suggested in comments, you can actually write this query using COALESCE() function, in a concise manner:
UPDATE test
SET step1_pincode = COALESCE(RetailerPincode, StorePartyPincode)


text:
Q: pandas read parquet with struct (not array) A call to
pd.read_parquet('foo.parquet')

fails with:
ArrowInvalid: Chunked field reads not yet supported with StructArray

whereas
spark.read.parquet('foo.parquet').printSchema()
works just fine.
NOTE: it does not contain any arrays just a simple struct:
root
 |-- id: string (nullable = true)
 ...
 |-- foo: struct (nullable = true)
 |    |-- baz: string (nullable = true)
 |    |-- bar: double (nullable = true)
 |-- bar: struct (nullable = true)
 |    |-- baz: string (nullable = true)
 |    |-- bar: double (nullable = true)

Is there a way to still be able to read the struct in pandas without resorting to spark?
edit
This is related to https://jira.apache.org/jira/browse/ARROW-3058
However, I am already using the latest 0.12 release and still face this issue.


text:
Q: Как сделать отступ текста от  в котором он находится? если сделать margin: top; то текст будет отступаться с верху, относительно верха экрана а вопрос в том, что надо отступить от div

A: За  внутренние отступы в общем случае отвечает padding, например отступы сверху этоpadding-top: 1em
margin же это внешние отступы.
Так же есть line-height: 3em который по сути междустрочный интервал, но тоже даст отступы, еще и между строками.
На самый крайний случай можно поставить
 (перевод каретки) перед текстом внутри div, это сместит все содержимое вниз на 1 line-height
P.S. 1em и 3em я взял для примера, чтобы показать какой тип данных  принимают вышеуказанные параметры css.

A: margin - внешний отступ
padding - внутренний
Можно сделать так:

        Текст

Можно сделать так:

Текст


text:
Q: New to Vue.js need help as to why the bars wont update beyond the first command The bars won't update with the health score after the first attempt, though if you keep clicking attack eventually the game ends. I get this error on console but don't know what to do about it to fix the issue. Any help would be appreciated.
[Vue warn]: Invalid handler for event "click": got undefined
(found in <Root>)

new Vue({
    el:'#app',
    data:{

        playerHealth:100,
        monsterHealth:100,
        gameIsRunning:false

    },

    methods:
    {

            startGame: function(){

                this.gameIsRunning= true;
                this.playerHealth = 100;
                this.monsterHealth = 100;

            },

            attack: function(){

                this.monsterHealth -= this.calculateDamage(3,10)

                if(this.checkWin()){
                    return;
                }

                this.monsterAttacks();

            },

            specialAttack: function(){
                this.monsterHealth -= this.calculateDamage(10,20)

                if(this.checkWin()){
                    return;
                }

                this.monsterAttacks();

            },

            heal: function(){

            },

            giveUP: function(){

            },

            calculateDamage: function(min,max){

                return Math.max(Math.floor(Math.random() * max) + 1,min);

            },

            checkWin: function(){

                if(this.monsterHealth <= 0){
                    if(confirm('You Won! new Game?')){
                        this.startGame();
                    }else{

                        this.gameIsRunning = false;

                    }
                    return true
                }else if(this.playerHealth <= 0){
                    if(confirm('You Lost! new Game?')){
                        this.startGame();
                    }else{

                        this.gameIsRunning = false;

                    }
                    return true;

                }
                   return false;
                },

            monsterAttacks: function(){
                this.playerHealth -= this.calculateDamage(5,12);
                this.checkWin();

            }

            }

});
.text-center {
    text-align: center;
}

.healthbar {
    width: 80%;
    height: 40px;
    background-color: #eee;
    margin: auto;
    transition: width 500ms;
}

.controls, .log {
    margin-top: 30px;
    text-align: center;
    padding: 10px;
    border: 1px solid #ccc;
    box-shadow: 0px 3px 6px #ccc;
}

.turn {
    margin-top: 20px;
    margin-bottom: 20px;
    font-weight: bold;
    font-size: 22px;
}

.log ul {
    list-style: none;
    font-weight: bold;
    text-transform: uppercase;
}

.log ul li {
    margin: 5px;
}

.log ul .player-turn {
    color: blue;
    background-color: #e4e8ff;
}

.log ul .monster-turn {
    color: red;
    background-color: #ffc0c1;
}

button {
    font-size: 20px;
    background-color: #eee;
    padding: 12px;
    box-shadow: 0 1px 1px black;
    margin: 10px;
}

#start-game {
    background-color: #aaffb0;
}

#start-game:hover {
    background-color: #76ff7e;
}

#attack {
    background-color: #ff7367;
}

#attack:hover {
    background-color: #ff3f43;
}

#special-attack {
    background-color: #ffaf4f;
}

#special-attack:hover {
    background-color: #ff9a2b;
}

#heal {
    background-color: #aaffb0;
}

#heal:hover {
    background-color: #76ff7e;
}

#give-up {
    background-color: #ffffff;
}

#give-up:hover {
    background-color: #c7c7c7;
}
<!DOCTYPE html>

    <title>Monster Slayer</title>

    <link rel="stylesheet" href="foundation.min.css">
    <link rel="stylesheet" href="app.css">

YOU

                    {{ playerHealth }}

MONSTER

                    {{ monsterHealth }}

            <button id="start-game" @click="startGame">START NEW GAME</button>

            <button id="attack" v-on:click="attack">ATTACK</button>
            <button id="special-attack" @click="specialAttack">SPECIAL ATTACK</button>
            <button id="heal" @click="heal">HEAL</button>
            <button id="give-up" @click="giveUp">GIVE UP</button>

A: The method bound to the click handler is giveUp(), while in your methods, it is spelled giveUP(). The discrepancy is likely throwing the warning.


text:
Q: Github pages not rendering css correctly for Jekyll theme This is the link to github for the theme which I'm working on: https://github.com/PrashantYadav/xosjapps
On the localhost, its working properly.
I have set the baseurl but still its rendering css correctly as you can see it here - https://prashantyadav.github.io/xosjapps/
This is the url for original theme: https://github.com/jeromelachaud/freelancer-theme
Please help.

A: The console said that it's failed to load ressources. Are you sure you put the correct path to the files ?

A: CSS files aren't being loaded properly.
Move your css files that are located in /_includes/css to /css and load them from your layout file (or include) as:
 <link rel="stylesheet" href="{{ '/css/main.css' | absolute_url }}" type="text/css" />
 <link rel="stylesheet" href="{{ '/css/bootstrap.min.css' | absolute_url }}" type="text/css" />


text:
Q: I can't pass some value from html checkbox array to my php page? I created the product management system that use HTML+PHP+SQL+JS.But it's have a problem
some value can't pass to php page to SQL query.I can't find any bug in my code because some data can do that normally.
my system use the checkbox array to choose each product that i want to do with them
echo "<input type=\"checkbox\" name=\"ProductKey[]\" value=\"".$Key."\"/>	";

and pass them to any target by javascript like this
<input type='button' id='edit' onclick="OnButtonEdit();" class = "btn btn-success" value='add'>

<input type='button' id='delete' onclick="OnButtonDelete();" class = "btn btn-warning" value='subtract'>

<input type='button' id='delete' onclick="OnButtonRemove();" class = "btn btn-danger" value='remove'>

<input type='button' id='delete' onclick="OnButtonProductbackquery();" class = "btn btn-info" value='pass back to homestock'>

in php page that receive value to sql query
foreach ($_POST['ProductKey'] as $Key){
....
}

The Example data that can pass
ProductKey | Size | Colour | Price | Cost | Quantity | Customer | ProductKey | AccountKey
DK9973 | 42 | Black | 550 | 280 |1 | ram35 | 57872 | 128

Example data that can't pass
ProductKey | Size | Colour | Price | Cost | Quantity | Customer | ProductKey | AccountKey
A056 | 40 | Brown | 350 | 220 |1 | ram35 | 58784 | 133

some javascript button function
 function OnButtonDelete() {
    document.myform.action = "delete.php";
    document.myform.target = "_self";
    document.myform.submit();
    return true;
  }

Thanks for all answer ,If you want more code please tell me :)

A: If your checkbox is not checked, it will not exist in the php page who receive the post data.
Just test :
if(isset($_POST['ProductKey'])){
  //Checkbox checked
} else {
  //Checkbox not checked
}

A: Now, I solved it!!
it should be the html checkbox maximum in one form.
I tried to make the search input that query from ProductID
it make the number of checkbox in one form decrease
but,now it work for all product.
I don't sure about this solution,but it's work.


text:
Q: How do I determine an appropriate sample size for my experiment? I want to do an experiment at my company's recruiting events to see if giving attendees some of our products has a measurable impact on how many people actually apply for positions and/or get hired.
I'm a statistics novice. How do I figure out what kind of sample size I would need? Also, if my company has historical data about our recruiting events' "success" rate, can I use that in place of a control group?


text:
Q: Is there a way to do a conditional regression? screenshot from the paper "Momentum Crashes" by Daniel and Moskowitz
so a stands for alpha, ß for beta.
I is a dummy variable
The model im trying to replicate is written like this, and in the solution table there are values for alpha zero and alpha (i). So is it possible to do a regression with two alphas and two betas if my dummy variable is one ? or is it just two separate regressions using subset?
The Authors call it a conditional CAPM.
reg<-      lm(Momentum.monthly$WMLRF[25:1044]~Fama.French.monthly$Mkt[25:1044],sub      set = Fama.French.monthly$bear.indicator == 0)

This was my try, but the values don't fit with the solution.


text:
Q: What is the best way to do basic numbers recognition? I would like to detect basic English Numbers from 0 to 9 using simple OCR on Android.
I've looked for OCR for Android, but it is too complex for my main purpose, is there any simpler way to just detect numbers on Android?

A: A simple alternative is to predefine the digits as bitmaps, and to find them using normalized cross-correlation.
There are a lot of disadvantages in this method:

*

*No robustness to different fonts

*No robustness to scale of numbers

*...

But maybe that is what you need just to get started with.

A: If you want to perform OCR from the phone-based camera, it'l be hard to use predefined bitmaps: photos will be taken with different scale, they will contain noise, they'll be scewed etc, so that would hardly be accurate enough.
If you're developing an Android APP, you are most likely usign Java. The bad news in that there are no native opensource Java OCR SDKs. There are Java APIs which wrap calls for native interfaces, for example, for one of the most popular opensource OCR engines -
Tesseract (http://groups.google.com/group/tesseract-ocr/) - there are some Java wrappers like tesjeract (http://code.google.com/p/tesjeract/) or Tess4J (http://tess4j.sf.net/). That could work for you, but it's rather hard to set up and will require developing image-preprocessing and font training on your side.
One more solution could be a cloud service. It requires end-user application to have the internet connection, but it's independent from your programming language choice and resources limitations. Have a look at ABBYY Cloud OCR SDK, it's a cloud-based OCR SDK recently launched by ABBYY. It's in beta, so for now it's totally free to use and it has a ready-to-go Android code samples. It has image pre-processing built-in, requires no training and simply works out of the box - you just send and image and receive ocr-ed data. Plus it has field-level recognition functionality which could save you a valuable piece of small device processing resources. I work @ ABBYY and can provide you additional info on our products if necessary.


text:
Q: Is it possible to create an alert with more than 2 buttons in SwiftUI? I need to create an alert with 3 buttons, but it looks like SwiftUI only gives us two options right now: one button or two buttons. I know that with UIKit, 3 buttons are achievable, but I can't seem to find a workaround in the latest version of SwiftUI to do this. Below is my code where I'm using only a primary and secondary button.
Button(action: {
    self.showAlert = true
}){
    Text("press me")
}
.alert(isPresented: self.$showAlert){
     Alert(title: Text("select option"), message: Text("pls help"), primaryButton: Alert.Button.default(Text("yes"), action: {
         print("yes clicked")
         }), secondaryButton: Alert.Button.cancel(Text("no"), action: {
         print("no clicked")
     })
     )
}

A: .actionSheet, .sheet, and .popover are options to provide custom alerts. Consider this sample:
import SwiftUI

struct ContentView: View {
    @State private var showModal = false
    @State private var cnt = 0
    var body: some View {

        VStack {
            Text("Counter is \(cnt)")
            Button("Show alert") {
                self.showModal = true
            }
        }
        .sheet(isPresented: $showModal,
               onDismiss: {
                print(self.showModal)}) {
                    CustomAlert(message: "This is Modal view",
                              titlesAndActions: [("OK", {}),
                                                 ("Increase", { self.cnt += 1 }),
                                                 ("Cancel", nil)])
        }
    }
}

struct CustomAlert: View {
    @Environment(\.presentationMode) var presentation
    let message: String
    let titlesAndActions: [(title: String, action: (() -> Void)?)] // = [.default(Text("OK"))]

    var body: some View {
        VStack {
            Text(message)
            Divider().padding([.leading, .trailing], 40)
            HStack {
                ForEach(titlesAndActions.indices, id: \.self) { i in
                    Button(self.titlesAndActions[i].title) {
                        (self.titlesAndActions[i].action ?? {})()
                        self.presentation.wrappedValue.dismiss()
                    }
                    .padding()
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: If you want to be compatible with previous versions of iOS 15, consider to use actionSheet like this:
.actionSheet(isPresented: $showActionSheet) {
    ActionSheet(title: Text("Title"), message: Text("Choose one of this three:"), buttons: [
        .default(Text("First")) { },
        .default(Text("Second")) { },
        .default(Text("Third")) { },
        .cancel()
    ])
}

A: This is now possible on iOS 15/macOS 12 with a new version of the alert modifier: alert(_:isPresented:presenting:actions:).
It works a bit differently because the Alert struct isn't used anymore; you use regular SwiftUI Buttons instead. Add a ButtonRole to indicate which buttons perform the "cancel" action or "destructive" actions. Add the .keyboardShortcut(.defaultAction) modifier to a button to indicate it performs the principal action.
For example:
MyView()
    .alert("Test", isPresented: $presentingAlert) {
        Button("one", action: {})
        Button("two", action: {}).keyboardShortcut(.defaultAction)
        Button("three", role: .destructive, action: {})
        Button("four", role: .cancel, action: {})
    }

Creates the following alert:

A: example below requires iOS 14.0 and available for both iPad and iPhone.
i also beleive this code will require minimum modifications to support iOS 13.0 as well.
(xcode project with usage example is available here)
import SwiftUI

public extension View {

    func alert(if condition: Binding<Bool>,
               title: String = "",
               text: String = "",
               buttons: [Alert.Option] = [.cancel("OK")]) -> some View {
        let alert: AlertView = .init(condition, title, text, buttons)
        return overlay(condition.wrappedValue ? alert : nil)
    }

}

private struct AlertView : View {

    @Binding var active: Bool
    private let title: String
    private let text: String
    private let buttons: [Alert.Option]
    private let cancel: Alert.Option?

    init(_ active: Binding<Bool>, _ title: String, _ text: String, _ buttons: [Alert.Option]) {
        self._active = active
        self.title = title
        self.text = text
        self.buttons = buttons.filter { $0.role != .cancel }
        self.cancel = buttons.first { $0.role == .cancel } ?? (buttons.isEmpty ? .cancel("OK") : nil)
    }

    var body: some View {
        VStack() {
            if title.count > 0 { Text(title).fontWeight(.semibold).padding([.top, .bottom], 5) }
            if text.count > 0 { Text(text).fixedSize(horizontal: false, vertical: true) }
            ForEach(buttons, id: \.label) { Divider(); button(for: $0) }
            if let cancel { Divider(); button(for: cancel) }
        }.padding()
         .frame(maxWidth: width)
         .background(Color(.secondarySystemBackground))
         .cornerRadius(20)
         .shadow(color: Color(.black), radius: 5)
         .screenCover()
         .onTapGesture { if cancellable { active = false } }
    }

    private func button(for option: Alert.Option) -> some View {
        HStack {
            Spacer()
            Text(option.label)
                .foregroundColor(option.role == .destructive ? Color(.red) : Color(.link))
                .fontWeight(option.role == .cancel ? .semibold : .regular)
                .padding([.top, .bottom], 5)
            Spacer()
        }.background(Color(.secondarySystemBackground))
         .onTapGesture { if option.role != .cancel { option.action() }; active = false }
    }

    private var width: CGFloat { min((UIScreen.main.bounds.width * 0.8), 500) }

    private var cancellable: Bool { cancel != nil }

}

extension Alert {

    public final class Option {

        public let label: String
        public let role: Role
        public let action: () -> Void

        public init(_ label: String, role: Role = .regular, action: @escaping () -> Void = { }) {
            self.label = label
            self.role = role
            self.action = action
        }

        public static func cancel(_ label: String) -> Option { .init(label, role: .cancel) }

    }

}

public extension SwiftUI.Alert.Option { enum Role { case regular; case cancel; case destructive } }

public extension View {

    func screenCover(_ color: Color = .init(UIColor.systemBackground), opacity: Double = 0.5) -> some View {
        color.opacity(opacity)
             .ignoresSafeArea()
             .overlay(self)
    }

}


text:
Q: AS3 What causes lag with side scrollers? I've been programming a side scroller based on a tutorial found in a book. My friend did the same, and his is working perfectly.
I've only really changed a few variable names around (I've also done animations differently) but for some reason, when my character is moving, there is a large amount of lag.
HOwever the lag is only present when there are 'walls' on the stage. When I scroll past them, the lag goes away, then returns.
Walls and Floors both use the same code (they are both assigned as 'floorObjects' variables) and use the same collision code, however I cannot figure out why there is lag involved.
From where the character starts (about 60x) if the character goes left, there is a HUGE amount of lag. If I go right, there isn't too much lag, until the screen starts to scroll.
The lag from going left I believe may have something to do with the program being preventing from scrolling off the map etc. But I can't figure out why there is lag when trying to move right.
I've listed the Scroll code, and the main loop, if need be I can upload the collisions code, and any help would be greatly appreciated.
Scroll code;
public function scrollGame()
        {

            var stagePosition:Number = gameLevel.x + player.mc.x;
            var rightEdge:Number = stage.stageWidth - edgeDistance;
            var leftEdge:Number = edgeDistance;
            //Scroll the GameLevel to the Left if player moves right
            if(stagePosition > rightEdge)
            {
                gameLevel.x -= (stagePosition - rightEdge);
                //Prevent the game scrolling off the stage
                if (gameLevel.x < -(gameLevel.width-stage.stageWidth))
                    gameLevel.x = -(gameLevel.width-stage.stageWidth);
            }
            //Scroll the GameLevel to the right if player moves left
            if(stagePosition < leftEdge)
            {
                gameLevel.x += (leftEdge - stagePosition);
                //Prevent the game scrolling off the stage
                if(gameLevel.x > 0)
                    gameLevel.x = 0;
            }

        }

Main Loop:
public function gameLoop(e:Event)
        {
            //Get Time Difference
            if(lastTime == 0) lastTime = getTimer();
            var timeDiff:int = getTimer() - lastTime;
            lastTime += timeDiff;

            //Game Cycle tasks
            //Only perform if in play mode
            if(gameMode == "play")
            {
                moveCharacter(player, timeDiff);
                moveEnemies(timeDiff);
                checkCollisions();
                scrollGame();

            }
        }

UPDATE:
So I "profiled" it, most of the time is being spent either in the MoveCharacter() function, using the gotoAndStop() command. So I removed that, and it made no difference, still lagging. I then removed the enemies also, still lagging. But turning quality down to low has somehow fixed it (though at a poor quality now ) Any ideas as to what is causing the lag and how to fix it?

A: this is from the flash university book isn't it?
The code is fine.
I know what will lag your flash game.
This is a guess though, and I do get this error some times.
Make sure your images are optimized!
If they're imported from photo shop or illustratro then flash will have to deal with those complicate vector points.
Use .png for transparent images, bitmaps don't hurt either.


text:
Q: Javascript: Split a string by comma, except inside parentheses Given string in the form:
'"abc",ab(),c(d(),e()),f(g(),zyx),h(123)'

How can I split it to get the below array format:
abc
ab()
c(d(),e())
f(g(),zyx)
h(123)

I have tried normal javascript split, however it doesn't work as desired. Trying Regular Expression but not yet successful.

A: You can keep track of the parentheses, and add those expressions when the left and right parens equalize.
For example-
function splitNoParen(s){
    var left= 0, right= 0, A= [],
    M= s.match(/([^()]+)|([()])/g), L= M.length, next, str= '';
    for(var i= 0; i<L; i++){
        next= M[i];
        if(next=== '(')++left;
        else if(next=== ')')++right;
        if(left!== 0){
            str+= next;
            if(left=== right){
                A[A.length-1]+=str;
                left= right= 0;
                str= '';
            }
        }
        else A=A.concat(next.match(/([^,]+)/g));
    }
    return A;
}

var s1= '"abc",ab(),c(d(),e()),f(g(),zyx),h(123)';
splitNoParen(s1).join('\n');

/*  returned value: (String)
"abc"
ab()
c(d(),e())
f(g(),zyx)
h(123)
*/

A: This might be not the best or more refined solution, and also maybe won't fit every single possibility, but based on your example it works:
var data = '"abc",ab(),c(d(),e()),f(g(),zyx),h(123)';
// Create a preResult splitting the commas.
var preResult = data.replace(/"/g, '').split(',');
// Create an empty result.
var result = [];

for (var i = 0; i < preResult.length; i++) {
    // Check on every preResult if the number of parentheses match.
    // Opening ones...
    var opening = preResult[i].match(/\(/g) || 0;
    // Closing ones...
    var closing = preResult[i].match(/\)/g) || 0;

    if (opening != 0 &&
        closing != 0 &&
        opening.length != closing.length) {
        // If the current item contains a different number of opening
        // and closing parentheses, merge it with the next adding a
        // comma in between.
        result.push(preResult[i] + ',' + preResult[i + 1]);
        i++;
    } else {
        // Leave it as it is.
        result.push(preResult[i]);
    }
}

Demo

A: For future reference, here's another approach to top-level splitting, using string.replace as a control flow operator:
function psplit(s) {
  var depth = 0, seg = 0, rv = [];
  s.replace(/[^(),]*([)]*)([(]*)(,)?/g,
            function (m, cls, opn, com, off, s) {
    depth += opn.length - cls.length;
    var newseg = off + m.length;
    if (!depth && com) {
      rv.push(s.substring(seg, newseg - 1));
      seg = newseg;
    }
    return m;
  });
  rv.push(s.substring(seg));
  return rv;
}

console.log(psplit('abc,ab(),c(d(),e()),f(g(),zyx),h(123)'))

["abc", "ab()", "c(d(),e())", "f(g(),zyx)", "h(123)"]

Getting it to handle quotes as well would not be too complicated, but at some point you need to decide to use a real parser such as jison, and I suspect that would be the point. In any event, there's not enough detail in the question to know what the desired handling of double quotes is.

A: You can't use .split for this, but instead you'll have to write a small parser like this:

function splitNoParen(s){
  let results = [];
  let next;
  let str = '';
  let left = 0, right = 0;

  function keepResult() {
    results.push(str);
    str = '';
  }

  for(var i = 0; i<s.length; i++) {
    switch(s[i]) {
    case ',':
      if((left === right)) {
        keepResult();
        left = right = 0;
      } else {
        str += s[i];
      }
      break;
    case '(':
      left++;
      str += s[i];
      break;
    case ')':
      right++;
      str += s[i];
      break;
    default:
      str += s[i];
    }
  }
  keepResult();
  return results;
}

var s1= '"abc",ab(),c(d(),e()),f(g(),zyx),h(123)';
console.log(splitNoParen(s1).join('\n'));

var s2='cats,(my-foo)-bar,baz';
console.log(splitNoParen(s2).join('\n'));

A: Had a similar issue and existing solutions were hard to generalize. So here's another parser that's a bit more readable and easier to extend to your personal needs. It'll also work with curly braces, brackets, normal braces, and strings of any type.  License is MIT.
/**
 * This function takes an input string and splits it by the given token, but only if the token is not inside
 * braces of any kind, or a string.
 * @param {string} input The string to split.
 * @param {string} split_by Must be a single character.
 * @returns {string[]} An array of split parts without the split_by character.
 */
export function parse_split(input:string, split_by:string = ",") : string[]
{
    // Javascript has 3 types of strings
    const STRING_TYPES = ["'","`","\""] as const;

    // Some symbols can be nested, like braces, and must be counted
    const state = {"{":0,"[":0,"(":0};
    // Some cannot be nested, like a string, and just flip a flag.
    // Additionally, once the string flag has been flipped, it can only be unflipped
    // by the same token.
    let string_state : (typeof STRING_TYPES)[number] | undefined = undefined

    // Nestable symbols come in sets, usually in pairs.
    // These sets increase or decrease the state, depending on the symbol.
    const pairs : Record<string,[keyof typeof state,number]> = {
        "{":["{",1],
        "}":["{",-1],
        "[":["[",1],
        "]":["[",-1],
        "(":["(",1],
        ")":["(",-1]
    }

    let start = 0;
    let results = [];
    let length = input.length;
    for(let i = 0; i < length; ++i)
    {
        let char = input[i];

        // Backslash escapes the next character. We directly skip 2 characters by incrementing i one extra time.
        if(char === "\\")
        {
            i++;
            continue;
        }
        // If the symbol exists in the single/not nested state object, flip the corresponding state flag.
        if(char == string_state)
        {
            string_state = undefined;
            console.log("Closed string ", string_state);
        }
        // if it's not in a string, but it's a string opener, remember the string type in string_state.
        else if(string_state === undefined && STRING_TYPES.includes(char as typeof STRING_TYPES[number]))
        {
            string_state = char as typeof STRING_TYPES[number];
        }
        // If it's not in a string, and if it's a paired symbol, increase or decrease the state based on our "pairs" constant.
        else if(string_state === undefined && (char in pairs) )
        {
            let [key,value] = pairs[char];
            state[key] += value;
        }
        // If it's our split symbol...
        else if(char === split_by)
        {
            // ... check whether any flags are active ...
            if(Object.entries(state).every(([k,v])=>v == 0) && (string_state === undefined))
            {
                // ... if not, then this is a valid split.
                results.push(input.substring(start,i))
                start = i+1;
            }
        }
    }

    // Add the last segment if the string didn't end in the split_by symbol, otherwise add an empty string
    if(start < input.length)
    {
        results.push(input.substring(start,input.length))
    }
    else
        results.push("");

    return results;
}

A: With this regex, it makes the job:

const regex = /,(?![^(]*\))/g;
const str = '"abc",ab(),c(d(),e()),f(g(),zyx),h(123)';
const result = str.split(regex);

console.log(result);

A: Javascript
var str='"abc",ab(),c(d(),e()),f(g(),zyx),h(123)'
str.split('"').toString().split(',').filter(Boolean);

this should work