text:
Q: java.lang.SecurityException: Unable to locate a login configuration Hi
I am using Bonita5.2 and the Tomcat6.0.19
I exported the application(which gives a war file and some config file and libraries) and deployed in the tomcat. When I run the application, after the login page, I get the error

description The server encountered an internal error () that prevented it from fulfilling this request.

exception
java.lang.SecurityException: Unable to locate a login configuration
    com.sun.security.auth.login.ConfigFile.(Unknown Source)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    java.lang.reflect.Constructor.newInstance(Unknown Source)
         .
         .
         .
         .

Before starting tomcat I run a bat file with the following content:

set BONITA_OPTS="-Dorg.ow2.bonita.environment=d:\Tomcat6.0\conf\bonita-environment.xml"
set LOG_OPTS="-Djava.util.logging.config.file=d:\Tomcat6.0\conf\logging.properties"
set SECURITY_OPTS="-Djava.security.auth.login.config=d:\Tomcat6.0\conf\jaas-standard.cfg"
set JAVA_OPTS=%JAVA_OPTS% %LOG_OPTS% %SECURITY_OPTS% %BONITA_OPTS%

I guess this error is because the jaas config file is not found. But I am sure about the paths I have mentioned.
What else could be that I am missing to configure for jaas?
Thanks

A: Specifying the jaas config file like so on the command line would work also:
-Djava.security.auth.login.config=C:/Apps/apache-tomcat-6.0.29/conf/jaas.config

A: I am using the Tomcat 6.0.13 extracted (not Windows service) version and I faced the similar problem.
To fix it, I simply added the the following option to catalina.bat file:
set JAVA_OPTS=%JAVA_OPTS% "-Djava.security.auth.login.config=C:/SecureLoginModule.conf" %LOGGING_CONFIG%

It worked for me.
--
Tks

A:
I have resolve this problem. I needed to put the jaas cnfig file path in the file JAVA_HOME\jre6\lib\security\java.security
Thanks

A: Try this:
String configFileLocation = getServletContext().getRealPath("/WEB-INF/jaas.config");
    System.err.println(configFileLocation);
    System.setProperty("java.security.auth.login.config", configFileLocation);

in your servlet or JSP

A: inside catalina.bat
under line :okhome
add the following line
set JAVA_OPTS=%JAVA_OPTS% -Djava.security.auth.login.config=%CATALINA_HOME%/conf/jaas.config

It works for me. I have that error for past 2 days and thanks you for some else post in here


text:
Q: How to run an applymap function using grouby in pandas Dataframe? In a pandas Dataframe I want to applymap(somefunction) using groupby (using some column index values), which I am finding really difficult to accomplish.
mcve_01.txt
pos         f1_index      M1       M2      F1_x
16230484    141      G/G      G/G       G
16230491    141      C/C      C/C       C
16230503    141      T/T      T/T       T
16232072    211      A/A      A/A       A
16229783    211      C/C      C/C       G
16229992    211      A/A      A/A       G
16230007    211      T/T      T/T       A
16230011    263      G/G      G/G       C
16230049    263      A/A      A/A       T

I read the above file and set the pos and f1_index to index and rest of the column values to list:
mcve_data.set_index(['pos', 'index'], append= True, inplace = True)
mcve_list = mcve_data.applymap(lambda c:[list(c)])

So, now I want to read two lines (values) at the time and create either itertools.product vs zip of the two values using the function described below. I am not sure if this function is going to be useful but hope it helps the reader.
def mapfun(c):
if any(['.' in l for l in c]):
    return '.'

if all(['|' in l for l in c]):
    fun = zip

else:
    fun = product

filt_set = set(['|','/'])
filt = partial(filter,lambda l: not (l in filt_set))

return ','.join('g'.join(t) for t in fun(*map(filt, c)))

Final code: I take the above function and read two lines at a time using `mcve_list+mcve_list.shift(1):
mcve_mm = (mcve_list+mcve_list.shift(1)).dropna(how='all').\
    applymap(mapfun)

which gives me (final output) like:
pos    index      M1        M2      F1_x
16230484    141  CgG,CgG,CgG,CgG        CgG,CgG,CgG,CgG         CgG
16230491    141  TgC,TgC,TgC,TgC        TgC,TgC,TgC,TgC         TgC
.....      ...   TgT,TgT,TgT,TgT        TgT,TgT,TgT,TgT         TgT

Thing I want to fix - this is the problem:
All is fine with the above (function code) and final code except that now I want to run the function separately for each f1_index values. Doing this by group will not product or zip the list when the index value changes.
Things I tried:

*

*reseting the f1_index and then groupby('f1_index')
mcve_group = mcve_list.reset_index(level=['f1_index'])
mcve_group2 = mcve_group.groupby('f1_index')

for x, group in mcve_group2:
    mcve_mm2 = (mcve_group2+mcve_group2.shift(1)).dropna(how='all').\
    apply(mapfun)

And, also:
mcve_mm2 = (mcve_group2+mcve_group2.shift(1)).dropna(how='all').\
    apply(lambda x: [mapfun(c) for c in x])

*using groupby('key')
mcve_mm = (mcve_list+mcve_list.shift(1)).groupby('f1_index').dropna(how='all').\
applymap(mapfun)

*Wrapping the applymap
mcve_mm = (mcve_list+mcve_list.shift(1)).dropna(how='all').groupby(['f1_index'], group_keys = False).apply(lambda x: [mapfun])

I didn't get any error but the function part got messed up when trying to groupby and then apply.
I am also not finding any examples and tutorial that uses applymap along with groupby in pandas df.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP cant update SQLSTATE[HY093]: Invalid parameter number: no parameters were bound Table structure:
ex_id   int(11)
ex_fecha    date
ex_nombre   varchar(100)
ex_apaterno varchar(100)
ex_materno  varchar(100)
ex_correo   varchar(100)
ex_calle    varchar(100)
ex_numero   varchar(5)
ex_colonia  varchar(100)
ex_ciudad   varchar(100)
ex_telefono varchar(15)
ex_celular  varchar(15)
ex_sexo int(11)
ex_nacimiento   date
ex_religion int(11)
ex_ocupacion    varchar(100)
ex_reco_id  int(11)
Indices
PRIMARY ex_id

My updated query:
$stmt = $this->db->prepare("UPDATE expedientes SET  `ex_nombre` = ?,
                                                            `ex_apaterno` = ?,
                                                            `ex_materno` = ?,
                                                            `ex_correo` = ?,
                                                            `ex_calle` = ?,
                                                            `ex_numero` = ?,
                                                            `ex_colonia` = ?,
                                                            `ex_ciudad` =?,
                                                            `ex_telefono` = ?,
                                                            `ex_celular` = ?,
                                                            `ex_sexo` = ?,
                                                            `ex_nacimiento` = ?,
                                                            `ex_religion` = ?,
                                                            `ex_ocupacion` = ?,
                                                            `ex_reco_id` = ?
                                                             WHERE `ex_id` = ?");

$stmt->bindparam('ssssssssssidisii',$nombre,$paterno,$materno,$umail,$calle,$numero,$colonia,$ciudad,$telefono,$celular,$sexo,$nacimiento,$religion,$ocupacion,$recomendado,$ex_id);
$stmt->execute();

A: Remove the $stmt->bindparam line and when you call the execute method do this instead:
$stmt->execute(array($nombre,$paterno,$materno,$umail,$calle,$numero,$colonia,$ciudad,$telefono,$celular,$sexo,$nacimiento,$religion,$ocupacion,$recomendado,$ex_id));

You were using bindParam incorrectly, the first parameter of bindParam does this:

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.  Read more here

But with the execute method, the first parameter is this:

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.  Read more here


text:
Q: Como puedo hacer la funciones de cada uno de estos casos? Lo que necesito hacer es un formulario para almacenar nombre, apellido, matricula, nota, tengo que tener un boton para mostrarlo y uno para ingresar pero deben estar hecho por separado, y no se como hacerlo. Ademas debo mostrar la nota mas alta, mas bajita y el promedio. como puedo hacerlo.
La tarea es la siguiente:

*

*Crear la clase Estudiante con los atributos:
nombre, apellido, matricula y nota.

*Crear un documento html con cajas de texto para cada uno de los atributos: nombre, apellido, matricula y nota. Agregar un botón "Agregar".

*Con JS manejar el evento click del botón para que tome las informaciones de las cajas de texto y las asigne a un nuevo objeto de tipo Estudiante. El nuevo objeto se debe almacenar en un arreglo.

*Crear un botón "Mostrar estudiantes" que muestre una lista (en html) de todos los estudiantes con cada uno de sus datos ( nombre, apellido, matricula y nota ). Debe crear una función para esto y manejarla con el evento click.

*Mientras se vayan agregando los estudiantes se debe mostrar automáticamente el promedio, la nota máxima y la nota mínima. (Cada una de ellas deben ser calculadas y retornadas con funciones independientes).

*Aplicar estilos a su html para dar un toque agradable a la UI
  class Estudiantes{
          constructor(nombre,apellido,matricula,nota){
              this.nombre= nombre;
              this.apellido = apellido;
              this.matricula = matricula;
              this.nota = nota;
          }
      }
      const Agregar = () => {
          let nombre = document.getElementById("nombre").value;
          let apellido = document.getElementById("apellido").value;
          let matricula = document.getElementById("matricula").value;
          let nota = document.getElementById("nota").value;

          let student = new Estudiantes(nombre,apellido,matricula,nota);
          let Alumnos = [];
          Alumnos.push(student);
          Mostrar(Alumnos);
          document.getElementById("nombre").value = " ";
          document.getElementById("apellido").value = " ";
          document.getElementById("matricula").value = " ";
          document.getElementById("nota").value = " ";
        };

          let Mostrar = (Alumnos = []) => {
          let tabl = document.querySelector('#data').innerHTML;
          for (let i = 0; i < Alumnos.length; i++) {

              tabl += `

                  ${Alumnos[i].nombre}
                  ${Alumnos[i].apellido}
                  ${Alumnos[i].matricula}
                  ${Alumnos[i].nota}

