text:
Q: Invoking Regex.IsMatch() inside a dynamic linq query I'm trying to invoke the Regex.IsMatch() and evaluate the returned result inside a dynamic linq query. This is what I tried:
public static LambdaExpression Parse(SearchQuery query)
{
    string compilableExpression = "Regex.IsMatch(Category.ToLower(), \"\\bSomeCat\\b\", RegexOptions.Compiled) == true";

    ParameterExpression parameter1 = System.Linq.Expressions.Expression.Parameter(typeof(EventListItem));
    ParameterExpression parameter2 = System.Linq.Expressions.Expression.Parameter(typeof(Regex));

    return System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { parameter1, parameter2 }, null, compilableExpression);
}

In this case Category is a property in the EventListItem. This exception is thrown upon calling ParseLambda():
Unknown identifier 'Regex'.
Is there a way to invoke the method? I came across Expression.Call() method, but I'm not sure if that's what I'm looking for. Any help is appreciated.

A: I haven't used System.Linq.Dynamic a lot, but here is a way to make your example work:
1 - You really only have one input object, your EventListItem, so remove parameter2 (Regex):
string compilableExpression = "Regex.IsMatch(Category.ToLower(), \"\\bSomeCat\\b\", RegexOptions.Compiled) == true";
ParameterExpression parameter1 = System.Linq.Expressions.Expression.Parameter(typeof(EventListItem));
return System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { parameter1 }, null, compilableExpression);

2 - DynamicExpression.ParseLambda() is made to read properties and methods from the input object. Using methods on other classes (here: Regex.IsMatch() is limited to a small set of predefined classes, and by default Regex isn't one of them.
Therefore, we somehow need to make the parser realize that "Regex" is a class and not a property on EventListItem. Assuming you have included the DynamicLinq.cs file in your project, this can be done by adding Regex (and RegexOptions) to the internal ExpressionParser.predefinedTypes array:
static readonly Type[] predefinedTypes = {
    typeof(Object),
    typeof(Boolean),
    ...

    typeof(System.Text.RegularExpressions.Regex),
    typeof(System.Text.RegularExpressions.RegexOptions),
};

EDIT: Complex parameter values
If we need to include more complex parameters in our method calls, e.g. a combined RegexOptions enum; RegexOptions.Compiled | RegexOptions.IgnoreCase, ParseLambda also accepts a list of values.
We prepare the combined enum beforehand, and submit it in that values list. In compilableExpression we include placeholders for the values we submit, indexed in the same order we submit them (here we only have one value - index 0)
var options = RegexOptions.Compiled | RegexOptions.IgnoreCase;
string compilableExpression = "Regex.IsMatch(Category.ToLower(), \"\\bSomeCat\\b\", @0) == true";
ParameterExpression parameter1 = SLE.Expression.Parameter(typeof(EventListItem));
return SLD.DynamicExpression.ParseLambda(new[] { parameter1 },
                                         null,
                                         compilableExpression,
                                         options);

Bonus: Because the RegexOptions class/enum is no longer directly referenced in compilableExpression, we also no longer need to include RegexOptions in ExpressionParser.predefinedTypes.


text:
Q: Supersized jQuery functionality I have been working on customization of the Supersized jQuery plugin, its working absolutely fine. I have added  images in its slide functionality as an array with title. Now I want to make slow zoom in functionality in the images defined in slides.
Here's my current code:
jQuery(function($){
            $.supersized({
                // Functionality
                slideshow               :   1,          // Slideshow on/off
                autoplay                :   1,          // Slideshow starts playing automatically
                start_slide             :   1,          // Start slide (0 is random)
                stop_loop               :   0,          // Pauses slideshow on last slide
                random                  :   0,          // Randomize slide order (Ignores start slide)
                slide_interval          :   5000,       // Length between transitions
                transition              :   2,          // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,        // Speed of transition
                new_window              :   1,          // Image links open in new window/tab
                pause_hover             :   0,          // Pause slideshow on hover
                keyboard_nav            :   1,          // Keyboard navigation on/off
                performance             :   3,          // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,          // Disables image dragging and right click with Javascript

                // Size & Position
                min_width               :   0,          // Min width allowed (in pixels)
                min_height              :   0,          // Min height allowed (in pixels)
                vertical_center         :   1,          // Vertically center background
                horizontal_center       :   1,          // Horizontally center background
                fit_always              :   0,          // Image will never exceed browser width or height (Ignores min. dimensions)
                fit_portrait            :   1,          // Portrait images will not exceed browser height
                fit_landscape           :   0,          // Landscape images will not exceed browser width

                // Components
                slide_links             :   'blank',    // Individual links for each slide (Options: false, 'num', 'name', 'blank')
                thumb_links             :   1,          // Individual thumb links for each slide
                thumbnail_navigation    :   1,          // Thumbnail navigation
                slides                  :   [           // Slideshow Images
                                                {image : 'images/background-slideshow/1.jpg', title : '

Test 1 title

},
                                                {image : 'images/background-slideshow/2.jpg', title : '

Integer turpis
</div},
                                                {image : 'images/background-slideshow/3.jpg', title : '

Test 3 title

},
                                                {image : 'images/background-slideshow/4.jpg', title : '

Test title 4

},
                                                {image : 'images/background-slideshow/5.jpg', title : '

Test title 5

}
                                            ],

                    // Theme Options
                    progress_bar            :   0,          // Timer for each slide
                    mouse_scrub             :   0

        });
        });

A: jQuery(function($){
            $.supersized({
                // Functionality
                slideshow               :   1,          // Slideshow on/off
                autoplay                :   1,          // Slideshow starts playing automatically
                start_slide             :   1,          // Start slide (0 is random)
                stop_loop               :   0,          // Pauses slideshow on last slide
                random                  :   0,          // Randomize slide order (Ignores start slide)
                slide_interval          :   5000,       // Length between transitions
                transition              :   2,          // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,        // Speed of transition
                new_window              :   1,          // Image links open in new window/tab
                pause_hover             :   0,          // Pause slideshow on hover
                keyboard_nav            :   1,          // Keyboard navigation on/off
                performance             :   3,          // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,          // Disables image dragging and right click with Javascript

                // Size & Position
                min_width               :   0,          // Min width allowed (in pixels)
                min_height              :   0,          // Min height allowed (in pixels)
                vertical_center         :   1,          // Vertically center background
                horizontal_center       :   1,          // Horizontally center background
                fit_always              :   0,          // Image will never exceed browser width or height (Ignores min. dimensions)
                fit_portrait            :   1,          // Portrait images will not exceed browser height
                fit_landscape           :   0,          // Landscape images will not exceed browser width

                // Components
                slide_links             :   'blank',    // Individual links for each slide (Options: false, 'num', 'name', 'blank')
                thumb_links             :   1,          // Individual thumb links for each slide
                thumbnail_navigation    :   1,          // Thumbnail navigation
                slides                  :   [           // Slideshow Images
                                                {image : 'images/background-slideshow/1.jpg', title : '

Test 1 title

'},
                                                {image : 'images/background-slideshow/2.jpg', title : '

Integer turpis
</div'},
                                                {image : 'images/background-slideshow/3.jpg', title : '

Test 3 title

'},
                                                {image : 'images/background-slideshow/4.jpg', title : '

Test title 4

'},
                                                {image : 'images/background-slideshow/5.jpg', title : '

Test title 5

'}
                                            ],

                    // Theme Options
                    progress_bar            :   0,          // Timer for each slide
                    mouse_scrub             :   0

        });
        });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent iPhone from auto-connecting to unknown Wi-Fi? One thing I never do is to connect to foreign Wi-Fis. But my iPhone decides to automatically connect to those.

Translated:

Welcome to the Telekom HotSpot (german network provider). You are connected to the internet via your SIM over Wi-Fi and are using your HotSpot flatrate. There will be no additional cost.

Unfortunately I've seen the message half an hour later so I assume I already sent data via a foreign Wi-Fi in the background. How do I stop the phone from connecting to new, for me unknown wifis, without turning Wi-Fi off completly? Is this a general 'feature' or only in branded iPhones?

A: iPhone will only auto-join networks that are set to be joined automatically — it won't connect to any random network. SSIDs can be set to auto-join by being manually connected to in Settings → Wi-Fi in the past (the default is auto-join and you can tap the ⓘ to disable auto-join) or because of a profile installed on the device potentially by your carrier or workplace (accessed through Settings → General → Profiles).
You also might need to clean out the check mark to remember networks if you sync settings over iCloud. When one device remembers a network - it will sync to all devices and computers.


text:
Q: Apps script to get automated html email on google form submit I want to send a confirmation email whenever a customer submit a booking via google form. The content of the email will be partly based on the number of people and timeslot the customer chosen.
I succeed in triggering an email, but the email content is [object Object]. What did i do wrong?
function sendBookingConfirmationEmail(e) {

  var html = HtmlService.createTemplateFromFile("confirmationEmail.html");
  var emailTo = e.response.getRespondentEmail();
  var bookingParameters = e.response.getItemResponses();

  var bookingName = bookingParameters[0].getResponse()
  var numberOfTele = bookingParameters[1].getResponse()
  var numberOfKids = bookingParameters[2].getResponse()
  var numberOfAdults = bookingParameters[3].getResponse()
  var scheduledSlot = bookingParameters[4].getResponse()

  html.numberOfKids = numberOfKids;
  html.numberOfAdults = numberOfAdults;
  html.numberOfTele = numberOfTele;
  html.scheduledSlot = scheduledSlot;

  var htmlText = html.evaluate().getContent();

  var emailSubject = "BOOKING CONFIRMATION";
  var options = { htmlBody: htmlText }

  if (emailTo !== undefined) {
    GmailApp.sendEmail(emailTo, emailSubject, options);

  }

}

<!DOCTYPE html>

    <base target="_top">

  <?= numberOfKids ?> <?= numberOfAdults ?> Your booking has been confirmed.  etc...

 Best Regards

    Team

A: Based on this thread, try changing this line
GmailApp.sendEmail(emailTo, emailSubject, options);
to
GmailApp.sendEmail(emailTo, emailSubject, "", options);
I tested it and it works.

A: from documentation ,the full signature for the function is the folowing :
sendEmail(recipient, subject, body, options)
I supsect that you pass the options variable as the body
As workaround, you can put every argument into an object :
sendEmail({recipient:emailTo , subject: emailSubject, htmlBody: htmlText})


text:
Q: Code runs after catch statement catches and error and returns in react native firebase I am having issue whenever I catch an error and return from a function, by code after the catch block still runs. Here is my two functions that I use:
    usernameTaken: async (username) => {
        const user = await firebase.firestore().collection("uniqueUsers").doc(username).get();
        if (user.exists) {
            alert("Username is taken. Try again with another username.");
            throw new Error('Username is taken. Try again with another username.');
        }
    },
    changeUsername: async (currentUsername, newUsername) => {
      try {
          var user = Firebase.getCurrentUser();
          Firebase.usernameTaken(newUsername);
      } catch (err) {
          alert(err.message);
          return;
      }
      await db.collection('uniqueUsers').doc(currentUsername).delete();
      await db.collection("users").doc(user.uid).update({username: newUsername});
      await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});
      alert("Congratulations! You have successfully updated your username.");
    }

I would greatly appreciate any help for this problem, as I have been struggling with it for over 2 days now and can't seem to find a solution.

A: In your original code, the usernameTaken() promise is floating, because you didn't use await. Because it was floating, your catch() handler will never catch it's error.
changeUsername: async (currentUsername, newUsername) => {
  try {
      const user = Firebase.getCurrentUser();
      /* here -> */ await Firebase.usernameTaken(newUsername);
  } catch (err) {
      alert(err.message);
      return;
  }
  /* ... other stuff ... */
}

Additional Points
usernameTaken should return a boolean
You should change usernameTaken to return a boolean. This is arguably better rather than using alert() (which blocks execution of your code) or throwing an error.
usernameTaken: async (username) => {
  const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
  return usernameDoc.exists; // return a boolean whether the doc exists
}

Securely claim and release usernames
Based on your current code, you have no protections for someone coming along and just deleting any usernames in your database or claiming a username that was taken between the time you last checked it's availability and when you call set() for the new username. You should secure your database so that a user can only write to a username they own.
Add the owner's ID to the document:
"/uniqueUsers/{username}": {
  username: "username",
  uid: "someUserId"
}

This then allows you to lock edits/deletions to the user who owns that username.
service cloud.firestore {
  match /databases/{database}/documents {

    match /uniqueUsers/{username} {
      // new docs must have { username: username, uid: currentUser.uid }
      allow create: if request.auth != null
                    && request.resource.data.username == username
                    && request.resource.data.uid == request.auth.uid
                    && request.resource.data.keys().hasOnly(["uid", "username"]);

      // any logged in user can get this doc
      allow read: if request.auth != null;

      // only the linked user can delete this doc
      allow delete: if request.auth != null
                    && request.auth.uid == resource.data.uid;

      // only the linked user can edit this doc, as long as username and uid are the same
      allow update: if request.auth != null
                    && request.auth.uid == resource.data.uid
                    && request.resource.data.diff(resource.data).unchangedKeys().hasAll(["uid", "username"]) // make sure username and uid are unchanged
                    && request.resource.data.diff(resource.data).changedKeys().size() == 0; // make sure no other data is added
    }
  }
}

Atomically update your database
You are modifying your database in a way that could corrupt it. You could delete the old username, then fail to update your current username which would mean that you never link your new username. To fix this, you should use a batched write to apply all these changes together. If any one were to fail, nothing is changed.
await db.collection("uniqueUsers").doc(currentUsername).delete();
await db.collection("users").doc(user.uid).update({username: newUsername});
await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});

becomes
const db = firebase.firestore();
const batch = db.batch();

batch.delete(db.collection("uniqueUsers").doc(currentUsername));
batch.update(db.collection("users").doc(user.uid), { username: newUsername });
batch.set(db.collection("uniqueUsers").doc(newUsername), { username: newUsername });

await batch.commit();

Usernames should be case-insensitive
Your current usernames are case-sensitive which is not recommended if you expect your users to type/write out their profile's URL. Consider how "example.com/MYUSERNAME", "example.com/myUsername" and "example.com/myusername" would all be different users. If someone scribbled out their username on a piece of paper, you'd want all of those to go to the same user's profile.
usernameTaken: async (username) => {
  const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username.toLowerCase()).get();
  return usernameDoc.exists; // return a boolean whether the doc exists
},
changeUsername: async (currentUsername, newUsername) => {
  const lowerCurrentUsername = currentUsername.toLowerCase();
  const lowerNewUsername = newUsername.toLowerCase();

  /* ... */

  return lowerNewUsername; // return the new username to show success
}

The result
Combining this all together, gives:
usernameTaken: async (username) => {
  const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
  return usernameDoc.exists; // return a boolean
},
changeUsername: async (currentUsername, newUsername) => {
  const user = Firebase.getCurrentUser();
  if (user === null) {
    throw new Error("You must be signed in first!");
  }

  const taken = await Firebase.usernameTaken(newUsername);
  if (taken) {
    throw new Error("Sorry, that username is taken.");
  }

  const lowerCurrentUsername = currentUsername.toLowerCase();
  const lowerNewUsername = newUsername.toLowerCase();
  const db = firebase.firestore();
  const batch = db.batch();

  batch.delete(db.collection("uniqueUsers").doc(lowerCurrentUsername));
  batch.update(db.collection("users").doc(user.uid), {
    username: lowerNewUsername
  });
  batch.set(db.collection("uniqueUsers").doc(lowerNewUsername), {
    username: lowerNewUsername,
    uid: user.uid
  });

  await batch.commit();

  return lowerNewUsername;
}

// elsewhere in your code
changeUsername("olduser", "newuser")
  .then(
    (username) => {
      alert("Your username was successfully changed to @" + username + "!");
    },
    (error) => {
      console.error(error);
      alert("We couldn't update your username!");
    }
  );

Note: If you are using all of the above recommendations (like the security rules), one of the expected ways batch.commit() will fail is if someone takes the username before the current user. If you get a permissions error, assume that someone took the username before you.

A: Try this check if your values are empty or not defined throw some error in try block  e.g.
cosnt user = Firebase.getCurrentUser();
const name = Firebase.usernameTaken(newUsername);
// throwing error
if(name == "") throw "is empty";
await db.collection('uniqueUsers').doc(currentUsername).delete();


text:
Q: PostgreSQL role inheritance not working? I ran into a very annoying role inheritance issue with PostgreSQL. It simply doesn't behave as it should according to the documentation.
I would like to have a master role, and grant its permissions to newly created users. These users should inherit the permissions without issuing SET ROLE manually.
CREATE ROLE testrole NOSUPERUSER INHERIT CREATEDB NOCREATEROLE;
CREATE ROLE testuser LOGIN NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE;
GRANT testrole TO testuser;

Now after I connect as testuser, I get the following:
postgres=> CREATE DATABASE foobar;
ERROR:  permission denied to create database
postgres=> SET ROLE testrole;
SET
postgres=> CREATE DATABASE foobar;
CREATE DATABASE

According to the docs linked above (because of the INHERIT option), the SET ROLE shouldn't be required.
What am I missing here?

A: A bit further down the same page:
"The role attributes LOGIN, SUPERUSER, CREATEDB, and CREATEROLE can be thought of as special privileges, but they are never inherited as ordinary privileges on database objects are. You must actually SET ROLE to a specific role having one of these attributes in order to make use of the attribute."


text:
Q: Add text in clipboard as hyperlink to a cell I want to create macro which when run, pastes the link contained in clipboard to the current cell as a hyperlink. I tried with the record macro the following code was generated which I modified a little:
Sub Macro1()
'
' Macro1 Macro
'

'
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="abc.com" _
        , TextToDisplay:="Link"
End Sub

Here, instead of abc.com it should be something like "paste text in keyboard".

A: According to the @DanL comment, here is the code you need :
Sub Macro1()
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=GetClipboardText() _
        , TextToDisplay:="Link"
End Sub

Function GetClipBoardText() as String
   Dim DataObj As MSForms.DataObject
   Set DataObj = New MsForms.DataObject '<~~ Amended as per jp's suggestion

   On Error GoTo Whoa

   '~~> Get data from the clipboard.
   DataObj.GetFromClipboard

   '~~> Get clipboard contents
   GetClipBoardText = DataObj.GetText(1)

   Exit Sub
Whoa:
   If Err <> 0 Then MsgBox "Data on clipboard is not text or is empty"
End Sub


text:
Q: Ayuda con diseño de Tabs en HTML con Bootstrap En realidad no sé mucho de diseño, por eso utilizo Bootstrap para diseñar la parte estética de mi sistema.
Estoy intentando organizar mis TABs pero la verdad se me ve de una forma muy horrible, espero que me puedan ayudar indicándome cómo puedo hacer para que se vea más estético, por ejemplo utilizar mas el div y que no se parta en 2 partes las letras.
PRODUCTOS LCN -> boton ver mas
168.235.83.190/~app/img/lcn/public_html
Les dejo la imagen y el codigo de mi TABS

El codigo:

Accesorios

Acopladores

Audio

Control de Accesos

Control Remoto

Entradas Binarias

Estación Climática

Gateways

Módulos de Bus

Salidas

A: Puedes optar por quitar la clase nav-justified para que cada pestaña ocupe un tamaño en función de su contenido o dividir en varias filas los tabs.
Esta segunda opción es bastante mala ya que únicamente se verá correctamente en ciertas resoluciones perdiendo la capacidad responsive de tu interfaz.
Las opciones que sugiere la propia documentación de bootstrap son:

*

*Reducir la cantidad o el tamaño (ancho) de los tabs

*Ocultar algunos elementos en función de la resolución utilizando las clases de bootstrap

*Modificar el punto en el que se pasa del modo "collapsed" al "horizontal" modificando la variable @grid-float-breakpoint.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">

Accesorios

Acopladores

Audio

Control de Accesos

Control Remoto

Entradas Binarias

Estación Climática

Gateways

Módulos de Bus

Salidas

Accesorios

Acopladores

Audio

Control de Accesos

Control Remoto

Entradas Binarias

Estación Climática

Gateways

Módulos de Bus

Salidas

A: Estas usando clases que pertenecen al elemento modal de boostrap.
En su lugar usa navbar, puedes ver los ejemplos aquí

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Link (current)

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

      <form class="navbar-form navbar-left">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

Link

          Dropdown

Action

Another action

Something else here

Separated link

A: Puedes guiarte de este menú que yo hice,

body{
    background: #8999A8;
}
.navbar, .dropdown-menu{
background:rgba(255,255,255,0.25);
border: none;

}

.nav>li>a, .dropdown-menu>li>a:focus, .dropdown-menu>li>a:hover, .dropdown-menu>li>a, .dropdown-menu>li{
  border-bottom: 3px solid transparent;
}
.nav>li>a:focus, .nav>li>a:hover,.nav .open>a, .nav .open>a:focus, .nav .open>a:hover, .dropdown-menu>li>a:focus, .dropdown-menu>li>a:hover{
  border-bottom: 3px solid transparent;
  background: none;
}
.navbar a, .dropdown-menu>li>a, .dropdown-menu>li>a:focus, .dropdown-menu>li>a:hover, .navbar-toggle{
 color: #fff;
}
.dropdown-menu{
      -webkit-box-shadow: none;
    box-shadow:none;
}

.nav li:hover:nth-child(8n+1), .nav li.active:nth-child(8n+1){
  border-bottom: #C4E17F 3px solid;
}
.nav li:hover:nth-child(8n+2), .nav li.active:nth-child(8n+2){
  border-bottom: #F7FDCA 3px solid;
}
.nav li:hover:nth-child(8n+3), .nav li.active:nth-child(8n+3){
  border-bottom: #FECF71 3px solid;
}
.nav li:hover:nth-child(8n+4), .nav li.active:nth-child(8n+4){
  border-bottom: #F0776C 3px solid;
}
.nav li:hover:nth-child(8n+5), .nav li.active:nth-child(8n+5){
  border-bottom: #DB9DBE 3px solid;
}
.nav li:hover:nth-child(8n+6), .nav li.active:nth-child(8n+6){
  border-bottom: #C49CDE 3px solid;
}
.nav li:hover:nth-child(8n+7), .nav li.active:nth-child(8n+7){
  border-bottom: #669AE1 3px solid;
}
.nav li:hover:nth-child(8n+8), .nav li.active:nth-child(8n+8){
  border-bottom: #62C2E4 3px solid;
}

.navbar-toggle .icon-bar{
    color: #fff;
    background: #fff;
}

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    Toggle navigation

                    </button>
                    Logo

Home

                            Departments

                                    View Departments

Add New

Add New

Managers

View Managers

Add New

Staff

View Staff

Add New

Bulk Upload

HR

Change Time Entry

Report

Signed in as

Change Password

My Profile

Logout

Nota: el menú está trasparente, colócale un color a tu gusto. Probablemente salgan algunos errores, normalmente es el Padding el que suele fallar, el width y algunos elementos mas.

A: Saliendome un poco de Bootstrap podría darte una alternativa, ahora bien. Ésta alternativa no es optimizada, pero igual puedes adaptarla.
https://codepen.io/anon/pen/weBPLb
El menú está vertical y es accesible desde un botón para que aparezca / desaparezca.
HTML

Menú de navegación

                Inicio

                Item 2

                Item más largo

                Item aún más largo

                Otro item

                Ésto no acaba

                Hasta cuando

                Deténte

                Super increíble

                Oh my God!

                Save us

                Save us

                Save us

                NOW!

                Último y más largo ítem

    <button class="btn btn-danger abrirMenu form-control">Abrir / Cerrar</button>

CSS
.menu{
    opacity: 0;
    position: fixed;
    top: 0;
    left: 0;
    background-color: #0275d8;
    padding: 12px;
    z-index: 999;
}
.menu .insider{
    width: 100%;
    height: 100%
    background-color: #0275d8;
}
.menu .insider h5{
    color: #1591ff;
}
.menu .insider ul.items{
    display: block;
    font-size: 0;
    margin: 0;
    padding: 0;
    width: 100%;
    overflow-y: auto
}
.menu .insider ul.items .item{
    display: block;
    font-size: 16px;
    margin-bottom: 5px;
}

jQuery / JavaScript
$(document).ready(function() {
    var ven = $(window);
    var inn = $(".menu .insider");
    var abierto = false;
    $(".menu").css({
        "width": 240,
        "height": ven.height()
    });
    $(".menu .insider ul.items").css({
        "height": (ven.height() - 24) - $(inn).find('h5').height()
    });

    $(".menu").css({
        left: ($(".menu").width() * -1) - 100
    });

    function an(){
        if (!abierto){
            abierto = true;
            $(".menu").animate({
                display:'block',
                opacity:1,
                left: 0
            }, 1000, "easeOutExpo");
        }else{
            abierto = false;
            $(".menu").animate({
                display:'',
                opacity:'',
                left: ($(".menu").width() * -1) - 100
            }, 1000, "easeOutExpo");
        }
    }

    $(".abrirMenu").on('click', function(event) {
        an();
    });
  ven.resize(function(){
    $(".menu").css({
      "width": 240,
      "height": ven.height()
    });
    $(".menu .insider ul.items").css({
      "height": (ven.height() - 24) - $(inn).find('h5').height()
    });
  });

});

NOTA: Yo uso jQuery 3, jQuery UI & Bootstrap 4 en éste ejemplo.

Adicionalmente: Si te gustan las animaciones y quieres saber más de ellas en jQuery UI hay muchas más: https://api.jqueryui.com/easings/
Espero pueda servirte.


text:
Q: jQuery check if the last three data attributes are equal to Lets say this is the HTML:

bla

bla

bla

bla

bla

How do I check if the last three user attributes are 7?

A: You could use nth-last-child selector in combination with attribute selector:

var is = $('.msg:nth-last-child(-n+3)[data-user=7]').length === 3;

if (is) {
    console.log('last 3 messages has data-user 7');
}

bla

bla

bla

bla

bla

A: Try using .slice() , .get() , Array.prototype.every()

var res = $("#chat .msg").slice(-3).get().every(function(val) {
  return val.dataset.user === "7"
});

console.log(res)

bla

bla

bla

bla

bla


text:
Q: VSCode-extension: changing color in settings.json I would like to change the color(s) of a multiple-words occurrence-highlighting VSCode-extension called highlight.
Here is what it looks like in my VSC with standard extension-settings:

I would like to change the green color (#e6ffb3) because I find it hard to see. According to the extension's readme, this should be possible by changing highlight.configuration.colors. Here you can see highlight.configuration.colors in action in the context of the extension's standard settings).
The following is how I tried to change #e6ffb3 green (by moving it to the end of the colors-array) in my VSC's settings.json-file, unfortunatly with no effect:
 {
    "window.zoomLevel": -1,
    "[csharp]": {
        "editor.defaultFormatter": "csharpier.csharpier-vscode"
    },
    "workbench.colorTheme": "Blue Light Theme",
    "workbench.colorCustomizations": {
        "editor.selectionBackground": "#e7ff0ed2", // "#13fa00",
        "editor.selectionHighlightBackground": "#e7ff0ed2",
        "scrollbarSlider.activeBackground": "#808080", // Slider background color when active.
        "scrollbar.shadow": "#808080", // Schatten zwischen Tableiste und Code
        "scrollbarSlider.background": "#808080" //Slider background color.
    },
    {
        "editor.wordWrap": "wordWrapColumn",
        "workbench.colorTheme": "Blue Light Theme"
    },
    {
        "highlight.configuration.colors": {
            [
                {
                    "light": "#b3d9ff",
                    "dark": "#F5B041"
                }
                {
                    "light": "#b3b3ff",
                    "dark": "#85C1E9"
                },
                {
                    "light": "#ffd9b3",
                    "dark": "#CD6155"
                },
                {
                    "light": "#ffb3ff",
                    "dark": "#AF7AC5"
                },
                {
                    "light": "#b3ffb3",
                    "dark": "#48C9B0"
                },
                {
                    "light": "#ffff80",
                    "dark": "#52BE80"
                },
                {
                    "light": "#d1e0e0",
                    "dark": "#F4D03F"
                },
                {
                    "light": "#e6ffb3",
                    "dark": "#FF9933"
                },
            ]
        }
    }
}

Can you please help me fix my above code?


text:
Q: php Loop through all skus in magento I need to write to mysql database related products and upsells. This should be done by php. I can now set this for 1 product, but need to loop through all the products. My script:
<?php
set_time_limit(0);

require_once "blablabla/app/Mage.php";//my path here
umask(0);
Mage::app();

$sku="876297-6";  //some Sku
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);

$param = array(
101=>array(
'position'=>3
),
102=>array(
'position'=>5
)
);
$_product->setRelatedLinkData($param);
$_product->save();

echo "Great!!";

 ?>

What I cannot do is the following:
1.Get all product IDs
  2.For each product ID set a related product as a random product from collection
Position does not matter at all.    + do this until there are 20 related products would be cool, but I can also run script 20 times, no pressure. Better to work with product IDs and not skus.
My script is just example. main purpose is to set 20 random related products to each product
Thanks in advance!

A: looping through all products using the Magento ORM is not the best idea. It's really time consuming.
Try instead to get all the ids and then run a simple sql query that will insert a row in the database.
Here is how you can get all the ids:
$ids = Mage::getModel('catalog/product')->getCollection()->getAllIds();

Once you know what product needs to be added as related for an other product do this:
Let's say that $mainId is the id of the main product and $relatedId is the id of the related product.
"INSERT into catalog_product_link SET
    product_id = $mainId,
    linked_product_id = $relatedId,
    link_type_id = 1
"

1 is the link type id for related products.

A: Final script, made by AreDubya:
<?php
set_time_limit(0);

require_once "/blablabla/app/Mage.php";//my path
umask(0);

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$resource = Mage::getSingleton('core/resource');

$writeConnection = $resource->getConnection('core_write');

$ids = Mage::getModel('catalog/product')->getCollection()->getAllIds();
foreach ($ids as $id) {
    $mainId = $id;
    $relatedId = $ids[array_rand($ids)];
    echo "$id - $relatedId<br/>";
    $query = "INSERT into catalog_product_link (product_id,linked_product_id,link_type_id) VALUES ($mainId, $relatedId ,1)";

    $writeConnection->query($query);
}

echo "done";

 ?>


text:
Q: linux string-replace for mac os x i.e. sed with no regex i have an old script on which replaces strings in files using the 'replace' command e.g.
    newname=`echo "$f" | replace "${OLD}" "${NEW}"`

this used to run on mac os x (all versions up to yosemite). I remember finding this as a non-regex processing version of sed i.e. you don't need to escape all the regex bits of the string. it definitely exists under linux (http://linux.die.net/man/1/replace).
i had to rebuild my mac (os x yosemite) and cannot for the life of me find this command. have tried

*

*googling but everything points to sed!

*tried some of the gnu utility packages in brew e.g. coreutils

nothing - i'm sure it used to exist!?
any pointers gratefully received!


text:
Q: How can i sort a string in alphabetical order in python I've been trying to sort a string in alphabetical order and got stuck. I know that the sort function exists on python but i cant use it. Cant even use the .join method as well. Gotta do it all using for loops.
def wordOrder(word):
    word =  list(word)
    for i in range(0, len(word)):
        for j in range(i, len(word)):
            if word[i] > word[j]:
                word[i], word[j] = word[j], word[i]
    word = ""+ str(word)
    return word

Here's what i have but I did it with a tutor and cant remember what the if section does.
Thank you!

A: You can use ( > , < , <= , <= , == , != ) to compare two strings. Python compares string lexicographically i.e using ASCII value of the characters.
If statement compares the first and second letter's ASCII value.
if its greater than exchange.
for example,
print(wordOrder('ba'))

output
['a', 'b']

ASCII value of small a is 97 and b is 98.
if word[i] > word[j]:
                word[i], word[j] = word[j], word[i]

So,
 word[i] --> b --> 98
 word[j]  --> a --> 97

Since, 98 is greater than 97 we swap both the values.


text:
Q: swift array only appended 3 items instead of 5 As title. I thought I've got it to work but it only appended 3 items into my array of NSMutableDictionary. I think maybe it's because the performsegue got called before the items are completely appended? How should I fix this problem?
(Also I dont know why but when I print(someDict.count) it gave me 17... it should only be 5 though since there are only 5 businesses)
Here's the code:
var searchBusinessDictionary: [NSMutableDictionary] = []

    func retrieveBusinessFromAPI(id: String){
    let url = URL(string: "https://api.yelp.com/v3/businesses/\(id)")
    var request: URLRequest = URLRequest(url: url!)
    request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "GET"
    let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
        let businessData = JSON(data)
            var someDict = NSMutableDictionary()
            someDict.setValue(businessData["name"], forKey: "Business Name")
            someDict.setValue(businessData["url"], forKey: "Business Yelp URL")
            someDict.setValue(businessData["image_url"], forKey: "Business image URL")
            someDict.setValue(businessData["hours"][0]["is_open_now"], forKey: "Business Is Open Now")
            someDict.setValue(businessData["price"], forKey: "Business Price")
            someDict.setValue(businessData["rating"], forKey: "Business Rating")
            someDict.setValue(businessData["location"]["display_address"], forKey: "Business Location")
        self.searchBusinessDictionary.append(someDict)
        self.performSegue(withIdentifier: "businessListSegue", sender: self)
    })
    task.resume()
}