`;

              }

              document.querySelector('#data').innerHTML = tabl;

      }

      <!DOCTYPE html>

              <meta charset="UTF-8">
              <meta http-equiv="X-UA-Compatible" content="IE=edge">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
              <link rel="stylesheet" href="style.css">

              <title>Ejercicio C</title>

                          <form id="formulario" class="p-3 mt-5 shadow border">

Formulario

                          Nombre
                          <input id="nombre" class="form-control my-2" type="text" >

                          Apellido
                          <input id="apellido" class="form-control my-2" type="text" >

                          Matricula
                          <input id="matricula" class="form-control my-2" type="text" >

                          Nota
                          <input id="nota" class="form-control my-2" type="text">

                          <button class="btn btn-primary mt-2" type="button" onclick="Agregar()">Agregar</button>
                          </form>

                          Nombre

                         Apellido

                          Matricula

                         Nota


text:
Q: How can I make a predict with a lstm-ctc checkpoint in mxnet? I following example/warpctc/lstm_ocr.py to training a model. Now I had saved a checkpoint mymodel-0100.params and mymodel-symbol.json.
So, How can I make a predict with this checkpoint use only one image?
I had tired to use Predictor interface, code below:
# Load the pre-trained model
symbol_file = "mymodel-symbol.json"
param_file = "mymodel-0100.params"
predictor = Predictor(open(symbol_file).read(),
    open(param_file).read(),
    {'data':(80, 30)})

But data shape always raise error and I don't know how to set this value. Anybody help me thank you.
However, I also tried another way:
add one line code in the end of mxnet/example/warpctc/lstm_ocr.py:
model = mx.model.FeedForward(ctx=contexts,
                             symbol=symbol,
                             num_epoch=num_epoch,
                             learning_rate=learning_rate,
                             momentum=momentum,
                             wd=0.00001,
                             initializer=mx.init.Xavier(factor_type="in", magnitude=2.34))

model.fit(X=data_train, eval_data=data_val,
          eval_metric = mx.metric.np(Accuracy),
          batch_end_callback=mx.callback.Speedometer(BATCH_SIZE, 50),)

model.save("ocr")

# add new line for predict
model.predict(data_val)

But it is always error output:
Traceback (most recent call last):
File "lstm_ctc_ocr.py", line 211, in <module>
training_all()
File "lstm_ctc_ocr.py", line 188, in training_all
model.predict(data_val)
File "/home/bobliu/Work/code/DL/mxnet/python/mxnet/model.py", line 618, in predict
self._init_predictor(data_shapes, type_dict)
File "/home/bobliu/Work/code/DL/mxnet/python/mxnet/model.py", line 541, in _init_predictor
self.ctx[0], grad_req='null', type_dict=type_dict, **dict(input_shapes))
File "/home/bobliu/Work/code/DL/mxnet/python/mxnet/symbol.py", line 685, in simple_bind
arg_types, _, aux_types = self.infer_type(**type_dict)
File "/home/bobliu/Work/code/DL/mxnet/python/mxnet/symbol.py", line 417, in infer_type
ctypes.byref(complete)))
File "/home/bobliu/Work/code/DL/mxnet/python/mxnet/base.py", line 77, in check_call
raise MXNetError(py_str(_LIB.MXGetLastError()))
mxnet.base.MXNetError: InferType Error in reshape0: [21:39:03] src/operator/./reshape-inl.h:345: Check failed: (dtype) != (-1) First input must have specified type

A: After reading the source code. I know what's wrong with me now.
1. Regrading to predictor() function.
We have to set data shape with a full symbol.
In this example:
    init_c = [('l%d_init_c'%l, (batch_size, num_hidden)) for l in range(num_lstm_layer)]
    init_h = [('l%d_init_h'%l, (batch_size, num_hidden)) for l in range(num_lstm_layer)]
    init_states = init_c + init_h

    all_shapes = [('data', (batch_size, 100 * 30))] + init_states + [('label', (batch_size, num_label))]

So, You have to set for data with all shapes.
2. Regrading to model.predict
I think a bug appear in source code, But i am not sure if i was wrong.
Please check predict function in model.py file.
change below code(Take care to X.provide_label):
    data_shapes = X.provide_data + X.provide_label
    data_names = [x[0] for x in data_shapes]
    type_dict = dict((key, value.dtype) for (key, value) in self.arg_params.items())
    for x in X.provide_data + X.provide_label:
        if isinstance(x, DataDesc):
            type_dict[x.name] = x.dtype
        else:
            type_dict[x[0]] = mx_real_t

and this point:
        for o_list, o_nd in zip(output_list, self._pred_exec.outputs[0:real_size]):
            o_list.append(o_nd.asnumpy())

Now, everything working well with me.


text:
Q: Open button in new window? How would I go about making the button open in a new window, emulating "a href, target = _blank"?
I currently have:
<button class="button" onClick="window.location.href='http://www.example.com';">
     Open
</button>

The button isn't in a form, I just want to make it open in a new window.

A: Opens a new window with the url you supplied :)
<button class="button" onClick="window.open('http://www.example.com');">
     Open
</button>

A: I couldn't get your method to work @Damien-at-SF...
So I resorted to my old knowledge.
By encasing the input type="button" within a hyperlink element, you can simply declare the target property as so:

<input type="button" class="button" value="Open" />

The 'target="_blank"' is the property which makes the browser open the link within a new tab. This attribute has other properties, See: http://www.w3schools.com/tags/att_a_target.asp for further details.
Since the 'value=""' attribute on buttons will write the contained string to the button, a span is not necessary.
Instead of writing:
<element></element>

for most HTML elements you can simply close them with a trailing slash, like so:
<element />

Oh, and finally...  a 'button' element has a refresh trigger within it, so I use an 'input type[button]' to avoid triggering the form.
Good Luck Programmers.
Due to StackOverflow's policy I had to change the domain in the example:
https://meta.stackexchange.com/questions/208963/why-are-certain-example-urls-like-http-site-com-and-http-mysite-com-blocke

A: <input type="button" onclick="window.open(); return false;" value="click me" />

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

A: You can acheive this using window.open() method, passing _blank as one of the parameter. You can refer the below links which has more information on this.
http://www.w3schools.com/jsref/met_win_open.asp
http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx
Hope this will help you.

A: If you strictly want to stick to using button,Then simply create an open window function as follows:

Then in your html do the following with your button:
Join
So you would have something like this:

<button  onclick="myfunction()" type="button" class="btn btn-default subs-btn">Join</button>


text:
Q: Applescript / Photoshop - Some sort of "wait if busy" command? I have some code that constantly checks for any open documents and adds a comment in finder when it is closed.
I'm having an issue though that if anything like the "Do you wish to save?" or "Loading..." comes up, it's some weird limbo between 0 and 1 and can't seem to count properly. It then crashes with the generic "General Photoshop Error" message.
Is there some sort of "Pause/Wait if busy" command, or some other way around this?
repeat

tell application "Adobe Photoshop CS6"

    set D1 to count documents

    local mainDocList
    set mainDocList to {}

    if ((count mainDocList) ≠ D1) then
        log "Main Ran"
        if (D1 > 0) then
            set c to 1
            repeat while (c ≤ D1)
                set mainDocList to mainDocList & (file path of document c)
                set c to c + 1
            end repeat
        end if
    end if

    delay 3

    set D1 to count documents

    local currentDocList
    set currentDocList to {}

    if ((count currentDocList) ≠ D1) then
        log "Current Ran"
        if (D1 > 0) then
            set c to 1
            repeat while (c ≤ D1)
                set currentDocList to currentDocList & (file path of document c)
                set c to c + 1
            end repeat
        end if
    end if

end tell

local closedList, a
set closedList to {}
if ((count mainDocList) ≠ (count currentDocList)) then
    repeat with a in mainDocList
        set a to contents of a
        if {a} is not in currentDocList then set end of closedList to a
    end repeat
end if
log "∆: " & (count closedList)
log "- - - - -"

if ((count closedList) > 0 and ((count mainDocList) > (count currentDocList))) then
    tell application "Finder"
        set c to 1
        repeat while (c ≤ (count closedList))
            tell application "System Events"
                set modDate to modification date of (item c of closedList)
            end tell

            set theDate to current date

            set Y to text -2 thru -1 of ("00" & (year of theDate))
            set M to text -2 thru -1 of ("00" & ((month of theDate) as integer))
            set D to text -2 thru -1 of ("00" & (day of theDate))
            set spartanDate to Y & M & D

            set theTime to (time string of theDate)
            set theTime to text -11 thru -7 of ("00" & (time string of theDate))

            set currentComments to (get comment of (item c of closedList))
            set comment of (item c of closedList) to currentComments & (" | USER-" & spartanDate & "-" & theTime)
            log "******************COMMENTED"
            set c to c + 1
        end repeat
    end tell
end if

end repeat

A: Well, it would help if you indicated WHERE in the code it seems to hang. In my opinion, any Applescript code that is dealing with files should be liberally sprinkled with try...on error...end blocks.
try
    ...
 on error errMsg
    display dialog "ERROR: " & errMsg
end try

Once you've identified where the problem is triggered, and see the error message, you and we would be better able to fix the problem.
Also, if you suspect that a modal dialog popping up is part of the problem, encircle that code with a timeout block:
with timeout of 60000 seconds
   ... could that could otherwise timeout
end

Every script statement is subject to a timeout, and bad things usually happen if you do not either catch the timeout in a TRY block or think ahead and guard against it with a TIMEOUT block.


text:
Q: Send one-shot ViewModel event when using Jetpack Compose Previously I was able to fire a navigation event from ViewModel to a fragment using Event class
Something like this
[ViewModel]
private val _navigate = MutableLiveData<Event<String>>()
val navigate: LiveData<Event<String>> =_navigate

fun onClickNext(id: String) {
     // some processing
     _navigate.value = Event(id)
}

[Fragment]
viewModel.navigation.observe(viewLifecycleOwner, EventObserver {
    navigateToUser(it)
})

How can I do the same thing with Jetpack Compose?

Scenario: User clicks login button, the event goes to ViewModel, the
ViewModel does some processing and if the operation is successful fire
an event to Compose view to initiate navigation

A: Well you can do something like this
fun LoginRoute(viewModel: ....., onLoginSuccess:() -> Unit) {
   LoginScreen(
     onClickLogin = {viewModel.onLogin(onLoginSuccess)}
   )
}

fun LoginScreen(onClickLogin: () -> Unit) {
    // Invoke login somethow
}

class LoginViewModel (): ViewModel() {
    fun onLogin(success: () -> Unit) {
        // Show loading or something
        viewModelScope.launch {
            // Call repo/use-case to authenticate the user
            if failed
                // Show error
            else
                success()
                // Remove loading
        }

    }
}

If you use state hoisting your ViewModel is supposed to have the supposed entered username / password / credential.
Simple . . .
Check out this example if you want to learn more


text:
Q: ReportLabs Django Integration I'm following this link to integrate the ReportLabs in Django. I did everything correctly but I get an error saying -
Exception Type: RenderPMError

Exception Value:
Can't setFont(Times-Roman) missing the T1 files?
Originally <type 'exceptions.TypeError'>: makeT1Font() argument 2 must be string, not None

Where I'm going wrong? I guess the font is not available in ReportLabs package. How do I proceed from here?

A: To register a font:
import os
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont(TTFont("Arial", os.path.join(settings.PROJECT_ROOT, 'static', 'fonts', 'arial.ttf'))) # here i have my fonts for PDF's

to use it, ex:
page = canvas.Canvas(response, pagesize=A4, pageCompression = 0)

canvas.setFont('Arial',9)

A: You have to download the fonts and place them in your ReportLabs package.
You need these files:
http://www.reportlab.com/ftp/fonts/pfbfer.zip
Unzip them in:
/path/to/your/python/site-packages/reportlab/fonts


text:
Q: Use of require and referencing gem objects Beginner Ruby question here...
I'm using the AWS SDK, when I want to access an S3 resource I use:
Aws::S3::Resource.new

Given this code is from the aws-sdk gem, shouldn't I need:
require 'aws-sdk'

At the top of my file?
Seems to work without this so I'm just curious of the best practice and when I actually need to require things. Or if I'm just going about it in the complete wrong way...

A: The idea of the kernel method require is very simple. It runs the file being required, but only once. For example, there are 2 ruby script files:
foo.rb
puts 'foo'

main.rb
require '/path/to/foo.rb'
require '/path/to/foo.rb'

When you run ruby main.rb, you will see it prints foo only once, although it is required twice.
It is a common situation that a ruby script file defines a module or a class in it. require-ing such files loads the modules/classes into memory.
You said that require 'aws-sdk' sometimes can be omitted, that's because bundler has already done the require job for you.
Gemfile
gem 'aws-sdk'

Somewhere in your booting logic
require 'bundler/setup'
Bundler.require :default

The combination of the 3 lines of code did the trick.


text:
Q: split one column values into multiple column based another column value could you please help me writing select query to get expected output from the below picture. what I want is to split the UPC column values into three columns(Bottle UPC, Pack UPC, Case UPC) based on its UOM column values ZF2, ZF1 and ZF3 respectively.
any help would be appreciated. Thank you!

A: You can use three queries to separate the columns and join them with UNION ALL. We then use max to only keep the one we want.
I'm aware that this is not exactly the format you showed but it does include all the information without duplication.
Select
  Material_id,
  UOM,
  Max(Bottle) as Bottle_UPC,
  Max(Pack) as Pack_UPC,
  Max(Case) as Case_UPC
From
(
Select
  Material_id,
  UOM,
  UPC as Bottle,
  '' as Pack,
  '' as Case
From table_name
Where UOM = 'ZF1'
   Union all
Select
  Material_id,
  UOM,
  '' ,
  UPC ,
  ''
From table_name
Where UOM = 'ZF2'
   Union all
Select
  Material_id,
  UOM,
  '' ,
  '' ,
  UPC
From table_name
Where UOM = 'ZF3'
)
Group by
  Material_id,
  UOM,

A: This is one way to get the exact result you want, but it is confusing why you'd want all three rows to be returned with values you've already transposed to the first row only...
;WITH cte AS
(
  SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY Material_ID ORDER BY UOM),
    bupc = CASE WHEN UOM = 'ZF2' THEN UPC END,
    pupc = CASE WHEN UOM = 'ZF1' THEN UPC END,
    cupc = CASE WHEN UOM = 'ZF3' THEN UPC END
  FROM dbo.SomeTableName AS s
),
agg AS
(
  SELECT Material_ID,
    bupc = MAX(bupc),
    pupc = MAX(pupc),
    cupc = MAX(cupc)
  FROM cte GROUP BY Material_ID
)
SELECT cte.Material_ID, cte.UOM,
    [Bottle UPC] = COALESCE(agg.bupc, ''),
    [Pack UPC]   = COALESCE(agg.pupc, ''),
    [Case UPC]   = COALESCE(agg.cupc, '')
  FROM cte
  LEFT OUTER JOIN agg ON agg.Material_ID = cte.Material_ID
  AND cte.rn = 1;

*

*Example db<>fiddle


text:
Q: How to get update statement in trigger function or when condition CREATE TABLE accounts (
 id SERIAL PRIMARY KEY,
 email TEXT,
 verified BOOLEAN DEFAULT FALSE,
 ...
);

CREATE OR REPLACE FUNCTION fn_reset_verified() RETURNS TRIGGER AS $$
BEGIN
IF (
    OLD.email != NEW.email -- do nothing if no change
) THEN
    RAISE NOTICE 'UPDATE';
    UPDATE users SET verified=FALSE WHERE id=NEW.id;
END IF;
RETURN NEW;
END; $$ language 'plpgsql';

CREATE TRIGGER reset_verified AFTER UPDATE OF email ON accounts
FOR EACH ROW
WHEN (OLD.email != NEW.email) -- only when email changed
EXECUTE PROCEDURE fn_reset_verified();

Based on above schema, I wish to create trigger to automatic update verified to false if user change email.
It work well for below statement:
UPDATE accounts SET email='newemail@email.com' WHERE id=1;

My problem come in when I intend update the email and set verified to TRUE at same time like below statement:
UPDATE accounts SET email='verified@email.com', verified=TRUE WHERE id=1;

If verified is been set in update statement, I should skip the function. Maybe condition as below:
WHEN (OLD.email != NEW.email AND STATEMENT.verified IS NULL)

So is there any way I can get the update statement or involved column?

A: First, you should NEVER call UPDATE on a table within an update trigger on that table. Chances are that you will endless loop (not in this particular case, but anyway) and there are typically better ways to achieve the same thing.
In your case, you would make a BEFORE UPDATE trigger that fires when the email address changes and check/modify the verified column within that trigger:
CREATE OR REPLACE FUNCTION fn_reset_verified() RETURNS TRIGGER AS $$
BEGIN
    -- Below condition does not have to be checked because of WHEN clause in trigger
IF (
    OLD.email != NEW.email -- do nothing if no change
) THEN
    RAISE NOTICE 'UPDATE';
    NEW.verified := ...;
END IF;
    RETURN NEW;
END; $$ language 'plpgsql';

CREATE TRIGGER reset_verified BEFORE UPDATE OF email ON accounts
FOR EACH ROW
WHEN (OLD.email != NEW.email) -- only when email changed
EXECUTE PROCEDURE fn_reset_verified();
However, there is no logic to determine what to set NEW.verified to inside the trigger. The thing is, the NEW variable holds the values of all the columns of the new row after setting the columns with new values, not just those values being modified by the command. So if NEW.verified = true there is no way to know if the command that invoked the trigger was:
UPDATE accounts SET email = 'newemail@email.com', verified = true WHERE id = 1;

or
UPDATE accounts SET email = 'newemail@email.com' WHERE id = 1;

So NEW.verified could refer to the old email address or to the new email address which is specifically labeled as verified in the UPDATE command.
Your only option is to change your logic: if the email address changes, it always needs to be verified after, so NEW.verified = false.


text:
Q: Attribute "transform" works for some elements, not others Chrome iOS first post so apologies if my formatting is rough - I will try to present verbose issue information.
Background info - I need to use Javascript to perform transformations on nested SVG elements.
Platform: Google Chrome iOS
Problem Description:
Parent SVG hangar does not transform when the transform attribute is added.
hangar.setAttribute("transform", "scale(" + scale + ") " +
"translate(" + translateValues.x + "," + translateValues.y + ") ");

Child SVG towG does transform when transform attribute is added.
towG.setAttribute("transform", "scale(" + (100/slider.value)*towScale + ")");

This may or may not be relevant but the transform is performed on a  tag on the Child SVG.
Thanks in advance,
Derrek
Edit
When I log the hangar.getAttribute("transform") the expected value is printed, but the hangar SVG is not transformed.

A: Try implementing support locally within a CSS file without Javascript. If it doesn't work, then Google Chrome iOS still hasn't implemented support for the transform attribute, unfortunately :(
User agent scans are inefficient, but it's the only way to find out if a mobile user has Chrome for iOS.
I would suggest using a CSS media query, and then scan if X element is displayed, then that means that the display is of your specified size, and if it returns true then you start the scan. You have to find the user agent string and search for 'Chrome iOS' somewhere in there.
Edit: I installed the User Agent Manager extension on my browser, and the user agent string I got from it was this: Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/80.0.3987.95 Mobile/15E148 Safari/604.1. Hope it helps
If it is on Chrome iOS, then you'd want to replace that property with something similar, so as to maintain compatibility, partial compatibility is better than none.
In the meantime, you would probably want to submit a report to Google on this issue, as Chrome iOS is a pretty big userbase, you don't want to have to keep making these exceptions.

A: Instead of setting the attribute transform, try setting the transform within the style:
hangar.style.transform = "scale(" + scale + ") " + "translate(" + translateValues.x + "px," + translateValues.y + "px) ";

towG.style.transform = "scale(" + (100/slider.value)*towScale + ")";


text:
Q: Why can't I query by reference with Spring Data Jdbc? I created a query method using a Reference from another Aggregate.
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE, onConstructor_=@PersistenceConstructor)
public static class Book {

    public static Book of(Author author) {
        return new Book(null, AggregateReference.to(author.id));
    }

    @Id
    private Long id;

    private AggregateReference<Author, Long>  authorId;
}

interface BookRepository extends CrudRepository<Book, Long> {

    List<Book> findBooksByAuthorId(Long  authorId);
}

But I got the following exception:
    Caused by: java.lang.IllegalArgumentException: Cannot query by reference: authorId
    at

I have checked the source below.
But I don't understand why it throws an exception.
org.springframework.data.jdbc.repository.query.JdbcQueryCreator.validateProperty(JdbcQueryCreator.java:146)

        private static void validateProperty(PersistentPropertyPathExtension path) {
         .....

        if (path.getRequiredPersistentPropertyPath().getLeafProperty().isReference()) {
            throw new IllegalArgumentException(
                    String.format("Cannot query by reference: %s", path.getRequiredPersistentPropertyPath().toDotPath()));
        }
    }

Why can't I create a query method on a Reference?
The source for your reference is here.
https://github.com/yangwansu/try-spring-data-jdbc/blob/main/src/test/java/masil/example/springdata/jdbc/ch9_7/QueryToAggregateReferenceTest.java

A: For anybody coming to this at a later time:
This was a limitation of Spring Data JDBC. Thanks for finding it.
It is now properly implemented. The first version with the fix included is the 2.3 M1 release.
See the issue created by Wansu yang for details.


text:
Q: Prestashop 1.7, error on translated pages I'm having a weird issue here.
Everytime I try to access my prestashop 1.7 website in another language than the default one (EN atm), I get a blank page.
I enabled the debug mode and this is the error I'm receiving :
ContextErrorException in ApiClient.php line 52:
Notice: Undefined offset: 1

It's even more weird that I've created a custom module and there's no error in any other languages on my module's pages.
has anyone already faced this problem?  I'm really struggling here.
Thank's !
[EDIT] :
I managed to get it working, by reinstalling a new PS 1.7.2.2 .. Had to reinstall a lot of other things so this isn't the best option but now at least it works.  I don't know what I've done on the previous version to break everything because I actually repeated the same steps here :/


text:
Q: What makes heroku response time too much slow I am making a rails application to crawl the flight information from specific website. This app can be found here https://vemaybay.herokuapp.com/.
It only took around 4-5 seconds to response locally, but it took 15-20 seconds when running on heroku.
Is there anyway to speed up this response time?
I have already changed the free to hobby dyno type to avoid DB spin-up costs but I believe DB connection and query is not the root cause.
Is it related to the hosting problem? So can think about buying a host.
Below is my example code:
FlightService
 def crawl(from, to, date)
return if flight_not_available?(from, to)
begin
  selected_day = date.day - 1
  browser = ::Ferrum::Browser.new
  browser.headers.set({ "User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36" })

  browser.goto("https://www.abay.vn/")
  browser.at_css("input#cphMain_ctl00_btnSearch").click
  browser.back

  browser.execute("document.getElementById('cphMain_ctl00_txtFrom').setAttribute('value','#{from}')")
  browser.execute("document.getElementById('cphMain_ctl00_txtTo').setAttribute('value','#{to}')")
  browser.execute("document.getElementById('cphMain_ctl00_cboDepartureDay').selectedIndex = #{selected_day}")
  browser.at_css("input#cphMain_ctl00_btnSearch").click
  # browser.execute("document.querySelectorAll('a.linkViewFlightDetail').forEach(btn=> btn.click())")
  sleep(1)
  body = Nokogiri::HTML(browser.body)

  flight_numbers = body.css("table.f-result > tbody > tr.i-result > td.f-number").map(&:text)
  depart_times = body.css("table.f-result > tbody > tr.i-result > td.f-time").map { |i| i.text.split(" - ").first }
  arrival_times = body.css("table.f-result > tbody > tr.i-result > td.f-time").map { |i| i.text.split(" - ").second }
  base_prices = body.css("table.f-result > tbody > tr.i-result > td.f-price").map(&:text)

  prices = base_prices
  store_flight(flight_numbers, from, to, date, depart_times, arrival_times, base_prices, prices)
  browser.quit
rescue StandardError => e
  Rails.logger.error e.message
  fail_with_message(e.message)
  browser.quit
end

end
Then in my controller i just call the crawl method to fetch data:
service = FlightService.new(from: @from, to: @to, departure_date: @departure_date, return_date: @return_date)
service.crawl_go_flights
@go_flights = service.go_flights

A: I would try to add NewRelic Heroku add-on, it will show you what takes the most time, most likely it will be your Ruby code doing HTTP requests in a controller action to crawl a page.
Heroku tends to be slower than running code on your own development machine because Heroku resources are shared across users unless you bought expensive M/L dynos.
Without you sharing the code for crawling we don't know much how it work and where is the bottleneck. Do you crawl the single page or many pages (then this might be slow).
You can try moving crawl logic to the background worker, for instance, use Sidekiq gem. You could crawl page from time to time and store results in your DB then your controller action would only ask for data from your DB instead of crawling page every time. You can also use a rake task every 10 minutes defined in Heroku Scheduler to crawl page instead of Sidekiq (this might be faster to do). I don't know if having data up to date every 10 minutes is good enough for your use case. You need to pick a tech solution for your business use case needs. With Sidekiq you could run jobs more often by starting them every 1 minute using clockwork gem.


text:
Q: TypeError: 'float' object is not iterable i'm using scrapy and python 3.5 I have a problem with my scrapyspider which uses the following code:
class MySpider(BaseSpider):
    name = "craig"
    allowed_domains = ["craigslist.org"]
    start_urls = ["http://sfbay.craigslist.org/search/npo"]

    def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.xpath("//span[@class='pl']")
    items = []
    for i in titles:
        item = CraigslistSampleItem()
        item["title"] = i.select("a/text()").extract()
        item["link"] = i.select("a/@href").extract()
        items.append(item)
    return items

This is my items.py
from scrapy.item import Item, Field

class CraigslistSampleItem(Item):
    title = Field()
    link = Field()

When I run the spider with scrapy crawl craig, I get the following error:
TypeError: 'float' object is not iterable
2017-03-07 10:13:44 [scrapy.core.scraper] ERROR: Error downloading <GET http://sfbay.craigslist.org/search/npo>
TypeError: 'float' object is not iterable

How can I fix this?
Thanks

A: I encountered a similar error after installing scrapy using conda which resulted in getting scrapy version 1.1 and twisted version 17.1.0.
I believe there is an incompatibility between scrapy versions less than 1.3.2 and twisted version 17.x. I was able to resolve it by downgrading twisted to version 16.x or upgrading scrapy to version 1.3.3.


text:
Q: Generate List of random Floats in a sequence for Mocking IoT Sensor I have been struggling to mock the IoT Sensor data. I need a list of floats which will increase and decrease sequentially.
For example [0.1, 0.12, 0.13, 0.18, 1.0, 1.2, 1.0, 0.9, 0.6]
Right now I have generated the list with max and min range using this,
for k in dts:
    x = round(random.uniform(j["min"], j["max"]), 3)
    random_float_list.append(x)

list generated form this code is not in a sequence. I need something which generates random floats in range and there are no abrupt changes in it. Values can increase and decrease in a sequence.

A: You can generate multiple random sequences and glue them together. Something like this:
import numpy as np

def gen_floats(count, min_step_size, max_step_size, max_seq_len):
    # Start around 0
    res = [np.round(np.random.rand() - 0.5, 2)]
    while len(res) < count:
        step_size = np.random.uniform(min_step_size, max_step_size)
        # Generate random number of steps for sequence
        remaining = count - len(res)
        steps = np.random.randint(1, remaining + 1 if remaining < max_seq_len else max_seq_len)
        # Generate additive or subtractive sequence using previous values
        if np.random.rand() > 0.5:
            vals = np.round(np.linspace(res[-1] + step_size, res[-1] + steps * step_size, steps), 2)
        else:
            vals = np.round(np.linspace(res[-1] + step_size, res[-1] - steps * step_size, steps), 2)
        res.extend(vals)
    return res

Then print(gen_floats(20, 0.1, 0.5, 10)) generates something like: [0.4, 0.86, 0.25, -0.37, -0.99, -1.61, -2.23, -2.85, -2.64, -2.95, -3.26, -3.57, -3.88, -3.63, -3.38, -3.19, -2.89, -2.63, -3.15, -3.68]. You can play with params to match desired output.

A: Something like this should work if you want a random where you can control the min, max and max difference between the values.
It will first random a value between start and end and append it to the list output. The next value will be a random value between the last value in the output list +-max_diff.
import random
def rand(start,end,max_diff,elements,output):
    elements -= 1
    if output:
        if output[-1]-max_diff < start: #To not get a value smaller than start
            output.append(round(random.uniform(start,output[-1]+max_diff),3))
        elif output[-1]+max_diff > end: #To not get a value bigger than end
            output.append(round(random.uniform(output[-1]-max_diff,end),3))
        else:
            output.append(round(random.uniform(output[-1]-max_diff,output[-1]+max_diff),3))
    else:
        output.append(round(random.uniform(start,end),3))
    if elements > 0:
        output = rand(start,end,max_diff,elements,output)
    return output

print(rand(1,2,0.1,3,[])) #[1.381, 1.375, 1.373]

A: You can generate random numbers with a uniform distribution, and then sort the numbers into ascending order in the first part, and into descending order in the second part.
import numpy as np
np.random.seed(0)

def gen_rnd_sensor_data(low: float,
                        high: float,
                        n_incr: int,
                        n_decr: int) -> np.ndarray:
    incr = np.random.uniform(low=low, high=high, size=n_incr)
    incr.sort()
    decr = np.random.uniform(low=low, high=high, size=n_decr)
    decr[::-1].sort()
    return np.concatenate((incr, decr))

Then you can call this function with:
print(gen_rnd_sensor_data(0, 1, 5, 3))

This generates data within 0. and 1., the first 5 values are increasing, the last 3 are decreasing. Within the program, every time you call the function, you get different results, but if you rerun your program, you get the same results, so you can debug your program.


text:
Q: Evaluation of the contour integral $\int_\beta \frac{e^z}{e^z-\pi} \mathrm dz$
Suppose $\beta$ is a loop in the annulus $\{z:10<\left|z\right|<12\}$ that winds $N$ times about the origin in the counterclockwise direction, where $N$ is an integer.  Determine the value of the contour integral $$\int_\beta \frac{e^z}{e^z-\pi} \mathrm dz$$

Well, it certainly looks like a Cauchy's theorem problem of some kind, but I'm not sure how to get it in the right format.  Algebraically it doesn't seem like there's any way to turn this into the form $$\int \frac{f(z)}{(z-a)^n}\mathrm dz$$ The only idea I have is to somehow consider this in "$e^z$ space," but I'm not sure how to pull this off.
(Note: This is exam review, not homework.)

A: Lets do this another way:
$$\int_\beta \frac{e^z}{e^z-\pi}\,\mathrm{d}z = \int_\beta \frac{\mathrm{d}z}{1-e^{\log(\pi)-z}} = \int_\beta \frac{(z-\log(\pi))(1-e^{\log(\pi)-z})^{-1}}{z-\log(\pi)}\,\mathrm{d}z$$
I claim $f(z) = (z-\log(\pi))(1-e^{\log(\pi)-z})^{-1}$ is analytic near $\log(\pi)$, for
$$f(z) = \frac{z-\log(\pi)}{1-e^{\log(\pi)-z}} = \frac{z-\log(\pi)}{-\sum_{n=1}^\infty\frac{1}{n!}(\log(\pi)-z)^n} = \frac{1}{\sum_{n=1}^\infty\frac{1}{n!}(\log(\pi)-z)^{n-1}},$$
and thus especially $f(\log(\pi))=1$.
As Girianshiido remarks, there are three relevant $\log(\pi)$'s.
Hence by Cauchy, $\displaystyle \int_\beta \frac{f(z)}{z-\log(\pi)}\,\mathrm{d}z = 3\cdot 2\pi i N$.

A: The function $f:z\mapsto \dfrac{e^z}{e^z-\pi}=\dfrac{e^z}{g(z)}$ is meromorphic on $\Bbb C$ and has three poles in the interior of the loop $\beta$.
They are the zeros of $g$, $z_k=\ln(\pi)+2ik\pi$, $k\in\Bbb Z$, that have a modulus lesser than 10, i.e. $z_{-1}=\ln(\pi)-2i\pi$, $z_0=\ln(\pi)$ and $z_1=\ln(\pi)+2i\pi$.
You can easily check that the other zeros of $g$ have a modulus greater than 12.
We have, for all $k\in\Bbb Z$, $\mathrm{Res}(f,z_k)=\displaystyle\lim_{z\to z_k}\ (z-z_k) f(z)=\dfrac{e^{z_k}}{g'(z_k)}=\dfrac{e^{z_k}}{e^{z_k}}=1$
By the residue theorem : $\displaystyle\int_\beta f(z) dz=2i\pi\sum_{k=-1}^1I(\beta,z_k)\mathrm{Res}(f,z_k)=6i\pi N$


text:
Q: How can this excepction handling be made simpler? I have the equivalent to the following code:
class SomeError(Exception): pass

def do_things_with(fileobject):
    # Do things, and at some point the line below MAY be called
    raise SomeError

def try_another_approach():
    # Do different things, but at some point the line below MAY be called
    raise SomeError

try:
    try:
        with open('somefile') as somefile:
            do_things_with(somefile)
    except FileNotFoundError:
        try_another_approach()
except SomeError:
    print('Ooops')

That is, I try to open a file (or any other thing that may raise certain other exceptions) and if that fails a different approach may be used, but BOTH approaches may raise the same set of exceptions.
Right now I have to handle this with a nested try/except, as shown, but I would love to do something like this:
try:
    with open('somefile') as somefile:
        do_things_with(somefile)
except FileNotFoundError:
    # I'd like to have any SomeError raised from the function below
    # at the except clause just below, to keep code compact as I may
    # be adding more exceptions in the future
    try_another_approach()
except SomeError:
    print('Ooops')

Of course that doesn't work (I get one of those During handling of the above exception, another exception occurred), but it illustrates what I want to achieve: handle exceptions raised both in the try block and in some except block with a later except block, without nesting.
I don't need to avoid the nesting, I'm just curious about any way of solving this without having to nest, just in case.
Is it at all possible in Python?
Thanks in advance :)

A: No, you can't. Exceptions raised in an except clause will look for a handler in an outter block (i.e the nesting you do). There's no other way to go about this if in your current approach without nesting.
The only way you can remove the nesting is if you reduce the exceptions; that is, instead of raise Error you return a value as an indication that something went wrong. In that case you act on the returned value (with an if clause) instead of acting on the returned exception (with a try-except clause).


text:
Q: SQL XQuery Selector for Key/Value Pairs I have some xml in a column like this.
<ScopedWorkflowConfiguration xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/workflow/2012/xaml/activities">
  <appSettings>
    <AppSetting>
      <Key>CurrentWebUri</Key>
      <Value>http://myurl.org</Value>
    </AppSetting>
    <AppSetting>
      <Key>SomethingElse</Key>
      <Value>1</Value>
    </AppSetting>
    <AppSetting>
      <Key>AnotherThing</Key>
      <Value>420</Value>
    </AppSetting>
  </appSettings>
</ScopedWorkflowConfiguration>

Trying to select the value of the Value node.
;WITH Casted AS (SELECT t.Id, t.[Configuration] As XmlData FROM dbo.MyTable AS t)
Select Distinct
     Id
    ,pv.value('//*:Key="CurrentWebUri"/Value', 'nvarchar(max)') As CurrentWebUri
From
    Casted
    Cross Apply Casted.XmlData.nodes(N'//*:ScopedWorkflowConfiguration//*:appSettings//*:AppSetting') AS A(pv)

I know I am close -- but I have having trouble with the syntax here: //:Key="CurrentWebUri"/Value*
The Query above results in this error:

A node or set of nodes is required for /

Can you help?
Adding a result set for reference to further clarify what I am after:
+----+------------------+------------------+------------------+
| ID | CurrentWebUri    | SomethingElse    |  AnotherThing    |
+----+------------------+------------------+------------------+
|  1 | example.org      |        1         |       420        |
+----+------------------+------------------+------------------+
|  2 | example.com      |        6         |       29         |
+----+------------------+------------------+------------------+

A: The default namespace declaration was missing, and XPath expressions were off. And with the latest clarification of the desired output, a dynamic SQL for PIVOTing is needed.

SQL

-- DDL and sample data population, start
USE tempdb;

DROP TABLE IF EXISTS dbo.tbl;

CREATE TABLE dbo.tbl (ID INT IDENTITY PRIMARY KEY, [Configuration] xml);

INSERT INTO dbo.tbl ([Configuration])
VALUES ('<ScopedWorkflowConfiguration xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
                             xmlns="http://schemas.microsoft.com/workflow/2012/xaml/activities">
    <appSettings>
        <AppSetting>
            <Key>CurrentWebUri</Key>
            <Value>http://myurl.org</Value>
        </AppSetting>
        <AppSetting>
            <Key>SomethingElse</Key>
            <Value>1</Value>
        </AppSetting>
        <AppSetting>
            <Key>AnotherThing</Key>
            <Value>420</Value>
        </AppSetting>
    </appSettings>
</ScopedWorkflowConfiguration>');
-- DDL and sample data population, end

DECLARE @columns AS NVARCHAR(MAX),
    @SQL AS NVARCHAR(MAX);

;WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/workflow/2012/xaml/activities')
SELECT TOP(1) @columns = STUFF([Configuration].query('for $s in /ScopedWorkflowConfiguration/appSettings/AppSetting/Key
                           return <x>{concat(",",$s)}</x>')
                   .value('.','varchar(max)'),1,1,'')
FROM dbo.tbl;

SET @SQL =
N';WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/workflow/2012/xaml/activities''), rs AS
(
    SELECT ID
        , c.value(''(Key/text())[1]'', ''NVARCHAR(MAX)'') AS [Key]
        , c.value(''(Value/text())[1]'', ''NVARCHAR(MAX)'') AS [Value]
    FROM dbo.tbl as tbl
        CROSS APPLY tbl.[Configuration].nodes(''/ScopedWorkflowConfiguration/appSettings/AppSetting'') AS t(c)
)
SELECT ID,' + @columns + N' FROM rs
PIVOT (
    MAX([Value])
    FOR [Key] IN (' + @columns + N')
) AS pvt;
';

EXEC sp_executesql @SQL;

Output

+----+------------------+---------------+--------------+
| ID |  CurrentWebUri   | SomethingElse | AnotherThing |
+----+------------------+---------------+--------------+
|  1 | http://myurl.org |             1 |          420 |
+----+------------------+---------------+--------------+


text:
Q: Retrieve serial ID with Npgsql when inserting with ExecuteScalar I'm trying to insert a row into a PostgreSQL table with a serial primary key and I need to retrieve this column after it was inserted. I got something like this:
The table "pais" has 3 columns: id, pais, capital; id is a serial column and is its primary key.
NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital)", conn);
query.Parameters.Add(new NpgsqlParameter("nombre", NpgsqlDbType.Varchar));
query.Parameters.Add(new NpgsqlParameter("capital", NpgsqlDbType.Varchar));
query.Prepare();
query.Parameters[0].Value = this.textBox1.Text;
query.Parameters[1].Value = this.textBox2.Text;
Object res = query.ExecuteScalar();
Console.WriteLine(res);

It inserts the row on the table but "res" value is null. If I insert with the nexval('table_sequence') also returns null.
Any idea of how can I return the id of the table? Am I missing something?
Thanks in advance

A: In order to select the last identity inserted you need to use: currval(sequencename)
so your select statement should look like:
NpgsqlCommand query = new NpgsqlCommand("insert into pais(nombre, capital) values(@nombre, @capital);select currval('table_sequence');", conn);

A: The insert itself does not cause a value to be returned. When you perform ExecuteScalar it is looking for a single value to be "Selected" so to speak.
I believe you need to follow up your insert with a select statement to solve your issue.
If you were using t-sql you would do this like so
string sql =
        "INSERT INTO [Table] (FieldName) VALUES (@ParamName); "
        + "SELECT CAST(scope_identity() AS int)";
ExecuteScalar would then return the unique id;
I am not sure of the exact syntax for postGresql but hopefully this allows you to solve your issue.

A: Is that thread safe?
What if another insert happens between your insert and select?
Why not use:
INSERT INTO table (fieldnames) VALUES (values) RETURNING idcolumn?

A: insert into pais(nombre, capital) values(@nombre, @capital) RETURNING id

replace id with your primary keyenter code here and use
Object res = query.ExecuteScalar();

Inside res you'll have the PK.


text:
Q: remove '$' characters from a string I am trying to remove '$' signs from a string, but I am guessing it is some special char? I am extremely new to lua (just started coding in it today). From my understanding this should work and does for other chars string.gsub(line,'$','').

A: yup, that's a special character for pattern matching. you need to escape it with the % symbol.
local s = 'asdf$erer$iiuq'
print(s:gsub('%$', ''))

> asdfereriiuq  2


text:
Q: $\{g^{-1}(\Omega):\Omega\in\tau_Y\}\in \tau_X$ in topology for continuous functions Let $g: X\rightarrow Y$ be continuous. Let $(X,\tau_X)$ and $(Y,\tau_Y)$ be topological spaces.
Why do we have $\tau=\{g^{-1}(\Omega):\Omega\in\tau_Y\}\subseteq\tau_X$?
My attempt: Let $\Omega\in\tau$. Then $\Omega=g^{-1}(\Omega')$. Since $g$ is continuous we have $\Omega\in\tau$, which seems a little bit too easy for my. Any catches?

A: No catches: the whole inclusion statement is just a fancy way of re-stating that the inverse image of an open set under a continuous map is open.

A: This is because if $\Omega \in \tau$ that means there is some $\tilde{\Omega} \in \tau_Y$ such that $g^{-1}(\tilde{\Omega}) = \Omega$.  By definition though we have that $\tilde{\Omega}$ is open in $Y$, so since $g$ is continuous $g^{-1}(\tilde{\Omega})$ is open $X$, or rather $\Omega = g^{-1}(\tilde{\Omega}) \in \tau_X$.


text:
Q: Using argument (this) passed via element eventhandler I want to use the argument I pass (this) in a JS function and treat it as an jQuery variable.
Example:
<script>
function useMe(obj){
  $(obj).val();
  ...
  ...
  ...
}
</script>

<select id="selectid" onChange="useMe(this)">
    <option>......</option>
</select>

Is there a possibility to treat the passed argument as a jQuery element?
Btw. I need to do it this way, because the select-element isn't created on load. The select element will be created later asynchronously.
So, this won't work:
$("select").each(function (i){
    var select_id = $(this).attr("id");
    $(this).change(function(e){

because it doesn't exist yet.
Thanks for your help.

A: If your element isn't created on load, and loaded asynchronously instead you can bind the change event like this:
$('select').live('change',function(){
  // ...
});

This will bind the defined function to the change event on every existing and on every new select item.
Update: You need at least jQuery 1.4.1 for this

A: If the element doesn't exist at the document load it means that it is later added maybe by an AJAX call. If this is the case just put the change handle registration in the success callback.
$.ajax({
    url: '/somescript',
    success: function() {
        // some code that injects the select into the DOM
        // ...
        $("select").each(function(i) {
            var select_id = $(this).attr("id");
            $(this).change(function(e) {
                // ...
            });
        });
    }
});

A: If you do choose to stick with your onchange attribute (which I would advise against), just use:
<script>
function useMe($obj){
  $obj.val();
  ...
  ...
  ...
}
</script>

<select id="selectid" onChange="useMe($(this))">
    <option>......</option>
</select>


text:
Q: jQuery range slider - get range values on form submission? I have a jQuery UI range slider set up. When the slider controls are moved my code inserts the lower range value into a hidden input, and also the higher range value into a hidden input. These values constantly change as the slider is moving, but there is a problem. If the lower value stops on £60,000 for example, the value inserted into the hidden div will be £40,000. It is always 1 position out of sync. This is my first problem I need to fix. The values are set as #minPrice and #maxPrice in my code.
The second problem occurs on form submission. I need to get the values of the hidden inputs and (on the page load after the form submission) pass them back the to the text input that shows the range for the sliders e.g. 40,000 to 60,000. This input has the ID of #amount in the code.
Here is my code:
// Set increments for sale slider prices
    var increments = ['0', '20,000', '40,000', '60,000', '80,000', '100,000', '120,000', '140,000', '160,000', '180,000', '200,000', '220,000', '240,000', '260,000', '280,000', '300,000', '320,000', '340,000', '360,000', '380,000', '400,000', '420,000', '440,000', '460,000', '480,000', '500,000', '520,000', '540,000', '560,000', '580,000', '600,000', '620,000', '640,000', '660,000', '680,000', '700,000', '720,000', '740,000', '760,000', '780,000', '800,000', '820,000', '840,000', '860,000', '880,000', '900,000', '920,000', '940,000', '960,000', '980,000', '1,000,000', '1,100,000', '1,200,000', '1,300,000', '1,400,000', '1,500,000', '1,600,000', '1,700,000', '1,800,000', '2,000,000']

$('#sliderPriceSale').slider({
    range: true,
    min: 0,
    step: 1,
    max: 59,
    values: [4, 15],
    slide: function (event, ui) {
        $('#amount').val(increments[ui.values[0]] + " to " + increments[ui.values[1]]);

        var minPrice = $("#sliderPriceSale").slider("values", 0);
        $('#minPrice').val(increments[minPrice]);
        var maxPrice = $("#sliderPriceSale").slider("values", 1);
        $('#maxPrice').val(increments[maxPrice]);
    }
});
$('#amount').val(increments[$('#sliderPriceSale').slider("values", 0)] + " to " + increments[$('#sliderPriceSale').slider("values", 1)]);

Any help will be much appreciated.

A: To the first problem, you were using different means to set the #minPrice/#maxPrice and #amount inputs.  I cleaned up the code a making it more readable and storing DOM objects and other important data into variables.  This increases performance and makes the code much easier to debug.  This refactored code always reports the correct values from the slider.
<script type="text/javascript">
$(document).ready(function() {
    // Set increments for sale slider prices
    var increments = ['0', '20,000', '40,000', '60,000', '80,000', '100,000', '120,000', '140,000', '160,000', '180,000', '200,000', '220,000', '240,000', '260,000', '280,000', '300,000', '320,000', '340,000', '360,000', '380,000', '400,000', '420,000', '440,000', '460,000', '480,000', '500,000', '520,000', '540,000', '560,000', '580,000', '600,000', '620,000', '640,000', '660,000', '680,000', '700,000', '720,000', '740,000', '760,000', '780,000', '800,000', '820,000', '840,000', '860,000', '880,000', '900,000', '920,000', '940,000', '960,000', '980,000', '1,000,000', '1,100,000', '1,200,000', '1,300,000', '1,400,000', '1,500,000', '1,600,000', '1,700,000', '1,800,000', '2,000,000'];
    var amount = $('#amount');
    var minPrice = $('#minPrice');
    var maxPrice = $('#maxPrice');
    var slider = $('#sliderPriceSale');
    var initValuesMinIndex = $.inArray(minPrice.val(), increments); // Get index of value in #minPrice
    var initValuesMaxIndex = $.inArray(maxPrice.val(), increments); // Get index of value in #maxPrice
    var minPriceString = '';
    var maxPriceString = '';

    // Setup slider. Initialize #amount on creation.
    slider.slider({
        range: true,
        min: 0,
        max: 59,
        step: 1,
        values: [initValuesMinIndex, initValuesMaxIndex],
        create: function() {
            amount.val(increments[initValuesMinIndex] + " to " + increments[initValuesMaxIndex]);
        },
        slide: function (event, ui) {
            // Get max/min price strings. If max price is == largest value append "+" sign.
            minPriceString = increments[ui.values[0]];
            maxPriceString = (increments[ui.values[1]] == increments[increments.length-1]) ? increments[ui.values[1]] + "+" : increments[ui.values[1]];

            amount.val(minPriceString + " to " + maxPriceString);
            minPrice.val( increments[ui.values[0]] );
            maxPrice.val( increments[ui.values[1]] );
        }
    });
});
</script>

As for the second problem, it's hard to say exactly how you should accomplish that without seeing the rest of your code but in general all you have to do is make sure #maxPrice and #minPrice hidden variables are set to the correct values when the page loads and the slider will automatically display the correct information when it is instantiated because it checks for those values when it is constructed.  For example, if you are using PHP and submitting the form via POST then you might use the following code for those hidden vars:
<!-- Output minPrice & maxPrice values. Default to 80,000 and 300,000 respectively -->
<input type="hidden" id="minPrice" name="minPrice" value="<?php echo (isset($_POST['minPrice'])) ? $_POST['minPrice'] : '80,000'; ?>" />
<input type="hidden" id="maxPrice" name="maxPrice" value="<?php echo (isset($_POST['maxPrice'])) ? $_POST['maxPrice'] : '300,000'; ?>" />


text:
Q: How 99-default.link is interpreted differntly between 20.04 and 22.04 On Ubuntu 20.04 creating a bridge and attaching an interface was giving the bridge the same mac address as the attached interface.
However on Ubuntu 22.04 I started seeing different behavior, the bridge is getting new generated mac and does not inherit the attached interface mac address!
After some investigation thanks to https://bugs.launchpad.net/netplan/+bug/1782221/comments/17 I was able to revert the same behavior by changing macaddresspolicy from persistent to none in /usr/lib/systemd/network/99-default.link
But when I checked  the default config on Ubuntu 20.04 it was also persistent ?!
Is this file interpreted differently on both Ubuntu versions?
I was expecting that Ubuntu 20.04 has the default config macaddresspolicy=none and it is changed in 22.04 to macaddresspolicy=persistent so it makes sense when I change it to none I got the same behavior as 20.04 but in fact they have the same default config why I need to change macaddresspolicy=none to revert the behavior.  Something else must be changed on the newer version not this systemd network default config.


text:
Q: In Celery, only one task runs at the same time? I have a task, I want it to run once every 10 seconds
at the same time, this task can only run one, can't repeat  run this task
I found two ways:
1).http://celery.readthedocs.org/en/latest/tutorials/task-cookbook.html#cookbook-task-serial
2).http://engineroom.trackmaven.com/blog/announcing-celery-once/
I don't know this two way is the best, do you have any good idea ?


text:
Q: javascript word count form validations I have been trying everything to try and solve this myself, but cannot find any solutions on google or my beginner php skills are not up to the task.  So please can someone show me how I can make the form submit ONLY if people have written 15 words or more.  Any suggestions would be very much appreciated.  Below is the css, javascript and html.
#container {
    background: #ededed;
    border: 1px solid #ddd;
    margin: 0 auto;
    padding: 10px;
    position: relative;
    width: 638px;
}

.error { color: #f00; }

ol.forms { list-style: none; overflow: hidden; }
ol.forms li { float: left; margin-bottom: 12px; width: 100%; }
ol.forms label { cursor: pointer; display: block; }
ol.forms textarea {
    border: 1px solid #ddd;
    float: left;
    font: 14px/1.5em Georgia, Times, serif;
    height: 120px;
    margin-right: 5px;
    overflow-y: auto;
    padding: 5px;
    width: 500px;
}
ol.forms textarea:focus { border: 1px solid #000; }
ol.forms div.wordCount { float: left; font-size: 20px; line-height: 30px; }

#quick50 {
    background: #fff;
    border: 1px solid #ddd;
    font-size: 11px;
    left: 5px;
    padding: 5px;
    position: fixed;
    width: 188px;
}

$(document).ready(function() {
    $("[class^='count[']").each(function() {
        var elClass = $(this).attr('class');
        var description = 0;
        var maxWords = 0;
        var countControl = elClass.substring((elClass.indexOf('['))+1, elClass.lastIndexOf(']')).split(',');

        if(countControl.length > 1) {
            description = countControl[0];
            maxWords = countControl[1];
        } else {
            maxWords = countControl[0];
        }

        $(this).after('
0 Words
');
        if(description > 0) {
            $(this).siblings('.wordCount').addClass('error');
        }

        $(this).bind('keyup click blur focus change paste', function() {
            var text = jQuery.trim($(this).val()).replace(/\s+/g," ");
            var numWords = text.split(' ').length;
            if($(this).val() === '') {
                numWords = 0;
            }
            $(this).siblings('.wordCount').children('strong').text(numWords);

            if(numWords < description || (numWords > maxWords && maxWords != 0)) {
                $(this).siblings('.wordCount').addClass('error');
            } else {
                $(this).siblings('.wordCount').removeClass('error');
            }

        });

    });
});

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Word Count</title>
<link href="wordcount.css" type="text/css" rel="stylesheet" media="screen,projection" />

jQuery Word Count

50 words for quick copying

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam leo orci, porta eget, tincidunt sit amet, sagittis id, turpis. Aenean sed metus at leo ullamcorper dapibus. Duis vitae risus dignissim lectus dapibus faucibus! In porttitor, ante non adipiscing ultricies, magna velit blandit dui, a tempus ligula dolor eu orci? Sed.

        <form action="submitcontent.php" method="post">

Min Word Textarea (15 words or more)
            <textarea onkeyup="limitWords(this,5);" name="minWord" class="count[15,0]" id="minWord"></textarea>

        <input type="submit" value="Submit Content"  onclick="return doSubmit()" />
        </form>

A: Off the top of my head, something like this?
<textarea id="some-textarea" onkeypress="activateSubmit();">
</textarea>
<input type="submit" value="Submit" id="submit-button" disabled="disabled">

And correspondingly somewhere:

A: this is an example with a regular expression:
$('form#count').submit(function(){
    // if we accept that words are only made of letters
    if ($(this).find('textarea').val().match(/[a-z]+/gi).length < 15) {
        // add some error message
        return false; // prevents submitting
    }
});


text:
Q: Soft KeyBoard does not show up in Landscape orientation In my app, I have a dialog with EditText. I have coded it in such a way that as soon as the dialog shows up,the soft keyboard shows up, the edit text will get focus , all the existing text in the editText is preselected. And user can start typing. This all works fine when I am holding my phone in portrait orientation. But the same thing does not work when I have phone in landscape orientation. Part of my code in my fragment is pasted below.
final EditText inputDeviceId = new EditText(getActivity());
inputDeviceId.setInputType(InputType.TYPE_CLASS_TEXT);
String savedDevId = getDeviceID();
inputDeviceId.setText(savedDevId);
inputDeviceId.setSelectAllOnFocus(true);

// some more code ... to create dialog , ok cancel buttons then,
final AlertDialog alertDialog = alertDialogBuilder.create();
inputDeviceId.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    if(hasFocus){
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                }
});

alertDialog.show();

Now this all works in portrait orientation and does not work in landscape.
In landscape mode the dialog with edittext shows up , it has focus and existing text  is preselected but it does not show the keyboard. User has to click in the editText for keyboard to come up. Why? I am using nexus-5 to test.


text:
Q: Ctrl+S (horizontal split) not working with Command-T in vim I can't get the horizontal split to work. Ctrl+enter does nothing, Ctrl+S does nothing.
I've been googeling this for a bit and the only solutions I've found so far are related to OSX.
On both Arch Linux and Ubuntu, having same problem (but also the same config).
I'm not using Janus or anything like it, just a very basic config
set t_Co=256
set tabstop=2
set expandtab
set shiftwidth=2
set fileencoding=utf-8
set encoding=utf-8
set termencoding=utf-8
set showcmd
filetype plugin indent on
"color molokai
syntax enable
autocmd! BufNewFile * silent! 0r ~/.vim/skel/tmpl.%:e
set laststatus=2 " Always show the statusline

set backspace=indent,eol,start  " backspace through everything in insert mode

"" Searching
set hlsearch                    " highlight matches
set incsearch                   " incremental searching
set ignorecase                  " searches are case insensitive...
set smartcase                   " ... unless they contain at least one capital letter

call pathogen#infect()
colorscheme jellybeans
" use comma as <Leader> key instead of backslash
let mapleader=","

" Double <Leader> to switch between buffers
nnoremap <leader><leader> <c-^>
" double percentage sign in command mode is expanded
" to directory of current file - http://vimcasts.org/e/14
cnoremap %% <C-R>=expand('%:h').'/'<cr>

map <leader>f :CommandTFlush<cr>\|:CommandT<cr>
map <leader>F :CommandTFlush<cr>\|:CommandT %%<cr>

[~]$ ls .vim/bundle
rbenv:system
command-t  jellybeans.vim  snipmate-snippets  tlib_vim  vim-addon-mw-utils  vim-powerline  vim-snipmate

I was hoping someone would be able to shed some light on this, it's getting really frustrating.
Not entirely sure whats wrong but it have work occasionally, but not at all right now.
Pressing CTRL+S does nothing, shift+enter just opens it normally in the current buffer and ctrl+enter just hops down the search results list in Command-T.

A: In most terminals, Vim cannot distinguish between Enter and its combinations with Ctrl or Shift, unfortunately; these only work in GVIM.
The terminal's flow control commands may interfere with Ctrl-S and Ctrl-Q; this can be fixed (in the terminal, not in Vim!) with
stty start undef stop undef

in ~/.bashrc, ~/.zshrc, etc.


text:
Q: Gmail doesn't display some of embedded images I'm creating a service which sends emails with a lot of embedded images. And often these images are being randomly lost in  gmail web client using Chrome and other browsers (see the attached screenshot). I'm sure that the images are send correctly. The images are attached to email and the missed images could be successfully downloaded using Chrome context menu. If I press ctrl+F5 the images will be shown (or other images disapear). Also these emails are being displayed fine in Thunderbird or MS Outlook.
Here is a screnshot from my Chrome:

Please advice how I could change email body (maybe add some headers etc.) to woraround this issue!
Usage of external images (like ) is not preferable. Only embedded images like
The emails are being sent through Amazon Web Services mail sender.
Also I'm using javamail to send the images.
Here is a sample email text:
Return-Path: <0000014117bed1a2-aad7fbff-afdd-43ea-a658-825a817e9903-000000@amazonses.com>
Received: from a8-83.smtp-out.amazonses.com (a8-83.smtp-out.amazonses.com. [54.240.8.83])
        by mx.google.com with ESMTP id nd18si8517742qeb.113.1969.12.31.16.00.00;
        Fri, 13 Sep 2013 08:36:38 -0700 (PDT)
Received-SPF: pass (google.com: domain of 0000014117bed1a2-aad7fbff-afdd-43ea-a658-825a817e9903-000000@amazonses.com designates 54.240.8.83 as permitted sender) client-ip=54.240.8.83;
Authentication-Results: mx.google.com;
       spf=pass (google.com: domain of 0000014117bed1a2-aad7fbff-afdd-43ea-a658-825a817e9903-000000@amazonses.com designates 54.240.8.83 as permitted sender) smtp.mail=0000014117bed1a2-aad7fbff-afdd-43ea-a658-825a817e9903-000000@amazonses.com
Return-Path: 0000014117bed1a2-aad7fbff-afdd-43ea-a658-825a817e9903-000000@amazonses.com
From: <my service email here>
Sender: <my service email here>
To: <my receiver email here>
Message-ID: <0000014117bed1a2-aad7fbff-afdd-43ea-a658-825a817e9903-000000@email.amazonses.com>
Subject: =?UTF-8?Q?RedHelper_-_=D0=BF?=
 =?UTF-8?Q?=D0=BB=D0=B0=D0=BD=D0=BE=D0=B2=D1=8B=D0=B9?=
 =?UTF-8?Q?_=D0=BE=D1=82=D1=87=D1=91=D1=82_?=
 =?UTF-8?Q?(c_06.09.2013_=D0=BF=D0=BE_12.09.2013)?=
MIME-Version: 1.0
Content-Type: multipart/related;
    boundary="----=_Part_0_68348157.1379082638282"
Date: Fri, 13 Sep 2013 14:34:43 +0000
X-SES-Outgoing: 2013.09.13-54.240.8.83

------=_Part_0_68348157.1379082638282
Content-Type: text/html;charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

=09

=09=09
=09=09=09

...........................
The rest of email body
...........................

------=_Part_0_68348157.1379082638282
Content-Type: image/png; name=client_report_header.png
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename=client_report_header.png
Content-ID: <client_report_header.png>
X-Attachment-Id: client_report_header.png

...........................
base64 encoded image
...........................
...........................
then a lot of other images
...........................

Please help me to solve this problem, I'am at an impasse with it :(
Update:
I've explored the requests that browser makes for the embedded images and found that gmail attachment service sometimes returns wrong response headers (e.g. with text/html type insted of image/png) and then the images are not being displayed.
Here is an example of "good" response headers (copied from Chrome developer tools):
Request URL:https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=da16498049&view=att&th=141543ec8afd95ce&attid=0.49&disp=emb&zw&atsh=1&saduie=AG9B_P_B99tk3pnLfQHlDF_gPQKM&sadet=1380097953720&sads=D0OzbnmhqzBZ6htOe0o3RTWuwvw
Request Method:GET
Status Code:200 OK

Request Headers
:host:mail-attachment.googleusercontent.com
:method:GET
:path:/attachment/u/0/?ui=2&ik=da16498049&view=att&th=141543ec8afd95ce&attid=0.49&disp=emb&zw&atsh=1&saduie=AG9B_P_B99tk3pnLfQHlDF_gPQKM&sadet=1380097953720&sads=D0OzbnmhqzBZ6htOe0o3RTWuwvw
:scheme:https
:version:HTTP/1.1
accept:image/webp,*/*;q=0.8
accept-encoding:gzip,deflate,sdch
accept-language:en-US,en;q=0.8,ru;q=0.6
cookie:S=gmail=QQ8uQOaAEhQ4x5TFVYcQhg
referer:https://mail.google.com/mail/u/0/
user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
x-chrome-variations:CK61yQEIhrbJAQiqtskBCMS2yQEIt4XKAQjxhsoB

Response Headers
access-control-allow-credentials:true
alternate-protocol:443:quic
cache-control:private, max-age=86400
content-disposition:attachment; filename="visitors_capture_pic.png"
content-length:4336
content-type:image/png
date:Wed, 25 Sep 2013 08:32:14 GMT
server:GSE
status:200 OK
version:HTTP/1.1
x-content-type-options:nosniff
x-xss-protection:0

And here is an example of "bad" response headers:
Request URL:https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=da16498049&view=att&th=141543ec8afd95ce&attid=0.5&disp=emb&zw&atsh=1&saduie=AG9B_P_B99tk3pnLfQHlDF_gPQKM&sadet=1380097948083&sads=37LZqateabeXb45jYSk9ooGybwI
Request Method:GET
Status Code:200 OK

Request Headers
:host:mail-attachment.googleusercontent.com
:method:GET
:path:/attachment/u/0/?ui=2&ik=da16498049&view=att&th=141543ec8afd95ce&attid=0.5&disp=emb&zw&atsh=1&saduie=AG9B_P_B99tk3pnLfQHlDF_gPQKM&sadet=1380097948083&sads=37LZqateabeXb45jYSk9ooGybwI
:scheme:https
:version:HTTP/1.1
accept:image/webp,*/*;q=0.8
accept-encoding:gzip,deflate,sdch
accept-language:en-US,en;q=0.8,ru;q=0.6
cookie:S=gmail=QQ8uQOaAEhQ4x5TFVYcQhg
referer:https://mail.google.com/mail/u/0/
user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
x-chrome-variations:CK61yQEIhrbJAQiqtskBCMS2yQEIt4XKAQjxhsoB

Response Headers
alternate-protocol:443:quic
cache-control:no-cache, no-store, max-age=0, must-revalidate
content-encoding:gzip
content-type:text/html; charset=UTF-8
date:Wed, 25 Sep 2013 08:32:09 GMT
expires:Fri, 01 Jan 1990 00:00:00 GMT
pragma:no-cache
server:GSE
status:200 OK
version:HTTP/1.1
x-content-type-options:nosniff
x-frame-options:SAMEORIGIN
x-xss-protection:1; mode=block

Then if I try to download a missing image in a separate browser page it gives me 3 "302 Moved Temporarily" requests and finally a "200 OK" which gives the image.


text:
Q: Error al realizar borrado de Foreign Keys con LINQ + Entity Framework en una aplicación sencilla de CRUD en donde tenemos un listado de videojuegos, he intantado borrar algunos de sus registros. La base de datos al contener Foreign Keys no me permite realizarlo sin antes eliminar todos los registros asociados a ese videojuego como por ejemplo, las puntuaciones o la plataforma a la que pertenece.
Lo he intendo mediante consultas linq de las siguientes formas:
var deleteFK = from JuegoPlataforma in context.JuegoPlataformas
                       where JuegoPlataforma.IdJuego == id
                       select (JuegoPlataforma.IdJuego);

        context.JuegoPlataformas.Remove(deleteFK);

context.JuegoPlataformas.Remove(context.JuegoPlataformas.Where(x => x.IdJuego == id));

Pero de las dos me reporta el siguiente error:

Ajunto además el modelo JuegoPlataformas que además hace referencia a JuegoPlataformas, simplemente se ha modificado el nombre para una mayor legibilidad del código:
namespace Videojuegos_MartinN.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

public partial class JuegoPlataforma
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public JuegoPlataforma()
    {
        this.Puntuacion = new HashSet<Puntuacion>();
    }

    [Key]
    public int Id { get; set; }
    public Nullable<int> IdJuego { get; set; }
    public Nullable<int> IdPlataforma { get; set; }
    public Nullable<int> IdDistribuidor { get; set; }
    public Nullable<int> IdDesarrollador { get; set; }
    [ForeignKey("IdDesarrollador")]
    public virtual Desarrollador Desarrollador { get; set; }
    [ForeignKey("IdDistribuidor")]
    public virtual Distribuidor Distribuidor { get; set; }
    [ForeignKey("IdJuego")]
    public virtual Juego Juego { get; set; }
    [ForeignKey("IdPlataforma")]
    public virtual Plataforma Plataforma { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    [ForeignKey("Id")]
    public virtual ICollection<Puntuacion> Puntuacion { get; set; }
}

}
Por ahora no se me ha ocurrido hacerlo de otras formas, ya que no puedo realizar un borrado en cascada.
En el proyecto, se hace uso además de Entity Framework.
Cualquier documentación o comentario sería de gran ayuda. Si se necesita alguna información adicional, la ofreceré lo antes posible. Gracias de antemano.

A: Tu problema es que estas intentando borrar un conjunto de registros de una sola vez, y debes hacerlo de uno en uno.
El código sería así:
foreach (var _elemento in context.JuegoPlataformas.Where(x => x.IdJuego == id))
{
   context.JuegoPlataformas.Remove(_elemento);
}
context.SaveChanges();

También podrías eliminarlos de una sola vez (solo para EF 6.0 o superior) de la siguiente manera:
var _elementos = context.JuegoPlataformas.Where(x => x.IdJuego == id);
context.JuegoPlataformas.RemoveRange(_elementos);
context.SaveChanges();


text:
Q: how to get value hidden in C# when it is set by jquery after postback i am nwe to jquery.how i get value of hidden field after post back in csharp. when ever post back occures value dissapear.
this is my hidden field.
<asp:HiddenField ID="Hid_BasicSalary" runat="server" />

this is jquery code where is assign data to it after succsesful execution of ajax web service.
var BasicSalary = $('Hid_BasicSalary');
 BasicSalary.val(data["BasicSalary"]);

this is c sharp code when i click on button postback occurs afte this node data.
protected void Btn_PIncrementSave_Click(object sender, EventArgs e)
    {
        try
        {
            TxBx_IncrementAmount.Text = Hid_BasicSalary.Value.ToString();

        }
        catch (Exception ex)
        {

            Utility.Msg_Error(this.Master, ex.Message);
        }
    }

please help me

A: In jQuery we use the selector for select any elements, and we have to put . for the class and # to the id selector so please put # or . before your element.
In your case, $('#Hid_BasicSalary'); or $('.Hid_BasicSalary'); is your answer.

A: i was missing # with $.
var BasicSalary = $('Hid_BasicSalary');

i write this instead of this
 var BasicSalary = $('#Hid_BasicSalary');

A: Try this
var BasicSalary = $('#Hid_BasicSalary');

A: Use  This code is page load to get new value from hidden
Request.Form["hdnvalue"];

A: you missed the "#" and i think that you should use the hidden control's clientid.
var BasicSalary = $('#<%=Hid_BasicSalary.ClientID%>');

A: try this to get value of server control from javascript/jquery
var BasicSalary = document.getElementById('<%=Hid_BasicSalary.ClientID%>').value


text:
Q: sql query only displays rows that have a match in the join IN this SQL, it is only returning rows that had data in the col from the join table
(subst_Instructions). But we want it to display the row from main table even if there is not data in the join. Now, its' because of the where SUBST_INSTRUCTIONS is not null presumably.
but without that, it will not show the data from that column. is there a way to say where SUBST_INSTRUCTIONS is not null and null?
SELECT * FROM
(
     SELECT ID_KEY, [BATCH] AS column1, [IMPORTDATE], [DATEBILLED], [RX],
     [DATEDISPENSED], [DAYSUPPLY], [PAYTYPE], [NPI],
     [PHYSICIAN], [COST], [QUANTITY], [MEDICATION], A.[NDC], [PATIENTNAME],
     [ROUTEOFADMIN], [INVOICECAT], [COPAY], [BRAND], [TIER], [SKILLLEVEL],
     [STAT] STATUS, [LASTTASKDATE],SEQNO,B.[SUBST_INSTRUCTIONS],
     ROW_NUMBER() OVER(PARTITION BY ID_KEY ORDER BY ID_KEY) rn
   FROM [PBM].[T_CHARGES] A
     LEFT OUTER JOIN [OGEN].[NDC_M_FORMULARY] B
       ON A.[NDC] = B.[NDC]
   WHERE [STAT] NOT IN (3, 4)
     AND [TIER] <> 'T1'
 ) a
 WHERE SUBST_INSTRUCTIONS IS NOT NULL -- rn = 1

A: I would use full outer join instead of left outer join.

A: Make sure not to have any fields of the outer joined table in the WHERE clause. Do [STAT] and [TIER] both belong to the main table? If they belong to the outer joined table, then put the criteria in the ON clause, not in the WHERE clause.

A: You are right - applying the WHERE SUBSR_INSTRUCTIONS IS NOT NULL to the outer query means it will only return rows where there is a row in the right side of the join, as it is a column from the right side of the join.
Its easy enough to solve this though by moving this condition into the join criteria instead.
However if your database engine doesnt support multiple join conditions you should join onto a subquery instead as shown below
We also have no need of an outer query. Here is the altered query:
SELECT ID_KEY, [BATCH] AS column1, [IMPORTDATE], [DATEBILLED], [RX],
     [DATEDISPENSED], [DAYSUPPLY], [PAYTYPE], [NPI],
     [PHYSICIAN], [COST], [QUANTITY], [MEDICATION], A.[NDC], [PATIENTNAME],
     [ROUTEOFADMIN], [INVOICECAT], [COPAY], [BRAND], [TIER], [SKILLLEVEL],
     [STAT] STATUS, [LASTTASKDATE],SEQNO,B.[SUBST_INSTRUCTIONS],
     ROW_NUMBER() OVER(PARTITION BY ID_KEY ORDER BY ID_KEY) rn
   FROM [PBM].[T_CHARGES] A
     LEFT OUTER JOIN
     (
       SELECT * FROM [OGEN].[NDC_M_FORMULARY]
       WHERE [SUBST_INSRUCTIONS] IS NOT NULL  --  <--- Note now only applies to
                                                --       right hand side.
     ) B
     ON A.[NDC] = B.[NDC]
   WHERE [STAT] NOT IN (3, 4)
     AND [TIER] <> 'T1'


text:
Q: Duplicate code detection: Tools you can use I am looking out for a software that identifies duplicate/redundant Javascript code. I found one such tool named CloneDR, but don't know how good it is .
I was looking out for similar open source tools . Please guide .

A: I used PMD's Copy/Paste Detector (CPD) last year on a project.  There was some code for EcmascriptLanguage support but I recall having to update GUI.java and recompile the project to get it to work.

A: If you use ruby (or even have it on your system) you may want to try flay-js (flay plugin)

A: It may be worth checking out the coverage section in Google Chrome, relatively new feature:
https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage

Find unused CSS and JS code with the new Coverage tab. When you load or run a page, the tab tells you how much code was used, versus how much was loaded. You can reduce the size of your pages by only shipping the code that you need.


text:
Q: Adding non-button control to TinyMCE editor 4.x I'm using the TinyMCE editor (version 4.0.1). I've been trying to add a checkbox to the editor toolbar but can't figure out how to do it.
For normal buttons, I've used the addButton function. But I'm stuck on how to add other TinyMCE UI types such as a checkbox to the toolbar.
The documentation for the addButton function says it:

Adds a button that later gets created by the ControlManager. This is a shorter and easier method of adding buttons without the need to deal with the ControlManager directly. But it's also less powerfull if you need more control use the ControlManagers factory methods instead.

I tried to the ControlManager class, but it seems only appear in the TinyMCE 3.x API.
One solution would be to use the UI Factory create method and render the UI item directly to the HTML of the TinyMCE editor, but this seems a little clumsy:
tinyMCE.ui.Factory.create({
  type: 'checkbox',
  checked: true,
  text: 'My checkbox'
}).renderTo($('#mce_92-body')[0]);

Can anyone think of a better approach?
See http://www.tinymce.com/wiki.php/api4:class.tinymce.ui.Checkbox
and http://www.tinymce.com/wiki.php/api4:method.tinymce.Editor.addButton

A: Inside your tinymce init method:
setup : function(ed) {
                    ed.addButton('check', {
                        type:'checkbox',
                        text: 'some descriptive label',
                    });
                },


text:
Q: definition of countably generated Borel space I have one source
http://www.ams.org/journals/tran/1957-085-01/S0002-9947-1957-0089999-2/S0002-9947-1957-0089999-2.pdf
page 137, first paragraph of section 2
which says a countably generated Borel space is a Borel space with a countable generating family, which is also separated. I don't know if that is supposed to mean that the countable generating family is also a separating family. On the other hand I have another source
http://www.math.missouri.edu/~jan/thesis/3meas
page 39
which does not have the additional requirement "which is also separated", but then goes on to say that it is clear that a countably generated Borel space is also countably separated. I do not know why this would be clear if we are not making any assumption that the countable generating family is also a separating family. I was wondering if I could find out what the correct definition is?

A: A $\sigma$-algebra is said to be countably generated if it is generated by a countable subset (v.g., the Borel sets of Euclidean $n$-space are generated by the open $n$-parallelepipeds with rational vertices). By extension, we may say that a measurable space is countably generated if its $\sigma$-algebra is.
This is independent of the concept separated. Nowadays it seems that the more explanatory phrase "separates points" is in use.
For instance, you have the following statement:

Let $\mathbf{S}=\langle S,\Sigma\rangle$ be a measurable space. $\mathbf{S}$ is the Borel space of a separable metrizable space iff $\Sigma$ is countably generated and separates points (in $S$).

The trivial $\sigma$-algebra $\{\emptyset, S\}$ on any set $S$ with more than two elements is countably generated but (obviously) does not separates points.


text:
Q: System call error while calling a function I am calling a function as below:
write_phy 1 0 0x100

While the function write_phy is:
proc write_phy {phy register value} {
  if { [regexp {^0} $value] } {
        scan $value "%o" value
     }

  if {$::DEBUG} {
       puts [format "Write PHY %s register %s = 0x%0.8X" $phy $register $value]
    }
 # exec ./write_phy.pl $phy $register $value
}

after 1;

While executing the function I am getting a system call error though the print statement works properly:
Write PHY 1 register 0 = 0x00000000

Disallowed system call: SYS__newselect

Other functions in the code are working good.
Please help.

A: If I let the code run on Tcl 8.6 (Raspbian), it tells me that it expected an integer but got "256". What Version of Tcl and what OS are you using? Are you running a Batteries-included Tcl (like Etcl) or some other distro?
P.S. The "after 1" in the global context just pauses one millisecond when loading the script into the interpreter. It has nothing to do with the error itself. I think you can remove it.


text:
Q: What might be preventing Unicode characters from displaying? When I insert the reference mark character and compile the following MWE, the character shows up in the compiled output:
\documentclass{article}
\usepackage{fontspec}
\begin{document}

྿

\end{document}

But when I use the same character in my longer (memoir-based) document, it does not show up in the compiled PDF. There's just a blank space. However, the log shows no error; so, as a non-expert, it's tough for me to know where to start in debugging this.
Extra Details
In the character table for the font that I am, ideally, trying to get this to work with (Sabon Next), I can see the character, and it has the following notation:
UTF-8: 0xE2 0x80 0xBB
UTF-16: 0x203B
C octal escaped UTF-8: \342\200\273
XML decimal entity: ※

The character is in the "General Punctuation" Unicode block. The same mark, with the same notation, in the same block, shows up in the character maps for Minion, Palatino, and other fonts. I have consulted the fontspec manual but have not found any guidance beyond the possibility that I may need to specify a distinct script to address this Unicode block (but, as far as I can see, there is no script for "General Punctuation" in the fontspec manual).
Possibly relevant portions of my preamble
\RequirePackage{luatex85}
\documentclass[draft,twoside,a5paper,10pt]{memoir}
\usepackage{fontspec}
\defaultfontfeatures{Ligatures=TeX,Numbers=OldStyle}
\setmainfont{Sabon Next LT Pro}[Numbers=OldStyle]
\setromanfont[Ligatures=TeX]{Sabon Next LT Pro}
\setsansfont[Ligatures=TeX]{Syntax LT Std}
\usepackage[USenglish]{babel}
\usepackage{layout}
\usepackage{hyperref}
\usepackage[cmyk]{xcolor}
\usepackage{hyperxmp}
\usepackage[final]{microtype}
\usepackage{epigraph}
\usepackage{ragged2e}
\usepackage{wasysym}
\usepackage{ellipsis}
\usepackage{graphicx}
\usepackage[export]{adjustbox}
\usepackage{lettrine}
\isopage
\checkandfixthelayout

What (probably very basic) thing am I missing here?


text:
Q: Why would initializing an ARMA process in a deterministic way, prevent it from being stationary? Let's assume that we have process $X_t$ that follows $\phi(B)X_t=\theta(B)Z_t$, where $Z_t$ is a white noise process, and $\deg(\phi)=p$, $\deg(\theta)=q$.
Assuming that $\phi$ has no unit roots, we can state that $X_t=\frac{\theta(B)}{\phi(B)}Z_t$ is the unique stationary solution to the above equation.
However, if we don't restrict ourselves to stationarity, then we can find infinite solutions, depending on how we initialize the first $p$ values of $X_t$, in a deterministic way. This is precisely what I don't get, in an intuitive way ...

A: There is an answer to a similar question here discussing the relationship between stationarity and the recursive equation for a model.  Some additional remarks are pertinent to your case.
Firstly, it is important to understand that the recursive equation defining the ARMA($p,q$) process is not sufficient to fully specify the process, even with specification of the distribution of the underlying noise series $\boldsymbol{Z} = \{ Z_t| t \in \mathbb{Z} \}$.  The recursive equations lock in the auto-correlation of the process, and specification of the distribution of the underlying noise series $\boldsymbol{Z}$ is then sufficient to give an asymptotic marginal distribution for the observable values.  However, the full joint distribution for the observable series $\boldsymbol{X} = \{ X_t| t \in \mathbb{Z} \}$ also depends on the distribution of the "starting values".  In some cases this is specifically defined, and in cases where it is not, it is usual to take this to mean that you are using the unique stationary distribution.
ARMA($p,q$) model with white noise: You have specified an underlying white noise series so you have distribution $Z_t \sim \text{IID N}(0, \sigma^2)$ for the underlying series.  Assuming that $\max| \phi_i | <1$ you have asymptotic stationarity with limiting distribution:
$$X_\infty \sim \text{N} \Bigg( 0, \sigma^2 \sum_{i=0}^\infty \psi_i^2 \Bigg) \text{ } \text{ } \text{ } \text{ } \text{ } \text{ } \text{ } \text{ } \text{ } \psi(B) \equiv \frac{\phi(B)}{\theta(B)}.$$
To get an ARMA process with strict stationarity, you would set $X_1, \cdots , X_p$ to have a joint normal distribution with zero mean, the above variance, and auto-correlation that is consistent with your specified ARMA model.  This would give you strict stationarity, in the sense that the joint distribution of observable values does not change when shifted in time.
If you were to use a different joint distribution for your "starting values", this would lead to a non-stationary model.  It would still be asymptotically stationary with the above limiting distribution, but the condition of strict stationarity would not hold.
Intuitive explanation: The recursive formula for an ARMA model specifies the relationship that each observable value has with previous values.  There is an infinite class of possible models that are consistent with this recursive specification (each represented by a full joint distribution for which that recursive equation holds).  For a model with auto-regressive coefficients inside the unit circle, there is a unique strictly stationary model in this class, but there are also an infinite number of other models that are non-stationary, but still have an asymptotic limiting distribution.  The basic thing to remember for the intuitive explanation is that the ARMA equation, which is merely a recursive equation does not fully specify the model.


text:
Q: Setting the creation date of each file in a folder to mach its own "last modifictaion" date automatically, using CMD, software or similar I got a folder of about 1000 pictures and videos. The creation date of the files is incorrect, but the "last modified" time stamp is correct. I want to set the creation date of each of the files in the folder to mach its own "last modifictaion" date, automatically using CMD or any program that is capable of this.

A: Windows 10 64-bit. PowerShell 5
How to replace creation time with last modified time using PowerShell.
If you do not see the updated Properties-Details in your files close the Properties-Details window, hit F5 and re-open the Properties-Details window.
To do all files in folder:
Get-ChildItem * | ForEach-Object{$_.CreationTime = $_.LastWriteTime}

Files by extension:
Get-ChildItem *.jpg, *.mkv | ForEach-Object{$_.CreationTime = $_.LastWriteTime}

To run the command in CMD:
powershell -NoLogo -NoProfile -Command "Get-ChildItem * | ForEach-Object{$_.CreationTime = $_.LastWriteTime}"

How to replace CreationTime with LastWriteTime for all files by extension in a folder using PowerShell 5 and a wildcard.
How to replace CreationTime with LastwriteTime using PowerShell 5 and a wildcard.