Tried dispatching my performsegue to my main thread however I dont think the perform segue is called since my view didn't change
Here's the code for that:
@IBAction func saerch(_ sender: UIButton) {
    self.yelpAPIRequest(completion: {
        OperationQueue.main.addOperation {
            self.performSegue(withIdentifier: "businessListSegue", sender: self)
        }
    })
}

 func yelpAPIRequest(completion: ()->()){
    let coordinate = YLPCoordinate(latitude: self.userLatitude, longitude: self.userLongitude)
    let query = YLPQuery(coordinate: coordinate)
    query.term = "dessert"
    query.limit = 5

    YLPClient.authorize(withAppId: clientId, secret: clientSecret).flatMap { client in
        client.search(withQuery: query)
        }.onSuccess { search in
            if search.businesses.isEmpty == false {
                let topBusiness = search.businesses

                for i in topBusiness{
                    print(i.identifier)
                    self.retrieveBusinessFromAPI(id: i.identifier)
                }

            } else {
                print("No businesses found")
            }
        }.onFailure { error in
            print("Search errored: \(error)")
        }
}


text:
Q: Get .tif and .jpg image tags using PHP When I use Windows Explorer to view the Properties of an image file, I see "Tags" under the Description section of the Details tab.
Is it possible to get these "Tags" using PHP?
I have looked at the documentation for exif_read_data on the PHP site. However, I only see code for getting reading dimensions and comments.

A: The very first example on the page you linked does just that: Example
With the IFD0 option you get all tags, so just implement it like this and use the tags you need.


text:
Q: In a UICollectionView, how can I get my cells to autolayout BEFORE they appear on screen? I have a UICollectionView with self sizing cells. When I scroll through the collection I can see the cells resizing themselves at the bottom of the screen.
Is there a way I can get the cells to resize themselves before the appear?
I am using flow layout and my cells contain just 3 labels. I am also using estimatedItemSize.


text:
Q: Determine if raw disk sector is in use I'm trying to write a free space zeroizer using open(2), lssek[64](2), and write(2). I am trying to determine of a disk sector is in use.
I have took a look at dd(1) from coreutils, but the utility is not performing similar checks. In the Windows world, I could call DeviceIoControl with FSCTL_GET_VOLUME_BITMAP.
Given a raw sector, is there a system call which allows me to determine if the sector is in use?

A: The traditional way this is accomplished (since your method is subject to filesystem-corrupting race conditions), is to create a giant file, zero it, then delete the file. In fact, you can do this with sh directly, no need for a file:
# dd will run until disk space is exhausted
dd if=/dev/zero of=__somefile.bin bs=1M conv=noerror; rm __somefile.bin


text:
Q: How can I get slurm to assign each node a single task? I'm running approximately 400 files through a SLURM pipeline with sbatch. When I queue a task with sbatch ./myscript.sh file_x all the files get queued to the same node.
I've tried a variation of the #SBATCH parameters at the beginning of sbatch script and to no luck. Here's what I've tried so far:
#!/bin/bash
#SBATCH -N 1
#SBATCH -n 60
#SBATCH -o slurm_out/output_%j.txt
#SBATCH -e slurm_error/error_%j.txt

and
#!/bin/bash
#SBATCH -n 60
#SBATCH -o slurm_out/output_%j.txt
#SBATCH -e slurm_error/error_%j.txt

and
#!/bin/bash
#SBATCH -N 1
#SBATCH -o slurm_out/output_%j.txt
#SBATCH -e slurm_error/error_%j.txt

and
#!/bin/bash
#SBATCH -o slurm_out/output_%j.txt
#SBATCH -e slurm_error/error_%j.txt

The slurm_out files are being created and written to so SBATCH is definitely picking up the parameters.
regarding the -n option, the docs say that the default is "one task per node" however, that seems not to be the case:

-n, --ntasks= sbatch does not launch tasks, it requests an allocation of resources and submits a batch script. This option
  advises the Slurm controller that job steps run within the allocation
  will launch a maximum of number tasks and to provide for sufficient
  resources. The default is one task per node, but note that the
  --cpus-per-task option will change this default.

What parameters will get a single task per node?

A: You can simply try with --ntasks-per-node=1. The default of "one task per node" applies when the number of tasks is not specified by the number of node is. In such case Slurm will assume that it must spawn as many tasks as the number of nodes requested. Which still does not mean that each task will be assigned a distinct node, it depends on how you start the computations in the submission script.
If you furthermore need no other jobs than yours on the node, add the --exclusive parameter.


text:
Q: What does a norm of a polynomial space mean? When talking about polynomial vector space, the following example was provided.

A polynomial of degree $n$ in two variables is $$p(X)=\sum_{0\leq k+j \leq n}  a_{j,k}x_1^jx_2^k$$ where $k+j=n$ and $a_{j,k} \neq 0$.
An example of a degree-two polynomial is $||X||^2$ $=x_1^2+x_2^2$

I am conflicted regarding this notation. My understanding was that a norm has outputs in $\mathbb{R}$ whereas this is showing the norm to be a polynomial in itself.
Am I misunderstanding something here?

A: $\|X\|$ is not really part of the example. It should probably just have been written

An example of a degree-two polynomial is $x_1^2+x_2^2$.

Writing "$\|X\|=$" in front of it seems just to be intended to reassure the possibly-overwhelmed reader that "this is not a totally new scary thing; remember that you have seen this expression before when defining the Euclidean norm even though you didn't know it was called a polynomial in 2 variables back then".
Feel free to feel vaguely offended by the suggestion that you may be overwhelmed enough to need such assurance.
The source you're quoting doesn't appear to be very carefully written: the condition after the displayed equation doesn't really make sense and should probably read something like

where $a_{j,k}\ne 0$ for at least one pair $(j,k)$ with $j+k=n$.

A: This is just suggestive notation; they are not actually saying this is a norm in the sense of analysis.  They are defining the symbol $\|X\|^2$ to mean a certain polynomial in $X$, namely $x_1^2+x_2^2$.  This notation is presumably chosen because this polynomial is related to the familiar Euclidean norm on $\mathbb{R}^2$.


text:
Q: How to simplify $\frac{3+\log_{p}3}{5^2}=\frac{-5+\log_{p}5}{3^2}$? I've found this problem in my algebra book and still can't get the right way how to solve it.
The problem is as follows:
Find $\log_{p^5}\left(3^5\times 5^3\right)$ from:
$$\frac{3+\log_{p}3}{5^2}=\frac{-5+\log_{p}5}{3^2}=\frac{10}{3^3+5^3}$$
The alternatives given are:
$\begin{array}{ll}
 1.& 2\\
 2.& 1\\
 3.& \frac{1}{2}\\
 4.& 3\\
 5.& \frac{1}{3}\\
 \end{array}$
So far what I tried is the following, but I must say that this process was tediously slow and in the end I couldn't get the value of $p$.
What I began was to obtain a relationship between the functions:
$\log_{p}3=\frac{5^2\left(10\right)}{3^3+5^3}-3$
$\log_{p}5=\frac{3^2\left(10\right)}{3^3+5^3}+5$
Then I went to the question so what it is being asked is:
$\log_{p^5}\left(3^5\times 5^3\right)$
This is reduced to:
$\log_{p^5}\left(3^5\times 5^3\right)=\frac{5}{5}\log_{p}3+\frac{3}{5}\log_{p}5$
So all what it was left was to replace the first two expressions in the later:
$\left(\frac{1}{5}\right)\left(\left[5\right]\left(\frac{5^2\left(10\right)}{3^3+5^3}-3\right)+\left[3\right]\left(\frac{3^2\left(10\right)}{3^3+5^3}+5\right)\right)$
$\frac{5}{5}\log_{p}3+\frac{3}{5}\log_{p}5=  \frac{1}{5}\left(\frac{5^3\left(10\right)-15\left(3^3+5^3\right)+3^3\left(10\right)+15\left(3^3+5^3\right)}{3^3+5^3}\right)$
$\frac{5}{5}\log_{p}3+\frac{3}{5}\log_{p}5=\frac{1}{5}\left(\frac{10\left(3^3+5^3\right)-15\left(3^3+5^3\right)+15\left(3^3+5^3\right)}{3^3+5^3}\right)$
$\frac{5}{5}\log_{p}3+\frac{3}{5}\log_{p}5=\frac{1}{5}\left(\frac{10\left(3^3+5^3\right)}{3^3+5^3}\right)$
$\frac{5}{5}\log_{p}3+\frac{3}{5}\log_{p}5=\frac{1}{5}\left(10\right)$
$\frac{5}{5}\log_{p}3+\frac{3}{5}\log_{p}5=2$
Therefore the answer would be $2$. However as mentioned using this procedure did not required to find $p$ however I wonder if attempting to find $p$ would yield an integer or would be a right way to go?. The method which I used consumed a lot of time. Does it exist a workaround to be easier or faster?. I'd appreciate someone could help me with this!.

A: Since $\log_p 5 = 3^2\frac {10}{3^3 + 5^3} + 5$
we have $5 = p^{3^2\frac {10}{3^3 + 5^3} + 5}= p^{5.5921052631578947368421052631579}$
So $p = \sqrt[5.5921052631578947368421052631579]{5} = 1.3334977373599735351181643891153$.
I'm pretty sure that's a dead end.
The algebra is nasty but there is a lot of canceling if you do it right so it's not so bad.
....
Well, $\log_p 3 = 5^2\frac {10}{3^3 + 5^3}-3$
And $\log_p 5 = 3^2\frac {10}{3^3 + 5^3} + 5$.
And so $\log_{p^5}(3^5\times 5^3) = \log_p 3 + \frac 35\log_p 5=5^2\frac {10}{3^3 + 5^3}-3 + \frac 35(3^2\frac {10}{3^3 + 5^3} + 5)$
$= 5^2\frac {10}{3^3 + 5^3}-3 + 3^3\frac {2}{3^3 + 5^3} + 3$
$= \frac {5^3*2}{3^3 + 5^3} + \frac {3^3*2}{3^3 + 5^3}$
$= \frac {2}{3^3 + 5^3}(5^3+ {3^3})$
$ = 2$


text:
Q: Desktop icons on Ubuntu 18.04 no longer displayed properly After upgrading to Ubuntu 18.04 my desktop icons no longer display their respective artwork. Only after opening them individually and going through the process of "Untrusted Application Launcher" will correct them.

Is there a way to trigger a mass "trust" to bring the art back or some other method?

A: desktop files can be trusted via the command line:
gio set Your_desktop_file.desktop "metadata::trusted" yes

NOTE:

*

*Make sure your Desktop file is executable with the following command: chmod +x Your_desktop_file.desktop

*You have to run this command with the same user as the owner of the desktop files

*It only works if you run the command in the gnome shell (not via SSH)

*To do this automatically at logon, you have to make a logon script which will execute a script, as this only run when Gnome is started. For example you can create a .desktop file in ~/.config/autostart/ which execute some shell script including the gio commands

*Make sure nautilus-desktop is really started. You can create a while loop with a sleep 1 till nautilus-desktop runs

*Icon's will not refresh automatically. You can achieve this with pressing F5 on the desktop or restart nautilus in your autostart script. killall nautilus && nautilus-desktop & (the last & sign is to make sure the rest of your code will run. Otherwise it will stop the script there till you close nautilus-desktop process again)


text:
Q: Yii2 dynamically add joinWith i have an online store with dynamic fields (specifications) and filters. All specifications are stored in table e.g
product_specifications:
-id
-product_id
-spec_id
-spec_val_id

Filters are connected with specifications, so when i send filter value i send specification values. For example
$_GET['Filters']['filter_id']['spec_val_id']

When i loop filters, i want to add left joins to product query. Something like that
$joinString = "";
foreach($filters){
$joinString .= "LEFT JOIN product_specifications AS prod_'.filter.' ON .....";
}

I have query to ActiveDataProvider like that:
$prodQuery = Product::find()->joinWith('translation')->joinWith('cats')->[HERE FILTERS JOINS]->where($whereString)->groupBy(['id']);

But if i have 5 filters, i need 5 joins to table product_specifications.
Can i add in joinWith an array with all joins or add 5 joins to query chain?
To one category my filters are also dynamically, so the page can have 5 or 10 filters, i can't add static number of joinWith('specs').
Thanks in advance.
I'm agree with different desicion, too.
EDIT:
I change query with findBySql like this
$prodQuery = Product::findBySql('
              SELECT `product`.*
              FROM `product`
              LEFT JOIN `productLang` ON `product`.`id` = `productLang`.`product_id`
              LEFT JOIN `product_cat` ON `product`.`id` = `product_cat`.`product_id`
              LEFT JOIN `page` ON `product_cat`.`page_id` = `page`.`id`
              LEFT JOIN `page` `parent` ON `page`.`id_in` = `parent`.`id`'
              .$joinString.
              ' WHERE ( '
                    .$whereString.
                    ' AND (`language`=\''.$lang->url.'\')) GROUP BY `product`.`id` ');

And my dataprovider:
$dataProvider = new ActiveDataProvider([
                'query' => $prodQuery,
                'pagination' => [
                    'totalCount' => count($prodQuery->all()),
                    'pageSize' => $pageSize,
                    'route' => Yii::$app->getRequest()->getQueryParam('first_step'),
                ],
                'sort' => [
                    'defaultOrder' => $orderArr,
                ],
            ]);

Now my problem is pagination and sorting. In my test site i have 4 products, when i set $pageSize = 1;, I have 4 pages in pagination, but in every page i have all 4 products.
Where is my mistake?

A: Could be  you can use andFilterWhere (if the value is null no where codntion is added  otherwise the and Where is added)
$prodQuery = Product::find()->joinWith('translation')->joinWith('cats')->where($whereString)->groupBy(['id']);

$prodQuery->andFilterWhere(['attribute1' => $value1])
          ->andFilterWhere(['attribute2' => $value2])
          ->andFilterWhere(['attribute3' => $value3])
          ->andFilterWhere(['attribute4' => $value4])
          ->andFilterWhere(['attribute5' => $value5])


text:
Q: How to estimate the timescale for strong interactions? I have learned that the characteristic time for QCD process is about $10^{-24}s$, Then I wonder if there is a way to estimate the timescale for strong interactions?

A: The width of a resonance is directly connected to the lifetime :
Γ=h_bar/τ     Γ the width  τ the mean life time

Thus, the lifetime of a particle is the direct inverse of the particle's resonance width. For example, the charged pion has the second-longest lifetime of any meson, at 2.6033×10^−8 s. Therefore, its resonance width is very small, about 2.528×10−8 eV or about 6.11 MHz.

That was classified as a weak interaction
The π0   which decays to two gamma has a lifetime of 8.4*10^-17 , and decays electromagnetically. It was classified as an electromagnetic interaction.

The charged rho meson has a very short lifetime, about 4.41×10^−24 s. Correspondingly, its resonance width is very large, at 149.1 MeV or about 36 ZHz.

That was classified as a strong interaction.
Thus the time scale of strong interactions can be extracted from the width of  the resonances, of course corrected for experimental errors. For example the Higgs which decays weakly has a large width in the LHC measurements because of experimental errors. But in the beginning of classification of forces  careful experiments measuring lifetimes were carried out.
That is how the interactions were classified as strong, weak and electromagnetic.


text:
Q: ¿Cómo hacer consultas a array de json en MySQL? Buen día.
Tengo el siguiente json: [{"Name": "Bart", "Age": 10, "Id": 1}, {"Name": "Lisa", "Age": 8, "Id": 2}]
Y necesito obtener la ruta cuantdo el Id es 2.
Yo se que con JSON_SEARCH puedo obtener rutas, pero con el Id no meda :(.
Si lo hago con el nombre si da así:
SELECT '[{"Name": "Bart", "Age": 10, "Id": 1}, {"Name": "Lisa", "Age": 8, "Id": 2}]' as json,
   JSON_SEARCH('[{"Name": "Bart", "Age": 10, "Id": 1}, {"Name": "Lisa", "Age": 8, "Id": 2}]', 'one', 'Lisa') as path;

Y me sale el resultado esperado:
|-----------------------------------------------------------------------------|------------|
|json                                                                         | path       |
|-----------------------------------------------------------------------------|------------|
|[{"Name": "Bart", "Age": 10, "Id": 1}, {"Name": "Lisa", "Age": 8, "Id": 2}]  |"$[1].Name" |
|-----------------------------------------------------------------------------|------------|

Pero al intentarlo con el id asi:
SELECT '[{"Name": "Bart", "Age": 10, "Id": 1}, {"Name": "Lisa", "Age": 8, "Id": 2}]' as json,
       JSON_SEARCH('[{"Name": "Bart", "Age": 10, "Id": 1}, {"Name": "Lisa", "Age": 8, "Id": 2}]', 'one', 2) as path;

Sale nulo:
|-----------------------------------------------------------------------------|------------|
|json                                                                         | path       |
|-----------------------------------------------------------------------------|------------|
|[{"Name": "Bart", "Age": 10, "Id": 1}, {"Name": "Lisa", "Age": 8, "Id": 2}]  | null       |
|-----------------------------------------------------------------------------|------------|

¿Cómo puedo realizar la consulta filtrando por id?
Muchas Gracias!

A: La función JSON_SEARCH(json_doc, one_or_all, search_str[, escape_char[, path] ...]) espera en su tercer parámetro un valor texto (string).
Un opción, quizás algo compleja, es la siguiente (evaluar posibles problemas de desempeño/performance):
SELECT
  JSON_SEARCH(
    REPLACE(
      REPLACE(
        REPLACE(
          JSON_EXTRACT(@`json`, "$[*].Id"),
          ', ',
          '","'
        ),
        '[',
        '["'
      ),
      ']',
      '"]'
    ),
    'one',
    '2'
  ) `path`;

Ver dbfiddle.


text:
Q: Multiple Insert statements in one connection I need some tips on how to do this better, I am inserting multiple queries with using one connection.
I understand this is not good programming, especially with it being very prone to sql injection, I also wanted to mention it's not going to be out on the internet just run locally.
This is what I have so far..
public partial class Modify : System.Web.UI.Page
{
    OleDbConnection connection;
    OleDbCommand command;

  public void OpenConnection2()
    {
        connection = new OleDbConnection("");
        command = new OleDbCommand();
        connection.Open();
    }

  protected void btnSave_Click1(object sender, EventArgs e)
    {
        if (AcctNumList.SelectedValue == "3")
        {
            string query2 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                            id, newguid, Name1TxtBox.Text.Replace("'", "''"), Amt1TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString());
            string query3 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                            id, newguid, Name2TxtBox.Text.Replace("'", "''"), Amt2TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString());
            string query4 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                            id, newguid, Name3TxtBox.Text.Replace("'", "''"), Amt3TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString());
            OpenConnection2();
            command.Connection = connection;
            command.CommandText = query2;
            int c = command.ExecuteNonQuery();
            connection.Close();
        }
     if (AcctNumList.SelectedValue == "4")
        {
            string query2 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                            id, newguid, Name1TxtBox.Text.Replace("'", "''"), Amt1TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString());
            string query3 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                            id, newguid, Name2TxtBox.Text.Replace("'", "''"), Amt2TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString());
            string query4 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                            id, newguid, Name3TxtBox.Text.Replace("'", "''"), Amt3TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString());
            string query5 = String.Format(@"INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date) values
                                                            ('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                            id, newguid, Name4TxtBox.Text.Replace("'", "''"), Amt4TxtBox.Text.Replace("'", "''"), 3, DateTime.Now.ToString());
            OpenConnection2();
            command.Connection = connection;
            command.CommandText = query2;
            int c = command.ExecuteNonQuery();
            connection.Close();
        }

A: You should parameterized your query - ALWAYS, but for now you can concatenate those queries with ; and then execute them once like:
string allQueries = string.join(';', query2, query3, query4, query5);
command.CommandText = allQueries;
int c = command.ExecuteNonQuery();

Currently you are just executing one query. Semicolon ; marks end of statement in SQL, so combining these statements with ; will make them separate statements but they will be executed under one execution.
kcray - This is what worked for me.
 string[] arr = { query2, query3 };
 string allQueries = string.Join(";", arr);
 command.CommandText = allQueries;
 int c = command.ExecuteNonQuery();

A: You are executing only the query2 not the query3 and query4 command text
OpenConnection2();
command.Connection = connection;

command.CommandText = query2;
int c = command.ExecuteNonQuery();

command.CommandText = query3;
c = command.ExecuteNonQuery();

command.CommandText = query4;
c = command.ExecuteNonQuery();
connection.Close();

Said this, really you should use parameters also if you don't have concerns of Sql Injection because your code will be more clear and you don't need to worry about parsing strings to replace quotes, prepare the correct string for datetime field and use the correct decimal point character for floating point values
Another optimization is through the using statement.
In this case your OpenConnection2 should return the OleDbConnection created and opened and no need to use a global connection object (Always a bad practice also with file based databases)
public OleDbConnection OpenConnection2()
{
    OleDbConnection connection = new OleDbConnection("");
    connection.Open();
    return connection;
}

and then in your code you will be able to use the using statement that will ensure the correct close and dispose of the connection when is no more needed
using(OleDbConnection cn = OpenConnection2())
using(OleDbCommand command = new OleDbCommand())
{
    command.Connection = connection;
    command.CommandText = query2;
    int c = command.ExecuteNonQuery();

    command.CommandText = query3;
    c = command.ExecuteNonQuery();

    command.CommandText = query4;
    c = command.ExecuteNonQuery();
} // here the connection will be closed and disposed

As a last note, if you are running these queries against an MS Access Database then you need to execute them one by one because there is no support for multistatement

A: UNION your SELECT statements together to insert multiple rows into the same table.
INSERT INTO dbo.Products (ID, [Name])
SELECT 1, 'Car'
UNION ALL
SELECT 2, 'Boat'
UNION ALL
SELECT 3, 'Bike'

A: It is not possible to execute multiple queries in on OledbCommand. You have 2 options here

*

*Make a stored procedure

*call them one by one.

OR
As you are inserting in only one table so In your case though you can Design your query like this (just an example)
INSERT INTO ACH (rptid, tableid, name, amount, stat, create_date)
SELECT 1,1, 'Value3',2,2,DateTime.Now.ToString()
UNION
SELECT 1,1, 'Value3',2,2,DateTime.Now.ToString()
UNION
SELECT 1,1, 'Value3',2,2,DateTime.Now.ToString()
UNION
SELECT 1,1, 'Value3',2,2,DateTime.Now.ToString()


text:
Q: I want to convert an python output list to an array from os import name
import xml.etree.ElementTree as ET
from pathlib import Path

def getNameFromXML():
    for path in Path(".").rglob("*.nfo"):
        tree = ET.parse(path.name)
        root = tree.getroot()

        movieDate = root[4].text.replace("-", ".")
        movieName = root[1].text.replace(" ", ".").replace(".-", "") # Replace spaces and slash to "."
        movieQuality = "1080p" # Movie quality
        movieExt = ".mp4" # Movie Ext
        fullMovieName = "Company." + movieDate + "." + movieName +  "." + movieQuality + movieExt

        print(fullMovieName) # This prints the list

The output is this:
# Output in console
Company.00.00.00.moviename.1080p.mp4
Company.00.00.00.moviename.1080p.mp4
Company.00.00.00.moviename.1080p.mp4

I want to convert that in an array to let me grab every one in a "for"

A: Is this what you are looking for?
from os import name
import xml.etree.ElementTree as ET
from pathlib import Path

def getNameFromXML():
    myList=[]
    for path in Path(".").rglob("*.nfo"):
        tree = ET.parse(path.name)
        root = tree.getroot()

        movieDate = root[4].text.replace("-", ".")
        movieName = root[1].text.replace(" ", ".").replace(".-", "") # Replace spaces and slash to "."
        movieQuality = "1080p" # Movie quality
        movieExt = ".mp4" # Movie Ext
        fullMovieName = "Company." + movieDate + "." + movieName +  "." + movieQuality + movieExt

        myList.append(fullMovieName)

    return myList

myList = getNameFromXML()
print(myList)
print(myList[1])

You can create a list and return it from the function, then use it like "array".
You can learn about Lists in Python from documentations.


text:
Q: Failed to schedule Software Protection service for re-start at 2119-10-19T18:07:58Z. Error Code: 0x80041316 our Windows Server 2012 Essentials is getting evenvwr poluted with the error message bellow and attached every 30 seconds. I've done a lot of research but nothing worked so far, this is what I tried:

*

*Check the NETWORK SERVICE permissions on C:\Windows\System32\Tasks\Microsoft\Windows (it has FULL CONTROL)

*checked services and its dependencies and ensure they are running and have startup mode = automatic

*checked windows license with slmgr /ato

*started and stopped sppsvc service with net stop sppsvc/ net start sppsvc
This is our domain controler so I can't reinstall Windows - Any help please?
Log Name:      Application
Source:        Microsoft-Windows-Security-SPP
Date:          11/12/2019 1:07:58 PM
Event ID:      16385
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      DC20001811
Description:
Failed to schedule Software Protection service for re-start at 2119-10-
19T18:07:58Z. Error Code: 0x80041316.
Event Xml:
Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event":
System:
 Provider Name="Microsoft-Windows-Security-SPP" Guid="{E23B33B0-C8C9-472C-A5F9-F2BDFEA0F156}" EventSourceName="Software Protection Platform Service" :

 EventID Qualifiers="49152": 16385 EventID:

 Version: 0 Version:

 Level: 2 Level:

 Task: 0 Task:

 Opcode: 0 Opcode:

 Keywords: 0x80000000000000 Keywords:

 TimeCreated SystemTime="2019-11-12T18:07:58.000000000Z" :

 EventRecordID: 4441021 EventRecordID:

 Correlation :

 Execution ProcessID="0" ThreadID="0" :

 Channel: Application Channel:

 Computer: Andromeda.snapd.local Computer:

 Security :

System:
EventData:
 Data: 0x80041316 Data:

 Data: 2119-10-19T18:07:58Z Data:

EventData:
Event:
enter image description here
NETWORK SERVICE account has Read permissions
Service is set to use the NETWORK SERVICE account 2
Service is set to use the NETWORK SERVICE account
Task Scheduler service is running

A: This series of steps worked for me.  It is an abbreviated version of this solution.

*

*Back up all files in the directory C:\Windows\System32\Tasks\Microsoft\Windows\SoftwareProtectionPlatform just in case

*Add an XML extension to the files in the SoftwareProtectionPlatform folder

*Navigate to to Computer Management->System Tools->Task Scheduler->Task Scheduler Library->Microsoft->Windows->SoftwareProtectionPlatform

*Right-click on each task and select Delete

*Right-click on SoftwareProtectionPlatform, Import Task, and import each of the files that you renamed.  Don't worry if they don't appear in the Task List.

*Navigate to Computer Management->Services and Applications->Services and restart the Software Protection service

*Check the Event Viewer to verify that the errors have stopped

*Delete the XML files in the SoftwareProtectionPlatform folder


text:
Q: PHP page access without extension and variable How can I create a PHP page system that we access without .php extension and without ?page= variable?
There's a simple exemple:
http://www.exemple.com/portfolio/1

Instead of:
http://www.exemple.com/portfolio.php?id=1

It would be great for me because I'm a web designer and this is a thing I never did. So it would be good to know this! Also I will use this in my website.

A: you would need the following in your .htaccess file:
Options +FollowSymLinks

RewriteEngine On

RewriteCond %{REQUEST_URI} ^(.*[^/])/?$
RewriteCond %{DOCUMENT_ROOT}%1.php -f
RewriteRule .+ %1.php [QSA,L]

A: You're looking for mod_rewrite.
RewriteEngine On
RewriteRule ^/profile$ /account.php?profile [L]

A: You can use multiviews, or better and more used: mod_rewrite module from apache. It can be via a .htaccess file where you create rewrite rules like
RewriteEngine On
RewriteRule ^(.*)?(.*)$  /$1.php?Action=$2 [L]

A: Create .htaccess file in your web root and enter following.
Options +FollowSymLinks
RewriteEngine on

RewriteRule ^account/([0-9]+)$ account.php?id=$1

OR
See mod_rewrite, in case URL rewriting, if you trying to do such.


text:
Q: .NET compatibility issues with Visual Studio 2013 Express solution I have a problem when referencing a DLL.
I do everything correctly:
1.The DLL is built with no errors
2.I add it as a reference in my other solution
However the system doesn't recognize it and I get the folowing error message:
"Type or namespace could not be found.Are you missing an assembly reference?"
I read on various forums and adjusted the .NET version of the DLL to match the .NET 4 on my project.I tried all versions 4/4-Client Profile/4.5 and none of them fixed the problem.The DLL,I checked with .NET Reflector and everything is there and working as it's supposed to.
Can you help me with this issue?


text:
Q: Initialize New Relic JavaScript code with Angular 9 I am using New Relic Javascript code snippet to integrate New Relic in my Angular 9 app.
Everything works fine when I add this script tag in the head of my index.html page.
The problem:
This JavaScript code snipped has some keys like applicationID and licenseKey which are hardcoded.
I want to externalize these keys and want to pick them from the environment.ts file.
But I am unable to find the way through which I can achieve this.
I tried putting this JavaScript code in ngOnInit of my app.component.ts but it shows typescript errors.
I have another solution in my mind: set the keys in the session storage and after that load that code snippet dynamically so that it can access session storage and get the data from it. If it is a recommended approach, please guide me.
Please suggest if there is any workaround.
Thanks for your time.


text:
Q: Discrete Math - Show Logically $X$ beat $Y$ exactly 2 Times I was given a statement that I need to show logically. The question is #6 on this page. I have figured out the other 3 on my own but am stuck on this part of question:

Define the predicate $B(x, y)$ to mean that $x$ beat $y$ in the race. Give the logical expression equivalent to 'Sam beat exactly two people'.

I know that the use of a universal or existential quantifier is most likely required here but I am not sure how to write the expression "equal to two" in conjunction with them.
Any help would be greatly appreciated.

A: HINT: You want to say that there exist people $x$ and $y$ such that:

*

*Sam beat $x$;

*Sam beat $y$;

*$x$ and $y$ are not the same person; and

*for any person $z$, if Sam beat $z$, then $z$ is $x$ or $z$ is $y$.


text:
Q: Google contacts gdata (Java) fails on No parser for content type:application-xml[application/xml] Recently, a 2 days ago we started to experience exception in google gdata client in Java, when trying to access contacts (feed : /m8/feeds/contacts/default/full). The exception is :
com.google.gdata.util.ParseException: No parser for content type:application-xml[application/xml]
     at com.google.gdata.client.Service.parseResponseData(Service.java:2142)
     at com.google.gdata.client.Service.parseResponseData(Service.java:2098)
     at com.google.gdata.client.Service.getFeed(Service.java:1136)
     at com.google.gdata.client.Service.getFeed(Service.java:1077)
     at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:676)
     at com.google.gdata.client.Service.getFeed(Service.java:1034)

Did some sniffing with Wireshark and in the google documentation I see that correct responses should come with Content type : application/atom+xml but failed responses from google now coming with Content Type : application/xml.
Seems that something changed in google, and now it's returnes not correct content type and our code stopped to work (it was working fine for few years).
Need to say that part of the google app tenants (our customers) still working fine (with the same code) , but some parts of the customers is failing.
Is there any possible workaround for that issue ?
Thanks

A: The problem was fixed on Google side, so there is nothing to do on our side.


text:
Q: How to emit signal, when user changes row with keyboard arrows in tableView? I have two tableViews, in one I load album names, in the other I want to load tracks from selected album.
Problem is simple: I can't use signals such as activated, mouse clicked, etc. I want to change stuff in the tracks tableView simply by the highlighting row in the album names tableView.
Summary: emit signal when user changes row and find out on which row he is now.

A: See the Handling selection of items section in the Qt Model/Views documentation.
In essence, what you need to use is your QTableView's selection model which has signals for when the selection changes in the table. You access the view's selection model via it's selectionModel() member function.

A: Ok,so i have solved this problem like this:
First, you must obtain QItemSelectionModel !after! the table was filled:
QItemSelectionModel *select = ui->tableView->selectionModel();
Then connect SIGNAL "selectionChanged" with you own SLOT function:
connect(select, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
        this, SLOT(change_table()));


text:
Q: Multi-boot: Windows 10 cannot see one ntfs drive On a computer normally running Windows 7 (sda4) and Linux (Mint, sda5) in dual-boot, I have created two separate partitions (sda6 and sda7) within the same extended partition (sda3) as the Mint installation (sda5), in order to install other operating systems for test purposes , especially Linux, but also Windows 10 Technical Preview.
So, there are 5 main partitions, one for each operating system installed, and one separate ntfs partition (created with the initial Windows 7 installation). In Linux, the Gparted program shows the partitions like this:

So, Windows 10 (sda7) is inside the same extended partition (sda3) as Mint (sda5) and another Linux (Xubuntu-based Voyager on sda6), while Windows 7 on sda4 is outside the extended partition sda3.
In Mint (Thunar file manager) all drives are visible:

In Windows 7 (sda4), as expected, the ext4 drives of the Linux systems are not visible, but all ntfs drives are:

But in Windows 10 (sda7), one ntfs drive (sda2) is not accessible:

Why is that?
Is it because Windows 10 is inside an extended partition while the big ntfs drive (sda2) that is not accessible is outside that extended partition? But Windows 7 sda4 partition is also outside it and is still visible from Windows 10.
Could it be because sda2 is before the extended partition in which Windows 10 is installed? --- (sda2 is also before the Windows7 sda4 partition, from which it is still visible, but maybe what counts is also the difference that sda4 is not inside an extended partition...)
Windows 10 was the last system installed and that resulted in it being the only bootable system, so I had to repair (remove and reinstall) the grub from a Linux live usb.

A: This is old post now but most probably the problem was that the unaccessible drive had no propper letter assigned.
Computer management - Disk Management
Right-click the drive that you want to change, and then click Change Drive Letter and Paths.

To assign a drive letter if one has not already been assigned, click Add, click the letter that you want to use, and then click OK.


text:
Q: move assignment not called for vector element I am new to c++11 and I am trying to experiment with move semantics and rvalue function parameters.
I do not understand why the following code won't compile:
class MatchEntry
{
  unique_ptr<char []> key;

public:
  MatchEntry() {}

  MatchEntry(const char *key_bytes, int key_nbytes) {
    char *data = new char[key_nbytes];
    copy(key_bytes, key_bytes + key_nbytes, data);
    key = unique_ptr<char []>(data);
  }

};

void add_entry(vector<MatchEntry> v, MatchEntry&& e, int index) {
  v[index] = e;
}

class MatchEntry has a unique_ptr member and therefore no implicit copy assignment operator can be generated by the compiler. However a move assignment operator is generated. The add_entry function takes a rvalue reference to a MatchEntry and therefore I expected the move assignment to be called. But I get the following error when I try to compile:
gg.cpp: In function 'void add_entry(std::vector<MatchEntry>, MatchEntry&&, int)':
gg.cpp:57:12: error: use of deleted function 'MatchEntry& MatchEntry::operator=(const MatchEntry&)'
   v[index] = e;
            ^
gg.cpp:32:7: note: 'MatchEntry& MatchEntry::operator=(const MatchEntry&)' is implicitly deleted because the default definition would be ill-formed:
 class MatchEntry
       ^
gg.cpp:32:7: error: use of deleted function 'std::unique_ptr<_Tp [], _Dp>& std::unique_ptr<_Tp [], _Dp>::operator=(const std::unique_ptr<_Tp [], _Dp>&) [with _Tp = char; _Dp = std::default_delete<char []>]'
In file included from /usr/include/c++/4.9/memory:81:0,
                 from gg.cpp:1:
/usr/include/c++/4.9/bits/unique_ptr.h:599:19: note: declared here
       unique_ptr& operator=(const unique_ptr&) = delete;

A: Before directly discussing the compilation error, you should definitely take v by reference in this fuction.
void add_entry(vector<MatchEntry> &v, MatchEntry&& e, int index) {
                         //       |
                         //       `--- by reference here
  v.at(index) = std::move(e);
}

Anyway, the problem is the e is an lvalue, and therefore the assignment was trying to use copy assignment instead of move assignment. A named variable is always an lvalue, regardless of whether its type is MatchEntry or MatchEntry& or MatchEntry&&. Of course, we know that the object referenced by e was an rvalue, and therefore we can use move to tell the compiler to treat e as an rvalue.
(Unrelated: but I always like to access vectors with .at(index). It's safer due to the bounds-checking.)


text:
Q: Failures of categoricity not related to size? The paradigmatic cases I know of theories failing to be categorical are cases that seem tied to the language's inability to distinguish between different infinite cardinalities of the theories domain. For example, first-order Peano arithmetic fails to be categorical at least because of the Upward Löwenheim-Skolem theorem. The theory's models should have a cardinality of $\aleph_0$, but if it is has a model of $\aleph_0$ it has a model of every infinite cardinality, and so it has larger models as well (the non-standard ones).
In second-order $\mathsf{PA}$, however, it has access to resources of set theory in the semantics and so can distinguish between models of different infinite cardinalities (i.e., the Löwenheim-Skolem theorems fail in a second-order setting). So second-order $\mathsf{PA}$ gets to be categorical---its models all have cardinality $\aleph_0$.
Second-order $\mathsf{ZFC}$ isn't categorical, but it's almost-categorical, meaning $\mathcal{M} = \langle D, \in \rangle$ is a model of second-order $\mathsf{ZFC}$ iff there is an (strongly) inaccessible cardinal $\kappa$ such that $\mathcal{M}$ is isomorphic to $V_k$. In my understanding, since the Full Semantics for second-order logic relies on set theory (and assuming that set theory is $\mathsf{ZFC}$), both set theory and (consequently) second-order logic lose the ability to discriminate between inaccessible cardinals. Again, we have a failure of categoricity related to the background logic's inability to distinguish certain cardinalities [Side question: in the first-order setting we can blame this failure on the Löwenheim-Skolem theorems; what is the analogous result that we blame the inability to distinguish certain cardinalities on in a second-order setting?].
Are all failures of categoricity related to size like the examples above? Are there examples of theories that fail to be categorical in ways wholly unrelated to the size of their models?

A: Consider a group axiom, coupled with the axiom "There are exactly six objects". This is not categorical, because there are two non-isomorphic six-element groups (the symmetric group and the cyclic group).


text:
Q: Value is not updating after deleting an input value I just implemented a swipe to delete function in my code, and it works perfectly. However, it does not update my current calculation which is based on the the values in the tableview. The tableview reloads but, the number in the label does not recalculate.
Once I move to a different tab and come back the label is reloaded to the right amount, but that is due to a reloadsections in segmented controller. How can I reload the data in the text in my label?
Code Snippet is given below:
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    FoodEntry *foodEntry = [[StorageController sharedInstance] entriesForEssential:self.displayEssential][indexPath.row];
    [[StorageController sharedInstance] removeFoodEntry:foodEntry forEssential:self.displayEssential];
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        [self.tableView reloadData];
        self.currentPlaceHolder.text ????
        }
}


text:
Q: Open PSA: SQLSTATE[08006] [7] fe_sendauth: no password supplied | postgresql I am trying to setup OpenPSA in my system... Using this link.
I am using postgres as a database for this. I followed the initial steps & stuck with couple of errors of postgres. I tried couple of links to resolve this error. But, its not working. It shows this error when i execute the command and input the path to config file.
I am trying to execute this command:
 sudo ./vendor/bin/midgard-portable schema

I am giving the correct path to the config. file.
I am not able to find any clue regarding the error.
Here is my midgard-portable-default.inc.php file:
<?php
use midgard\portable\driver;
use midgard\portable\storage\connection;

$basedir = dirname(__DIR__);

require_once $basedir . "/vendor/autoload.php";

$schema_dirs = [$basedir . '/schemas/'];

$driver = new driver($schema_dirs, $basedir . '/var', '');

// CHANGE PARAMETERS AS REQUIRED:
$db_config = [
    'memory' => true,
    'driver' => 'pdo_pgsql',
];

connection::initialize($driver, $db_config, true);

Thanks

A: Similar problem here (using the MySQL driver).
As the syntax of config/midgard-portable.inc.php does not seem to be documented, and there are no  instructions on how to specify a password.
I found the following sample in openpsa/vendor/doctrine/orm/docs/en/reference/configuration.rst:
    // the connection configuration
    $dbParams = array(
        'driver'   => 'pdo_mysql',
        'user'     => 'root',
        'password' => '',
        'dbname'   => 'foo',
    );

Tried to duplicate the syntax and finally got the OpenPSA start page loading.
Steps to follow:

*

*cd config

*cp ./midgard-portable-default.inc.php midgard-portable.inc.php

*edit the midgard-portable.inc.php by adding 3 lines of code (user, password and dbname) like this:

// CHANGE PARAMETERS AS REQUIRED:
$db_config = [
    'memory' => true,
    'driver' => 'pdo_mysql',
    'user'     => 'db-username',
    'password' => 'db-password',
    'dbname'   => 'db-name',
];

Previously tried the following steps (probably not necessary to follow), yet I'm leaving them here for reference:
The ./vendor/bin/openpsa-installer midgard2:setup prompted for a username, password and DB name, and if I want to "Use existing configuration file midgard-portable.inc.php"
Specifying the parameters and refusing to use the existing file, got me moving forward. Instead of connection errors I got an "Unknown database" error.


text:
Q: Google Docs: converting distance units I'm trying to have a function for a Google Docs Document that will search the whole text for a number followed by the abbreviation "km.", pass the value of this number to a variable and multiply it, and replace the original text with the new variable plus "mi."
Basically, if there's some part in the text that reads "10km.", I'd need it to convert to "6.2mi."
So far I have this:
function replaceKmToMi(){
var body = DocumentApp.getActiveDocument().getBody();
var kilometers = body.findText("\\d+" + "km.");
var km = parseInt(kilometers);
var mi = km / 1.609;
var miles = mi + "mi."
body.replaceText(kilometers, miles);
}

What am I doing wrong?


text:
Q: How to remove the undefined/null from array inside the array in angular DATA = [{
    application: [{
        name: 'Room1'
    },{
        name: 'Room2'
    },{
        name: 'Room3'
    },{
        name: 'Room4'
    },{
        name: 'Room5'
    }, , undefined, null, null],
    name: 'Batch 1',
    date: '2020-10-20'
}]

What I'm trying to do here is to remove the undefined/null from the array.
the undefined/null should be remove.
output should be like this:
 [{
    application: [{
        name: 'Room1'
    },{
        name: 'Room2'
    },{
        name: 'Room3'
    },{
        name: 'Room4'
    },{
        name: 'Room5'
    }],
    name: 'Batch 1',
    date: '2020-10-20'
}]

it will remove the null or undefined

A:

DATA = [{
    application: [{
        name: 'Room1'
    },{
        name: 'Room2'
    },{
        name: 'Room3'
    },{
        name: 'Room4'
    },{
        name: 'Room5'
    }, , undefined, null, null],
    name: 'Batch 1',
    date: '2020-10-20'
}]

DATA[0].application = DATA[0].application.filter(i=> i);
console.log(DATA)

A: You could use the Array.prototype.filter method to keep only !!item (i.e. not-null, not-undefined, not-empty, not-false and not-zero items).

let DATA = [{
  application: [{
    name: 'Room1'
  }, {
    name: 'Room2'
  }, {
    name: 'Room3'
  }, {
    name: 'Room4'
  }, {
    name: 'Room5'
  }, , undefined, null, null],
  name: 'Batch 1',
  date: '2020-10-20'
}];
DATA[0].application = DATA[0].application.filter(item => !!item);
console.log(DATA);


text:
Q: How can I suspend using a keyboard shortcut, without administrator privileges? How can I set up a keyboard shortcut that I can use instead of clicking this menu item?

I have read about various terminal commands for suspending which I could easily assign to a keyboard shortcut, but all have required the use of sudo. I am looking for a solution that I can use on a system where I do not have administer privileges.

A: Same as above, but use this command instead:
dbus-send --system --print-reply --dest=org.freedesktop.login1 /org/freedesktop/login1 "org.freedesktop.login1.Manager.Suspend" boolean:true

Source: http://forum.ubuntu-fr.org/viewtopic.php?pid=16497311#p16497311

A: For Ubuntu 15.04. and later you can use from the terminal
systemctl suspend

Then create a shortcut in the settings/keyboard app with the same command.

Easy!
Reason: Ubuntu switched from upstart to systemd.

A: *

*Install the powermanagement-interface  package first, it provides the pmi command we will use to suspend.
UPDATE: I looked at the source for pmi and the command it uses to suspend is:
dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend

If you can't install pmi, replace pmi action suspend with that command in the next step.

*Open up System -> Preferences -> Keyboard Shortcuts, click on Add and put pmi action suspend as the command.

*Click on the newly created shortcut entry, and set the shortcut keys.

A: With Ubuntu 16.04 LTS an newer I would suggest using systemctl instead because newer systems use systemd to control things.
The safe command to run is systemctl suspend which suspends the machine immediately unless some process is asking the system to stay powered (e.g. video player showing a movie, active CD burner, another logged in user doing anything, etc).
If you want to force suspend immediately and ignore all "inhibitors" simply add -i as explained by the output of the above command.
If you want to immediately lock the screensaver and suspend the system in all cases, you can run
loginctl lock-session && systemctl suspend -i

This is better than using raw dbus to send messages because using loginctl and systemctl avoids hardcoding any info about your screensaver or session manager.

A: systemctl suspend -i worked for me.
Mapped to super+d in the Keyboard settings custom shortcuts.


text:
Q: gSOAP wsse plugin - what is the proper procedure for signing requests? I'm using gSOAP (2.8.16 - yes it's old) to develop a C++ client on RHEL that talks to a service that requires messages to be digitally signed.  The signature is based on a wsu:Timestamp element.  I'm using an X509 (PEM) certificate with an RSA private key.  Client was generated using
wsdl2h -g -e -o client-pre.h -t$SOAPHOME/WS/WS-typemap.dat -v $WSDL
sed -f add-imports client-pre.h > client.h # adds import statements for WS-Header.h, dom.h, and wsse.h
soapcpp2 -d ../ -A -L _c -w -j -I $SOAPHOME/import -x -n client.h

Based on the Genevia documentation, the following code should be sufficient (not actual code, but representative of it - error handling omitted to save space):
ServiceSOAPProxy client;
...
soap_register_plugin( client.soap, soap_wsse );
...
soap_ssl_client_context( client.soap, SOAP_SSL_DEFAULT, pemfile, pwd, cafile, NULL, NULL );

_ns__RequestType *req = soap_new__ns__RequestType( cpClient.soap );
// set request parameters

RSA *rsakey = PEM_read_RSAPrivateKey( fp, NULL, NULL, (void *) pwd );
...
X509 *cert = PEM_read_X509( fp, NULL, NULL, NULL );
...
soap_wsse_add_Timestamp( client.soap, timeid.c_str(), duration );

if ( soap_wsse_add_BinarySecurityTokenX509( client.soap, tokid.c_str(), cert ) != SOAP_OK ||
     soap_wsse_add_KeyInfo_SecurityTokenReferenceX509( client.soap, ("#" + tokid).c_str()) != SOAP_OK ||
     soap_wsse_sign( client.soap, SOAP_SMD_SIGN_RSA_SHA256, rsakey, 0 ) != SOAP_OK ||
     soap_wsse_sign_only( client.soap, ("#" + timeid).c_str() ) != SOAP_OK )
{
  soap_print_fault( client.soap, ::stderr );
  // handle error
}

ns__ResponseType *rsp = soap_new_ns__ResponseType( client.soap );
cpClient.SendRequest( req, rsp );

Unfortunately, the signature isn't complete - there's no SignatureValue, there's no SignedInfo, etc., just the SecurityTokenReference:
  <ds:Signature>
    <ds:KeyInfo>
      <wsse:SecurityTokenReference>
        <wsse:Reference URI="#BST-a9ec4d98-41c0-11e9-961e-0e5b675ed876" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
      </wsse:SecurityTokenReference>
    </ds:KeyInfo>
  </ds:Signature>

None of the soap_wsse* methods return an error, but either I'm missing a step or something hasn't been set up properly.  There is absolutely nothing in the Genevia documentation that even hints at what I'm doing wrong.
What step am I missing?
EDIT
It turns out I was passing the wrong tag for the timestamp - I was using the reference URI with the leading # (("#" + time_id).c_str()), which was why nothing was being added to the signature.
When I use the correct tag (time_id.c_str()), I get a segfault - somehow, soap->attributes gets set to a bad value.  I set a watch on the soap->attributes member in a gdb session and get the following:
Old value = (soap_attribute *) 0x0
New value = (soap_attribute *) 0x9bf1a0
0x00000000005f2d49 in soap_set_attr (soap=0x7ffff7fb7010, name=0x7ffff7fd35d0 "xmlns:SOAP-ENV", value=0x9bf131 "http://schemas.xmlsoap.org/soap/envelope/", flag=1) at stdsoap2.cpp:10456

Old value = (soap_attribute *) 0x9bf1a0
New value = (soap_attribute *) 0xa1aaa0
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0xa1aaa0
New value = (soap_attribute *) 0x9eca10
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x9eca10
New value = (soap_attribute *) 0x9bf3b0
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x9bf3b0
New value = (soap_attribute *) 0x9c4570
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x9c4570
New value = (soap_attribute *) 0x9ec740
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x9ec740
New value = (soap_attribute *) 0xa1a960
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0xa1a960
New value = (soap_attribute *) 0x9ec690
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x9ec690
New value = (soap_attribute *) 0x9b9f30
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x9b9f30
New value = (soap_attribute *) 0x9bf300
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x9bf300
New value = (soap_attribute *) 0x0
soap_clr_attr (soap=0x7ffff7fb7010) at stdsoap2.cpp:10510

Old value = (soap_attribute *) 0x0
New value = (soap_attribute *) 0x2000000000000
soap_smd_begin (soap=0x7ffff7fb7010, alg=10, key=0x95b150, keylen=0) at smdevp.c:373

Why in the world is this happening?