text:
Q: How can I automatically resize wibar? I have configured wibar so that the output is updated automatically. But there is a problem that the output can go beyond the borders of wibar. All the solutions I came up with don't work very well. How can I solve this problem?
Example:
Unfortunately, I can't insert an image until I have 10 reputations. I can only leave a link to the question on github where there is an image showing the problem.
Code:
mycpu = wibox.widget { widget = wibox.widget.textbox }

mycputemp = wibox.widget { widget = wibox.widget.textbox }

myram = wibox.widget { widget = wibox.widget.textbox }

mybattery = wibox.widget { widget = wibox.widget.textbox }

myupdates = wibox.widget {
   markup = "  . ",
   widget = wibox.widget.textbox
}

mykeyboardlayout = awful.widget.keyboardlayout()
mykeyboardlayout_icon = wibox.widget {
   markup = " ",
   widget = wibox.widget.textbox
}

mytextclock = wibox.widget {
   format = ' %H:%M ',
   widget = wibox.widget.textclock
}
mytextclock_icon = wibox.widget {
   markup = " ",
   widget = wibox.widget.textbox
}

awful.screen.connect_for_each_screen(function(s)
      s.mywibox = awful.wibar {
         screen  = s,
         align   = "right",
         margins = {
            top   = 14,
            right = 14
         },
         width   = 586,
         height  = 42,
         bg      = "#1c252acc",
         widget  = {
            {
               layout = wibox.layout.fixed.horizontal,
               expand = "none",
               mycpu,
               mycputemp,
               myram,
               mybattery,
               myupdates,
               mykeyboardlayout_icon,
               mykeyboardlayout,
               mytextclock_icon,
               mytextclock
            },
            widget = wibox.container.margin
         }
      }
end)

gears.timer {
   timeout   = 1.5,
   call_now  = true,
   autostart = true,
   callback  = function()
      awful.spawn.easy_async_with_shell("cpu",
                                        function(out)
                                           cpu_out = "  " ..
                                              out:gsub("%\n", "") .. " "
      end)
      awful.spawn.easy_async_with_shell("cat /sys/class/hwmon/hwmon3/temp1_input",
                                        function(out)
                                           mycputemp.markup = "  " ..
                                              math.floor(tonumber(out)/1000+0.5) .. "°C "
      end)
      awful.spawn.easy_async_with_shell("ram",
                                        function(out)
                                           ram_out = "  " ..
                                              out:gsub("%\n", "") .. " "
      end)
      awful.spawn.easy_async_with_shell("cat /sys/class/power_supply/BAT1/capacity",
                                        function(out)
                                           bat_out = "  " ..
                                              out:gsub("%\n", "") .. "% "
      end)
      mycpu.markup     = cpu_out
      myram.markup     = ram_out
      mybattery.markup = bat_out
   end
}

A: The best solution I could find was to use awful.popup instead of awful.wibar.
mycpu = wibox.widget { widget = wibox.widget.textbox }

mycputemp = wibox.widget { widget = wibox.widget.textbox }

myram = wibox.widget { widget = wibox.widget.textbox }

mybattery = wibox.widget { widget = wibox.widget.textbox }

myupdates = wibox.widget {
   markup = "  . ",
   widget = wibox.widget.textbox
}

mykeyboardlayout = awful.widget.keyboardlayout()
mykeyboardlayout_icon = wibox.widget {
   markup = " ",
   widget = wibox.widget.textbox
}

mytextclock = wibox.widget {
   format = ' %H:%M ',
   widget = wibox.widget.textclock
}
mytextclock_icon = wibox.widget {
   markup = " ",
   widget = wibox.widget.textbox
}

awful.screen.connect_for_each_screen(function(s)
      s.mywibox = awful.popup {
         screen  = s,
         placement = function(c)
            return awful.placement.top_right(c, { margins = 14 })
         end,
         minimum_height = 42,
         bg      = "#1c252acc",
         widget  = {
            {
               layout = wibox.layout.fixed.horizontal,
               expand = "none",
               mycpu,
               mycputemp,
               myram,
               mybattery,
               myupdates,
               mykeyboardlayout_icon,
               mykeyboardlayout,
               mytextclock_icon,
               mytextclock
            },
            widget = wibox.container.margin
         }
      }

      s.mywibox:struts({top = s.mywibox.minimum_height + beautiful.useless_gap * 2})
end)

gears.timer {
   timeout   = 1.5,
   call_now  = true,
   autostart = true,
   callback  = function()
      awful.spawn.easy_async_with_shell("cpu",
                                        function(out)
                                           mycpu.markup = "  " ..
                                              out:gsub("%\n", "") .. " "
      end)
      awful.spawn.easy_async_with_shell("cat /sys/class/hwmon/hwmon3/temp1_input",
                                        function(out)
                                           mycputemp.markup = "  " ..
                                              math.floor(tonumber(out)/1000+0.5) .. "°C "
      end)
      awful.spawn.easy_async_with_shell("ram",
                                        function(out)
                                           myram.markup = "  " ..
                                              out:gsub("%\n", "") .. " "
      end)
      awful.spawn.easy_async_with_shell("cat /sys/class/power_supply/BAT1/capacity",
                                        function(out)
                                           mybattery.markup = "  " ..
                                              out:gsub("%\n", "") .. "% "
      end)
   end
}


text:
Q: Unable to download ... from localhost. Unable to open this Internet site. The requested site is either unavailable or cannot be found I'm trying to make a default error page for each important http error by adding the following to the web.xml file;
<error-page>
  <exception-type>java.sql.SQLException</exception-type>
  <location>/error-mantenimiento.xhtml</location>
 </error-page>
 <error-page>
  <error-code>401</error-code>
  <location>/error-mantenimiento.xhtml</location>
 </error-page>
 <error-page>
  <error-code>403</error-code>
  <location>/error-mantenimiento.xhtml</location>
 </error-page>
 <error-page>
  <error-code>404</error-code>
  <location>/error-mantenimiento.xhtml</location>
 </error-page>
 <error-page>
  <error-code>500</error-code>
  <location>/error-mantenimiento.xhtml</location>
 </error-page>
 <error-page>
  <error-code>503</error-code>
  <location>/error-mantenimiento.xhtml</location>
 </error-page>

It does work on firefox or chrome when I try using a fake url, by throwing http 404 error. But on IE6 thru IE8 I get "Unable to download ... from localhost. Unable to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later."
I search this error on the internet, and some people report to have fixed it by enabling or disabling "Do not save encrypted pages to disk" on the security tab. Y try this option enabled and disabled and it keep throwing same error.
  Also I tried be adding or removing http header tags

as they do on other posts but I get the same IE6 error. The error page does work on IE9 and above.
The web server I use is JBOSS 4.0.3.
As far as I know they dont want to switch browser, and this issue will remain open.
Also we tried by modifying the following records on the windows registry
BypassHTTPNoCacheCheck   doubleword   0x00000001
BypassSSLNoCacheCheck    doubleword   0x00000001

But didnt work... :S
Any clues on this?
Regardsss

A: I was having this same issue and stumbled across your question. After researching it a bit further though I was able to find this question as well: IE : Unable to download * from *. Unable to open this Internet site. The requested site is either unavailable or cannot be found
If you are running your website over SSL then try setting the header content for the following properties:
Cache-Control: private
Pragma: token
I believe you can set this in xml using the following in your web.xml file:
<init-param>
    <param-name>Cache-Control</param-name>
    <param-value>max-age=172801, private</param-value>
</init-param>
<init-param>
    <param-name>Pragma</param-name>
    <param-value>token</param-value>
</init-param>

Though I am not terribly familiar with JBOSS. I hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RegisterClassEx invalid parameter on 64bit (but working on 32 bit) I've build a DLL that is compiled for 32 and 64 bit. The following snippet works for 32 bit, but doesn't for 64 bit (Error Code 87 - Invalid parameter)
const CHAR g_szClassName[] = "MyFancyDll";
...
WNDCLASSEX wndClass;
    wndClass.cbSize = sizeof(WNDCLASSEX);
    wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wndClass.lpfnWndProc = (WNDPROC) WinProcCallback;
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.hIcon = NULL;
    wndClass.hbrBackground = NULL;
    wndClass.lpszMenuName = NULL;
    wndClass.lpszClassName = g_szClassName;
    wndClass.hIconSm = NULL;
    if (!RegisterClassEx(&wndClass)) {
        DWORD error = GetLastError();
        printf("Error registering class: %d", error);
    }

The code is compiled using MinGW.
So why isn't this working for 64 bit?
The command line for 32 bit is (Extracted this from my makefile macros, so sorry for any typos):
...
gcc -m32 -g3 -c -static-libgcc -static-libstdc++ file.c -o file32.o
gcc -m64 -g3 -c -static-libgcc -static-libstdc++ file.c -o file64.o

g++ -m32 -shared --enable-stdcall-fixup -static-libstdc++ file32.o -o mydll32.dll
g++ -m64 -shared --enable-stdcall-fixup -static-libstdc++ file64.o -o mydll64.dll

A: Your code is leaving uninitialized memory and that might cause undefined behavior, make sure that every pointer/data is zero'ed out before proceeding setting your flags/pointers:
WNDCLASSEX wndClass;
memset(&wndClass, 0, sizeof(WNDCLASSEX));

or even better:
WNDCLASSEX wndClass = { 0 };


text:
Q: No hillshade effect when no-data area is on screen I'm facing this weird problem when hillshade effect partially brakes if a no-data area appears on screen.
If I move the area to hide it off screen, the hillshade effect works.
I tried changing symbology, colors,classes etc without change.


text:
Q: django many to many save admin I have a model like :
class MyModel(models.Model):
    name = models.CharField(max_length=100)
    type = models.ManyToManyField(Type, blank=True)

Here from admin I am adding MyModel.
What I want is if the type is not provided while saving then I want the type to be as default like Teacher
type Teacher has not been created. If the type is not provided I want to create the type and assign it if the type is not provided

A: According to documentation's example, you can override save_model like this:
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    def save_related(self, request, form, formsets, change):
        if not form.cleaned_data['type']:
            type, created = Type.objects.get_or_create(name="Teacher")
            form.cleaned_data['type'] = [type]
        form.save_m2m()
        for formset in formsets:
             self.save_formset(request, form, formset, change=change)


text:
Q: create a firewall exception using a batch file I am trying to make an automatic LAN joiner for a LAN party I am having but I need to know how to create a firewall exception for the games.exe?
The file location that need an exception is: lanparty\exes\halo4.exe

A: If you're talking about the windows firewall use:
Netsh Firewall

Type:
Netsh Firewall /?

From the Command prompt to get the list of parameters
If you're using another software firewall, you need to specify which one.
If it's a hardware firewall you need to specify which one as well.
There really isn't enough information to answer this question accurately


text:
Q: Failed to execute 'postMessage', problem with autoplay youtube API Im trying do auto play in YT videos and received the msg below:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin ('http://localhost:8000').
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '360',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    playerVars: { 'autoplay': 1, 'controls': 0,  'Origin': 'http://localhost:8000'  },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange,
      'onError': onPlayerError
    },
    host: 'https://www.youtube.com'
  });
}

Ive tryed follow tips on internet using https, using playerVars {origin or Origin}, host but nothing was effective... Im receiving Cross-Origin Request Blocked. I enabled in httpd.conf with:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "X-Requested-With, Content-Type, X-Token-Auth, Authorization"

but still not working.


text:
Q: Verificar se a string é nula ou vazia Como eu faço para verificar se a minha variável é vazia ou nula?
// Inserção
Nome = tf_Nome.getText().toString();
Tipo = tf_Tipo.getText().toString();
Estoque = Integer.valueOf(tf_Estoque.getText().toString());
Preco = Double.valueOf(tf_Preco.getText().toString());

Não estou sabendo fazer como faço para que ele verifique se o Estoque e Preco são em branco ou nulo...
} else if(Nome != null && Tipo != null && **Estoque < 0 && Preco < 0**) {
    Estoque = 0;
    Preco = 0;

    BaseDados.InserirProdutos(Nome, Tipo, Estoque, Preco);
    Limpar();
    Toast.makeText(MainActivity.this, "Produto" +Nome+ " Adicionado com sucesso", Toast.LENGTH_SHORT).show();
}

A: Vou supor que a linguagem que você usa aí é Java.
Você já sabe comparar com nulo (por exemplo, Nome != null). Se a string não é nula, você pode ver seu comprimento através de seu método length.
Por exemplo:
int tamanho = Nome.length() // isso preenche tamanho com o comprimento de Nome.

Existe também o método isEmpty que retorna true se a string for vazia, e false caso contrário. Acho mais legível para o seu caso.
Você pode fazer algo do tipo:
public Boolean isStringUsable(string s) {
    return s != null && !s.isEmpty(); // lembre-se de que a comparação
                                      // com nulo sempre deve vir antes,
                                      // para evitar chamar métodos em instâncias nulas
}

O código acima é para o caso em que você quer variáveis preenchidas e não nulas. Se você quer o contrário, variáveis vazias ou nulas, é só fazer o negativo do que fiz acima:
public Boolean isNullOrEmpty(string s) {
    return s == null || s.isEmpty();
}

E passar suas strings para esse método.

A: Quando for realizar essa verificação em Strings, no Android utilize sempre o método isEmpty() da classe TextUtils do Android.
TextUtils.isEmpty(suaString);


text:
Q: analyze user input c++ I want to make program which analyzes every letter of the text which has been written by the user of the program. So for example, someone types "hello there". Is there a way to put all these letters in some array? For example, myArray[0]=h, myArray[1]=e,...
Thank you

A: You can use std::string just like an array, but it's dynamic, knows its size, and is a lot more flexible.
//string is like a dynamic array of characters
std::string input;

//get a whole line of input from stdin and store it
std::getline (std::cin, input);

//you can manipulate it like an array, among other things
input [0] = 'i'; //now "iello there"

For a complete reference on std::string, see here.


text:
Q: Write on PTM Master Pseudoterminal When we use the write() system call function to write on a ptm master, the pty_write() function will be triggered of because /dev/ptmx is a device file.
The write() prototype is :
ssize_t write(int fd, const void *buf, size_t count);

where fd is the file descriptor which has been obtained from the call to open /dev/ptmx.
The pty_write() prototype is :
int pty_write(struct tty_struct *tty, const unsigned char *buf, int c);

where tty is the ptm.
As you can see, both functions have a buffer and a number of bytes to write as parameters. but the third parameter is different. The write() function has a file descriptor and pty_write() function has tty structure.
How does the kernel link a file descriptor of write() function to the right tty (ptm) of pty_write() function?


text:
Q: My java programe doesn't loop So this is my first loop and when i execute it ,it says,
"Enter the price of item 1"
,and when i give it an input, it displays the output without looping even once
import java.util.Scanner;
public class Loop
{
    public static void main(String[] args)
    {
        Scanner input=new Scanner(System.in);

        int value;
        int sum=0;
        int number=1;
        while (number > 6);

        {
            System.out.println("Enter the price of item"+number);
            value = input.nextInt( );
            sum=sum+value;
            number=number+1;
        }

double vat=value*0.15;
double total=value+vat;
System.out.println("The Total cost is $"+value+" \n The Value added tax is $"+vat+"\n The total cost including Value Added Tax is $"+total);
      }
  }

can somebody please help me?

A: a couple of problems here
 int number=1;
 while (number > 6);

number is less than six so it would never enter
and
remove the semicolon after the while

A: You define
    int number=1;

And you test
   while (number > 6);
    {
    <some code>
    }

The condition is never met since number is 1.
There's also another problem: the semicolon after the while will lead to an infinite loop if you correct just the condition
Fixed code:
   while (number < 6)  // <- no semicolon & correct comparison
    {
        System.out.println("Enter the price of item"+number);
        value = input.nextInt( );
        sum=sum+value;
        number=number+1;
    }

A: It's because your number is not > 6 in the first place. So it would never satisfy the entering condition of the loop because clearly 1 is not greater than 6. Instead you want to loop while it is < 6. You also need to remove the ; after your while.
So try to replace with that:
int number=1;
while (number < 6)
{
    System.out.println("Enter the price of item"+number);
    value = input.nextInt( );
    sum=sum+value;
    number=number+1;
 }

A: You have bad while condition, change while (number > 6); to while (number < 6), remmeber to remove the ; after the while

A: Firstly, there is a semicolon after the while statement.
    while (number > 6);

Though it is not syntactically wrong but when you want to loop, the semicolon must be omitted.
Secondly, number is initialized to 1 and while loop checks whether 1 > 6, which is false.


text:
Q: Использование shared_ptr с очередью FreeRTOS Я использую контроллер ESP-32 и хочу передать std::shared_ptr, используя очередь FreeRTOS. Однако, при этом теряется один указатель. Вероятно, проблема кроется в этом куске кода:
{ // Начало функции
SoundControl ctrl;
…
ctrl.provider = sound; // +1 указатель (`sound` является константной ссылкой на std::shared_ptr)
…
xQueueSendToBack(queue, &ctrl, portMAX_DELAY); // ±0 указателей
} // Конец функции, -1 указатель

В результате стоящий в очереди указатель не считается, а его деструктор уменьшает счётчик ссылок на один.
Как можно решить эту проблему (продолжив использовать очереди FreeRTOS, если возможно)?

A: Судя по описанию xQueueSendToBack происходит простое копирование памяти объекта ctrl куда-то в очередь, причем счетчик на shared_ptr не увеличивается. Так делать с shared_ptr нельзя, что там происходит дальше я не знаю, но подозреваю что вы удаляете копию памяти на ctrl и отрабатывается деструктор shared_ptr, который уменьшает счетчик до нуля.


text:
Q: Map not applying to loaded Obj This follows on from my previous question here. I'm just trying to apply a different texture to each side of this obj but nothing appears. There are no console errors and I believe I'm applying things in the right order.
This should be quite simple to do but I've been struggling with it for the past hour. Here's a code sample below:

(function onLoad() {
  var canvasElement;
  var width, height;
  var scene, camera;
  var renderer;
  var controls;

  var pivot;
  var bagMesh;
  var planeMesh;

  const objLoader = new THREE.OBJLoader2();
  const fileLoader = new THREE.FileLoader();
  const textureLoader = new THREE.TextureLoader();

  init();

  function init() {
    container = document.getElementById('container');
    initScene();
    addGridHelper();
    addCamera();
    addLighting();
    addRenderer();
    addOrbitControls();

    loadPlaneObj();

    // Logic
  var update = function() {};

  // Draw scene
  var render = function() {
   renderer.render(scene, camera);
  };

  // Run game logic (update, render, repeat)
  var gameLoop = function() {
   requestAnimationFrame(gameLoop);
   update();
   render();
  };
  gameLoop();
  }

  /**** Basic Scene Setup ****/
  function initScene() {
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xd3d3d3);
    var axis = new THREE.AxesHelper();
    scene.add(axis);
  }

  function addCamera() {
    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.set(3,3,3);
    scene.add(camera);
  }

  function addGridHelper() {
    var planeGeometry = new THREE.PlaneGeometry(2000, 2000);
    planeGeometry.rotateX(-Math.PI / 2);

    var planeMaterial = new THREE.ShadowMaterial({
      opacity: 0.2
    });
    var plane = new THREE.Mesh(planeGeometry, planeMaterial);
    plane.position.y = -200;
    plane.receiveShadow = true;
    scene.add(plane);

    var helper = new THREE.GridHelper(2000, 100);
    helper.material.opacity = 0.25;
    helper.material.transparent = true;
    scene.add(helper);

    var axis = new THREE.AxesHelper();
    scene.add(axis);
  }

  // *********** Lighting settings **********************
  function addLighting() {
    var light = new THREE.HemisphereLight(0xffffff, 0xffffff, 1);
    scene.add(light);
  }

  // ************** Material settings **************
  function setMaterial(materialName) {
    // get the object from the scene
    var bagMesh = scene.getObjectByName('bag');
    var material;

    if (!materialName) {
      materialName = materials.material;
    }

    if (bagMesh) {
      var colour = parseInt(materials.colour);
      switch (materialName) {
        case 'MeshBasicMaterial':
          material = new THREE.MeshBasicMaterial({
            color: colour
          });
          break;
        case 'MeshDepthMaterial':
          material = new THREE.MeshDepthMaterial();
          break;
        case 'MeshLambertMaterial':
          material = new THREE.MeshLambertMaterial({
            color: colour
          });
          break;
        case 'MeshNormalMaterial':
          material = new THREE.MeshNormalMaterial();
          break;
        case 'MeshPhongMaterial':
          material = new THREE.MeshPhongMaterial({
            color: colour
          });
          break;
        case 'MeshPhysicalMaterial':
          material = new THREE.MeshPhysicalMaterial({
            color: colour
          });
          break;
        case 'MeshStandardMaterial':
          material = new THREE.MeshStandardMaterial({
            color: colour
          });
          break;
        case 'MeshToonMaterial':
          material = new THREE.MeshToonMaterial({
            color: colour
          });
          break;
      }
      bagMesh.children.forEach(function(c) {
        c.material = material;
      });
    }
  }

  function setMaterialColour(colour) {
    materials.colour = colour;
    setMaterial(null);
  }
  // ************** End of materials ***************

  function addRenderer() {
    renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    container.appendChild(renderer.domElement);
  }

  function addOrbitControls() {
    var controls = new THREE.OrbitControls(camera, renderer.domElement);
  }

  function addPivot() {
    var cubeGeo = new THREE.BoxBufferGeometry(5, 5, 5);
    var cubeMat = new THREE.MeshBasicMaterial();
    pivot = new THREE.Mesh(cubeGeo, cubeMat);
    bagMesh.position.x -= 15;
    bagMesh.position.z -= 55;

    pivot.add(bagMesh);
    pivot.add(handle);
    scene.add(pivot);
  }

  function loadPlaneObj() {
  loadObjWithMtl('PlaneWithMaterial',
      'https://rawgit.com/Katana24/threejs-experimentation/material-test/models/PlaneWithMaterial.obj',
      'https://rawgit.com/Katana24/threejs-experimentation/material-test/models/PlaneWithMaterial.mtl')
   .then(function(mesh) {
        loadTexture(
          'https://rawgit.com/Katana24/threejs-experimentation/material-test/img/1.jpg', scene, 0xff0000, THREE.FrontSide, mesh);
   });
 }

  function loadObjWithMtl(modelName, modelUrl, mtlUrl) {
  return new Promise(function(resolve, reject) {
   var callbackOnLoad = function ( event ) { resolve(event.detail.loaderRootNode); };
   var onLoadMtl = function ( materials ) {
    objLoader.setModelName( modelName );
    objLoader.setMaterials( materials );
    objLoader.getLogger().setDebug( true );
    objLoader.load( modelUrl, callbackOnLoad, null, null, null, false );
   };
   objLoader.loadMtl(mtlUrl, null, onLoadMtl );
  });
 }

 function loadTexture(imgPath, scene, color, side, mesh) {
  var loadedMesh = mesh;
   textureLoader.load(imgPath,
   function (texture) {
        var geometry = new THREE.Geometry().fromBufferGeometry( loadedMesh.children[0].geometry );
    mesh.children[0].material.map = texture;
    mesh.children[0].material.needsUpdate = true;
    scene.add(mesh);
   },
   undefined,
   function ( err ) {
    console.error( 'An error occurred...' );
   }
  );
 }

  function addPlaneToSceneSOAnswer(mesh) {
  var frontMaterial = new THREE.MeshBasicMaterial( { color : 0xff0000, side: THREE.FrontSide } );
  var backMaterial  = new THREE.MeshBasicMaterial( { color : 0x00ff00, side: THREE.BackSide } );

  var geometry = new THREE.Geometry().fromBufferGeometry( mesh.children[0].geometry );
  var length = geometry.faces.length;
  geometry.faces.splice(14, 1);

  for (var i = 0; i < geometry.faces.length; i ++ ) {
   var face = geometry.faces[i];
   face.color.setHex(Math.random() * 0xffffff);
  }
  mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, side: THREE.DoubleSide }) );
  mesh.material.side = THREE.FrontSide;

  var mesh2 = new THREE.Mesh( geometry, mesh.material.clone() );
  mesh2.material.side = THREE.BackSide;
  // mesh2.material.vertexColors = THREE.NoColors;
  mesh2.material.vertexColors = [new THREE.Color(0xff0000), new THREE.Color(0x00ff00), new THREE.Color(0x0000ff)];

  mesh.add( mesh2 );
  scene.add(mesh);
 }
})();
body {
  background: transparent;
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}

#canvas {
  margin: 10px auto;
  width: 800px;
  height: 350px;
  margin-top: -44px;
}

So what simple thing am I doing wrong here? I think the problem is in this function:
  function loadTexture(imgPath, scene, color, side, mesh) {
    var loadedMesh = mesh;
    textureLoader.load(imgPath,
      function (texture) {
        var geometry = new THREE.Geometry().fromBufferGeometry( loadedMesh.children[0].geometry );
        mesh.children[0].material.map = texture;
        mesh.children[0].material.needsUpdate = true;
        scene.add(mesh);
      },
      undefined,
      function ( err ) {
        console.error( 'An error occurred...' );
      }
    );
  }

This function gets the mesh then loads the required texture and applies it to the material in the mesh. It then tells the material to update. Is this the correct approach?
This answer here actually only calls render once everything is set it but I want to be-able to change textures, materials etc at run time.
I thought that mesh.children[0].material.needsUpdate = true would signal the shader program to update...
Thanks

A: The texture is loaded correctly, but it is not shown correctly, because the blender object does not provide any texture coordinates:
# Blender v2.77 (sub 0) OBJ File: 'Plane.blend'
# www.blender.org
mtllib PlaneWithMaterial.mtl
o Plane
v -1.000000 0.000000 1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 0.000000 -1.000000
vn 0.0000 1.0000 0.0000
usemtl Material
s off
f 1//1 2//1 4//1 3//1

Use the following object instead:
# Blender v2.77 (sub 0) OBJ File: 'Plane.blend'
# www.blender.org
mtllib PlaneWithMaterial.mtl
o Plane

v -1.000000 0.000000 1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 0.000000 -1.000000

vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 1.000000 1.000000

vn 0.0000 1.0000 0.0000

usemtl Material
s off
f 1/1/1 2/2/1 4/4/1 3/3/1

See the code snippet:

(function onLoad() {
  var canvasElement;
  var width, height;
  var scene, camera;
  var renderer;
  var controls;

  var pivot;
  var bagMesh;
  var planeMesh;

  const objLoader = new THREE.OBJLoader2();
  const fileLoader = new THREE.FileLoader();
  const textureLoader = new THREE.TextureLoader();
  textureLoader.setCrossOrigin("");

  init();

  function init() {
    container = document.getElementById('container');
    initScene();
    addGridHelper();
    addCamera();
    addLighting();
    addRenderer();
    addOrbitControls();

    loadPlaneObj();

    // Logic
  var update = function() {};

  // Draw scene
  var render = function() {
   renderer.render(scene, camera);
  };

    function resize() {
      var aspect = window.innerWidth / window.innerHeight;
      renderer.setSize(window.innerWidth, window.innerHeight);
      camera.aspect = aspect;
      camera.updateProjectionMatrix();
    }
    window.onresize = resize;

  // Run game logic (update, render, repeat)
  var gameLoop = function() {
   requestAnimationFrame(gameLoop);
   update();
   render();
  };
  gameLoop();
  }

  /**** Basic Scene Setup ****/
  function initScene() {
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xd3d3d3);
    var axis = new THREE.AxesHelper();
    scene.add(axis);
  }

  function addCamera() {
    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.set(1,1,1);
    scene.add(camera);
  }

  function addGridHelper() {
    var planeGeometry = new THREE.PlaneGeometry(2000, 2000);
    planeGeometry.rotateX(-Math.PI / 2);

    var planeMaterial = new THREE.ShadowMaterial({
      opacity: 0.2
    });
    var plane = new THREE.Mesh(planeGeometry, planeMaterial);
    plane.position.y = -200;
    plane.receiveShadow = true;
    scene.add(plane);

    var helper = new THREE.GridHelper(2000, 100);
    helper.material.opacity = 0.25;
    helper.material.transparent = true;
    scene.add(helper);

    var axis = new THREE.AxesHelper();
    scene.add(axis);
  }

  // *********** Lighting settings **********************
  function addLighting() {
    var light = new THREE.HemisphereLight(0xffffff, 0xffffff, 1);
    scene.add(light);
  }

  // ************** Material settings **************
  function setMaterial(materialName) {
    // get the object from the scene
    var bagMesh = scene.getObjectByName('bag');
    var material;

    if (!materialName) {
      materialName = materials.material;
    }

    if (bagMesh) {
      var colour = parseInt(materials.colour);
      switch (materialName) {
        case 'MeshBasicMaterial':
          material = new THREE.MeshBasicMaterial({
            color: colour
          });
          break;
        case 'MeshDepthMaterial':
          material = new THREE.MeshDepthMaterial();
          break;
        case 'MeshLambertMaterial':
          material = new THREE.MeshLambertMaterial({
            color: colour
          });
          break;
        case 'MeshNormalMaterial':
          material = new THREE.MeshNormalMaterial();
          break;
        case 'MeshPhongMaterial':
          material = new THREE.MeshPhongMaterial({
            color: colour
          });
          break;
        case 'MeshPhysicalMaterial':
          material = new THREE.MeshPhysicalMaterial({
            color: colour
          });
          break;
        case 'MeshStandardMaterial':
          material = new THREE.MeshStandardMaterial({
            color: colour
          });
          break;
        case 'MeshToonMaterial':
          material = new THREE.MeshToonMaterial({
            color: colour
          });
          break;
      }
      bagMesh.children.forEach(function(c) {
        c.material = material;
      });
    }
  }

  function setMaterialColour(colour) {
    materials.colour = colour;
    setMaterial(null);
  }
  // ************** End of materials ***************

  function addRenderer() {
    renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    container.appendChild(renderer.domElement);
  }

  function addOrbitControls() {
    var controls = new THREE.OrbitControls(camera, renderer.domElement);
  }

  function addPivot() {
    var cubeGeo = new THREE.BoxBufferGeometry(5, 5, 5);
    var cubeMat = new THREE.MeshBasicMaterial();
    pivot = new THREE.Mesh(cubeGeo, cubeMat);
    bagMesh.position.x -= 15;
    bagMesh.position.z -= 55;

    pivot.add(bagMesh);
    pivot.add(handle);
    scene.add(pivot);
  }

  function loadPlaneObj() {
    makeTextFile = function (text) {
      var data = new Blob([text], {type: 'text/plain'});
      var textFile = window.URL.createObjectURL(data);
      return textFile;
    }
    var textbox_obj = document.getElementById('plane_obj');
    var obj_url = makeTextFile(textbox_obj.value);
    var textbox_mtl = document.getElementById('plane_mtl');
    var mtl_url = makeTextFile(textbox_mtl.value);

    loadObjWithMtl('plane1',
      obj_url, mtl_url)
   .then(function(mesh) {
        loadTexture(
         'https://rawgit.com/Katana24/threejs-experimentation/material-test/img/1.jpg',
         scene, 0xff0000, THREE.FrontSide, mesh);
   });
 }

  function loadObjWithMtl(modelName, modelUrl, mtlUrl) {
  return new Promise(function(resolve, reject) {
   var callbackOnLoad = function ( event ) { resolve(event.detail.loaderRootNode); };
   var onLoadMtl = function ( materials ) {
    objLoader.setModelName( modelName );
    objLoader.setMaterials( materials );
    objLoader.getLogger().setDebug( true );
    objLoader.load( modelUrl, callbackOnLoad, null, null, null, false );
   };
   objLoader.loadMtl(mtlUrl, null, onLoadMtl );
  });
 }

 function loadTexture(imgPath, scene, color, side, mesh) {
  var loadedMesh = mesh;
   textureLoader.load(imgPath,
   function (texture) {
        var geometry = new THREE.Geometry().fromBufferGeometry( loadedMesh.children[0].geometry );
    mesh.children[0].material.map = texture;
    mesh.children[0].material.needsUpdate = true;
    scene.add(mesh);
   },
   undefined,
   function ( err ) {
    console.error( 'An error occurred...' );
   }
  );
 }

  function addPlaneToSceneSOAnswer(mesh) {
  var frontMaterial = new THREE.MeshBasicMaterial( { color : 0xff0000, side: THREE.FrontSide } );
  var backMaterial  = new THREE.MeshBasicMaterial( { color : 0x00ff00, side: THREE.BackSide } );

  var geometry = new THREE.Geometry().fromBufferGeometry( mesh.children[0].geometry );
  var length = geometry.faces.length;
  geometry.faces.splice(14, 1);

  for (var i = 0; i < geometry.faces.length; i ++ ) {
   var face = geometry.faces[i];
   face.color.setHex(Math.random() * 0xffffff);
  }
  mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, side: THREE.DoubleSide }) );
  mesh.material.side = THREE.FrontSide;

  var mesh2 = new THREE.Mesh( geometry, mesh.material.clone() );
  mesh2.material.side = THREE.BackSide;
  // mesh2.material.vertexColors = THREE.NoColors;
  mesh2.material.vertexColors = [new THREE.Color(0xff0000), new THREE.Color(0x00ff00), new THREE.Color(0x0000ff)];

  mesh.add( mesh2 );
  scene.add(mesh);
 }
})();
body {
  background: transparent;
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}

#canvas {
  margin: 10px auto;
  width: 800px;
  height: 350px;
  margin-top: -44px;
}

  <textarea id="plane_obj" style="display:none;">
    # Blender v2.77 (sub 0) OBJ File: 'Plane.blend'
    # www.blender.org
    mtllib Plane.mtl
    o Plane

    v -1.000000 0.000000 1.000000
    v 1.000000 0.000000 1.000000
    v -1.000000 0.000000 -1.000000
    v 1.000000 0.000000 -1.000000

    vt 0.000000 0.000000
    vt 1.000000 0.000000
    vt 0.000000 1.000000
    vt 1.000000 1.000000

    vn 0.0000 1.0000 0.0000

    usemtl None
    s off
    f 1/1/1 2/2/1 4/4/1 3/3/1
  </textarea>

  <textarea id="plane_mtl" style="display:none;">
    # Blender MTL File: 'Plane.blend'
    # Material Count: 1

    newmtl None
    Ns 0
    Ka 0.000000 0.000000 0.000000
    Kd 0.8 0.8 0.8
    Ks 0.8 0.8 0.8
    d 1
    illum 2
  </textarea>


text:
Q: What does "actinide" as an adjective means in this phrase: The following exerpt from a web-novel:

A shaft of pure actinide destruction lanced forth from its outthrust palm (...)

source
What does "actnide" means in this context?

A: I rather suspect that the author is simply misusing the word.
The actinides are the f-block elements of group 7 in the periodic table, so called because they come immediately after actinium. The elements share some characteristics, such as having largely incomplete f-shell electrons and being radioactive, but none of that is applicable here. After all, most radioactive elements aren't in the actinide grouping.
I suspect they actually meant actinic. It's another scientific term, but one that has found great currency in certain types of fiction writing, especially in the set phrase 'actinic glare'. Actinic light is usually bright and low-wavelength (blue-white).
It is most likely that the two words are related, but they mean very different things.


text:
Q: Comparing different adb logs Does anyone know of any proper way to compare adb logs of different timestamp? I normally use Beyond compare text compare option. but that will show all the lines as different since the timestamp will be different. If I want to compare the workflow of any process for example, if want to see compare the difference in IMS registration and working flow from 2 different set of adb logs, what is the easiest way? Need Suggestions.

A: I am removing time stamps with the help of awk and then comparing logs with meld.
awk '{ s = ""; for (i = 5; i <= NF; i++) s = s $i " "; print s }'

A: You can print the log using a format that does not include the timestamp so you don't have to remove it.
For example:
adb logcat -v brief

See more options at https://developer.android.com/studio/command-line/logcat#outputFormat


text:
Q: Autofiltering Excel with multiple filter conditions I am trying to autofilter in Excel using the below VBScript code. This script called multiple times from a Perl program.
Dim objExcel : Set objExcel = GetObject(,"Excel.Application")
objExcel.Visible = True
objExcel.Selection.AutoFilter
objExcel.ActiveSheet.Range("G1").AutoFilter WScript.Arguments.Item(0), _
    WScript.Arguments.Item (1)

Now I would like to know: is there a way by which I can pass an array for WScript.Arguments.Item (1) so that all the conditions are selected in one go? The task is to delete the filtered value. I call this script through Perl multiple times and the above script filter one value at a time and delete. The program works fine, but is slow.
Following is the part of Perl which calls the VBScript.
while(<FILE>){
    chomp;
    system("CSCRIPT "."\"$currentWorkingDirectory\"".'aboveVBS.vbs 9 '."\"$_\"");
    sleep(2);
}

A: If you put quotes around the values, VBScript will treat it as a single argument.
> cscript script.vbs arg1 "multiple values for arg 2"

In the script:
WScript.Echo WScript.Arguments.Count    ' ==> 2

a = Split(WScript.Arguments(1))
WScript.Echo a(0)                        ' ==> multiple
WScript.Echo a(1)                        ' ==> values
WScript.Echo a(2)                        ' ==> for
WScript.Echo a(3)                        ' ==> arg
WScript.Echo a(4)                        ' ==> 2

Excel expects:
Range.AutoFilter <Field>, <Criteria>, <Operator>

If you want a list of criteria to filter on, you'll use xlFilterValues for the <Operator> argument. <Criteria> will be an array of string values, which we created above.
Const xlFilterVaues = 7

objExcel.ActiveSheet.Range("G1").AutoFilter WScript.Arguments.Item(0), a, xlFilterValues

So, just try adding Split() around WScript.Arguments(1) in your existing code, and pass xlFilterValues for the third param.

A: If only your second argument changes, you could pass the entire content of your data file to the VBScript:
local $/;
my $args = <FILE>;
$args =~ s/^\s+|\s+$//g;
$args =~ s/\r?\n/" "/g;

system("cscript \"$currentWorkingDirectory\\your.vbs\" 9 \"$args\"");

and change the processing in your VBScript to this:
Set xl = CreateObject("Excel.Application")
xl.Visible = True

Set wb = xl.Workbook.Open("C:\path\to\your.xlsx")
Set ws = wb.Sheets(1)
...
xl.Selection.AutoFilter

For i = 1 To WScript.Arguments.Count - 1
  ws.Range("G1").AutoFilter WScript.Arguments(0), WScript.Arguments(i)
  ...
Next

Or you could simply call the VBScript with the field and the path to the data file:
system("cscript \"$currentWorkingDirectory\\your.vbs\" 9 \"$filepath\"");

and do all the processing in VBScript:
Set xl = CreateObject("Excel.Application")
xl.Visible = True

Set wb = xl.Workbook.Open("C:\path\to\your.xlsx")
Set ws = wb.Sheets(1)
...
xl.Selection.AutoFilter

Set fso = CreateObject("Scripting.FileSystemObject")
Set f   = fso.OpenTextFile(WScript.Arguments(1))
Do Until f.AtEndOfStream
  ws.Range("G1").AutoFilter WScript.Arguments(0), f.ReadLine
  ...
Next
f.Close

Applying more than 2 AutoFilter conditions to a column at the same time is not possible. Check the signature of the AutoFilter method in the documentation:

expression .AutoFilter(Field, Criteria1, Operator, Criteria2, VisibleDropDown)
expression An expression that returns a Range object.

You have Critera1 and Criteria2 and an Operator for combining the two. Calling the AutoFilter method with another set of criteria replaces the existing criteria.


text:
Q: Backticks in snippets for Emacs I am trying to create a code block snippet for Markdown in Emacs.
I tried to create a snippet like so:
# -*- mode: snippet -*-
# name: code-block
# key: cb
# ---

```${1:r}
${2:code}
```

but when I tried to save, it threw an error saying wrong type argument: stringp, nil.
How can I get this snippet to work?

A: You'll have to escape the backticks with a backslash.
From the documentation:

Plain Text
Arbitrary text can be included as the content of a template. They are usually interpreted as plain text, except $ and `. You need to use \ to escape them: \$ and \` . The \ itself may also needed to be escaped as \\ sometimes.


text:
Q: Randomising colour for many of polygons in QGIS Is there a way in QGIS to randomise the colour of all the polygons present in a single layer?
I'm currently using QGIS 3.20.3 and a lot of the plugins for this that I've found online are not compatible (including Topocolour).

A: Right click the polygon layer in the layers panel and go to properties -> symbology. Choose the categorized renderer from the dropdown menu on the top. As value use $id. Choose random colors as color ramp. Then click classify.

A: If you want to get a fixed number of colors and want to control which ones these should be, use the "regular" Single Symbol layer rendering and set a date driven override for the color. In the assistant, as Source set the expression rand(1,5) to get 5 different colors. Select a color ramp (or create your own) from whicht QGIS picks the 5 colors.
Like this, the colors are updated every time you zoom or pan. If the colors should be fixed, creat a new attribute with Field calculator and the same expression as above. In the assistant, then select the name of this field as source. So the colors will be random, but will not change any more.

A: To get random colors, but be sure that to neighboring polygons are always in different colors, use Menu Processing / Toolbox / Cartography / Topological coloring (see documentation). Run the tool and on the output, set Data driven override > Assistant for the color and choose the field color_id as source.


text:
Q: Need to show data in weeks between selected timeframe I need to show the data broken down in weeks if you choose the start date and end date.   I have to show in a stacked column chart. I am trying to show the values if you choose for example last month i need to show it by weeks for example
week  user name total approved first approved last aprovedDate totalitemsAdded
----- --------- -------------- -------------- ---------------- ---------------
week1 XYZ       3              10/01/2012     10/05/2012       5
week2 XYZ       5              etc            etc              etc
week3

Below is the code and the result  i am getting now .
Current Results
UserName TotalApproved FirstApprovedDate       LastApprovedDate        TotalItemsAdded
-------- ------------- ----------------------- ----------------------- ---------------
XYZ      9             2011-11-19 16:56:49.960 2011-11-19 18:18:20.783 2

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '10/1/2012 '
SET @EndDate = '10/31/2012'

;with Items as(
       SELECT
              UserName = Profile.Description,
              TotalItems = COUNT(TransactionID),
              FirstAddedDate = MIN(UTCDate),
              LastAddedDate = MAX(UTCDate)
       FROM Transactiondatabase.dbo.transaction
                JOIN Biography.dbo.Profile ON transaction.ProfileId = Profile.ProfileID
       WHERE
              Data like '%ItemAdded%'
                AND UTCDate BETWEEN @StartDate AND DATEADD(dd,1,@EndDate)
       GROUP BY
              Profile.Description
)

,
Approved as
(
       SELECT
              UserName = Profile.Description,
              TotalApproved = COUNT(TransactionID),
              FirstApprovedDate = MIN(UTCDate),--Demo
              LastApprovedDate = MAX(UTCDate)
       FROM Transactiondatabase..transaction
                JOIN Biography.dbo.Profile ON transaction.ProfileId = Profile.ProfileID
       WHERE
              Data like '%Approved%'
                AND UTCDate BETWEEN @StartDate AND DATEADD(dd,1,@EndDate)
       GROUP BY
                Profile.Description
)

Select Distinct Approved.*, TotalItemssAdded = sum(distinct Items.TotalItems)
from Items, Approved
Group by Approved.UserName, Approved.FirstApprovedDate, Approved.LastApprovedDate, Approved.TotalApproved
using ssrs 2005

A: You may find:
DATEPART( WEEK, UTCDate )

helpful. As in:
SELECT FirstApprovedWeek = DATEPART( WEEK, UTCDATE ) FROM table

See MSDN - DATEPART (Transact-SQL) for more details and usage options.


text:
Q: Find Rating For Images using wordpress Plugin I'm a newbie looking for help. What I want to do is this:
I am using orange-theme gallery in my wordpress
Now i want to find rating for each images click`s can u help me... or send any useful plugin in wordpress

A: you can check pics mash plugin it works on wordpress 3.0 or higher http://wordpress.org/plugins/pics-mash/screenshots/

A: That's a good photo rating plugin, that helped me create a voting for the best children's photo - http://wp-vote.net/ (WP Foto Vote)


text:
Q: Sintaxe de seletor css para eliminar elemento  com jQuery Alguma forma de utilizar jquery e seletores de uma forma parecida com esta?
$("#tabela td").empty();

Necessito eliminar somente as linhas tr que contenham td de uma tabela como esta, mas não as linhas tr que possuem elementos th.
Da forma que estou fazendo, elimina as td, mas não as tr que contém td.

        title

        teste

A: Sugiro fazer como começou e adicionar .closest('tr') assim ele sobe ao elemento tr e pode removê-lo.
$("#tabela td").closest('tr').empty(); // ou .remove();

exemplo: http://jsfiddle.net/47T9T/

A: Não havia usado assim antes, mas acredito não tenha problema em continuar utilizando. No meu caso, costumo usar o closest (http://api.jquery.com/closest/) e o remove (http://api.jquery.com/remove/), passando o elemento que recebeu o clique.
Por exemplo:

        Asdf
        Excluir

// Irá encontrar a primeira ocorrência TR a partir do elemento (no caso, o link) e fazer a ação que mandarmos (no caso, excluir a tr toda).
function excluir(element){
    $(element).closest('tr').remove();
}

A: Seu seletor está quase correto.
Para a marcação HTML abaixo

        Linha com TH

        Linha com TD

Este código JS resolve o problema
$("#tabela td").closest("tr").remove();

Exemplo: http://jsfiddle.net/Npx67/1/
Edit1 para atendimento ao requisito


text:
Q: dapper PropInfo Setter for inherited EntitySet from abstract class reference is null I am trying to replace a nasty LINQ 2 SQL hit with some dapper queries to improve performanace. In doing so I have to weave a bunch of different objects together in order to create the big object required to hold all the information I need for ASN information.
The current problem I am having is with an abstract class Orders, this class is implemented by two seperate classes AutionOrder and MerchantOrder using a discriminator property.
Since I cannot use dapper to create a object that is an abstract class I am instead using one of the public classes. however when it goes to build the object it is failing inside of GetSettableProps it is finding the proper DeclaringType but the GetProperty method is returning null when it is looking for an property that is internal or is an EntitySet. I've tried to hack around it using t.BaseType.GetProperty as well as p.GetAccessors().First().GetBaseDefinition().DeclaringType.GetProperty(p.Name).GetSetMethod(true) with no success.
dummy objects:

Order

OrderID, Name, Address, RowVersion(internal), Shipments(EntitySet),OrderDetails(EntitySet), Customer(EntityRef)

Shipment

ShipmentID, OrderID, TrackingNumber

OrderDetails

OrderDetailID, OrderID, Product, QTY, Price

Customer

CustomerID, Name,

For this particular SQL hit I am trying to grab some of the 1 to 1 relationship mappings I need.

SELECT o.* from Orders as o left join Customers as c on o.CustomerID = c.CustomerID where o.OrderID in (1,2,3);

This is what I am using to utilize dapper and let it do it's magic:
using (var connection = new SqlConnection(_ConnectionString))
{
    connection.Open();
    results = connection.Query<MerchantOrder, MerchantCustomer, MerchantOrder>(sql.ToString(),
        (o, c) => { o.Customer = c; return o; },
        splitOn: "CustomerID");
}

If I change Order to be a public class this problem goes away though, but this is not a desired side-effect. It is failing when trying to set the propInfo for RowVersion - switching this to public instead of internal solved this problem - although not desired. But then it fails when it is trying to create the Shipments objects for Order. Again none of this is an issue when Order is a public class.
Also I am doing separate queries to pull in Many to one relationships such as Shipments to Orders and OrderDetails to Orders and normalizing the results into a proper Order Object.
MerchantOrder is pretty much an empty class with no real special logic. The discriminating different here is just how we end up finding the CustomerID which is abstracted away prior to the actual SQL hit anyway.
Also I am using the latest version of dapper as of 12/20/2011.
I really like dapper, but this problem is making my head asplode - so thanks for the help!

A: This was a bug, that is now fixed in trunk:
public class AbstractInheritance
    {
        public abstract class Order
        {
            internal int Internal { get; set; }
            protected int Protected { get; set; }
            public int Public { get; set; }

            public int ProtectedVal { get { return Protected; } }
        }

        public class ConcreteOrder : Order
        {
            public int Concrete { get; set; }
        }
    }

    // http://stackoverflow.com/q/8593871
    public void TestAbstractInheritance()
    {
        var order = connection.Query<AbstractInheritance.ConcreteOrder>("select 1 Internal,2 Protected,3 [Public],4 Concrete").First();

        order.Internal.IsEqualTo(1);
        order.ProtectedVal.IsEqualTo(2);
        order.Public.IsEqualTo(3);
        order.Concrete.IsEqualTo(4);

    }

One side note is that, by design, we do not set private fields or properties in the base classes. The behaviour can be magical and not consistent.
Eg:
class A { private int a {get; set;} }
class B : A { private int a {get; set;} }
class C: B {}

// What should "select 1 a" do? Set it on A? Set it on B? Set it on Both? Set it on neither?

We went with "set it on neither"

A: I think is not possible (because of the abstract class) without modifying your code.
I had a similar problem and ended up creating a new object private to the assembly where I have my repositories that derived from the abstract base class.
This class is not abstract and only visible to the repository class that stores the data, this class had all the required methods for the actual table.


text:
Q: totaling dynamically created inputs The following can add or remove a table using click events. In the top there is a table that is not dynamically created that I have an input field called name="total_hrs" that I would like to total all the hours entered into each of the inputs name="hours' + i + '"
The current function hrsUpdate only gives me the last inputs entered value. How can that function be modified to total all of the hours inputs and reduce in value if a table is removed?

            <input type="text" value=""></input>

            <input type="text" value=""></input>

            <input type="text" value=""></input>

            <input id="total_hrs" name="total_hrs" type="text" value=""></input>

edit:

A: Your could consider trying the following structure:
0.00

<button id="add_row_btn">Add Row</button>

and generate table rows that look like the following:

    <input type="text" value="" class="hours_entry">
    <button class="remove_row_btn">Remove</button>

JavaScript:
$(document).ready(function() {

    var handleAddRow = function(e) {
        var row = $('

');
        var input = $('</td').append('<input type="text" value="" class="hours_entry">');
            input.appendTo(row);
        var remove = $('</td').append('<button class="remove_row_btn">Remove</button>');
            remove.appendTo(row);
        row.appendTo('#hour_records');
    };

    var handleRemoveRow = function(e) {
        //Determine the respective row ('
') object and remove it
        $(e.currentTarget).parent().parent().remove();
    };

    var updateTotalHours = function(e) {
        //Assuming that you properly validate all hour entries as numbers
        var total_hours = 0;
        $('.hours_entry').each(function(i, elem) {
            var hours = parseFloat($(elem).val());
            if(!isNaN(hours)) {
                   total_hours += parseFloat($(elem).val());
            }
        });
        $('#total_hours').text(total_hours);
    };

    //Setup the 'add row' event listener
    $('#add_row_btn').on('click', handleAddRow);
    //Setup the 'remove row' event listener
    $('#hour_records').on('click', 'button.remove_row_btn', handleRemoveRow);
    //Setup a listener to update the total hours count
    $('#hour_records').on('change', updateTotalHours);

});

Here is a jsFiddle demo that includes some very basic input validation: http://jsfiddle.net/F2hxH/10/


text:
Q: The Word Toptimizer for s_index, s in enumerate(sentences):
        s_tokens = s.split()
        if (local_q_set.intersection(set(s_tokens)) == local_q_set):
            q_results.append(s_index)

The code snippet above is the core algorithm I used to find relevant sentences in massive text data that include all tokens in the query. For example, for a query "happy apple", it finds all sentences that include exactly one or more of all of the given tokens, (i.e. "happy" and "apple"). My method is very simple: find common intersecting sets and see if they match. However, I am not getting enough performance. If anyone has seen an optimization for such problem, I would highly appreciate any direction or link for the idea- Thank you for time in advance

A: There are a few things you can do to increase performance of the sequential search but the real boost would come from indexing tokens.
set.difference
Using not local_q_set.difference(s_tokens) instead of comparing the intersection to the original set may be somewhat faster.
Regular Expression filter
If your sentences are long, using a regular expression may provide some speed improvements by isolating the potential tokens out of the sentence before checking them against the token set:
import re
tokens     = re.compile("|".join(local_q_set))
tokenCount = len(local_q_set)
for s_index, s in enumerate(sentences):
    s_tokens = tokens.findall(s)
    if len(s_tokens) < tokenCount or local_q_set.difference(s.split()):
       continue
    q_results.append(s_index)

Filter using the in operator
You can also use a simple in operator to check for the presence of tokens instead of a regular expression (this should be faster when you have few tokens in the query):
result = []
tokenSet = set(queryTokens)
for index, sentence in enumerate(sentences):
     if any( token not in sentence for token in queryTokens) \
     or tokenSet.difference(sentence.split()):
         continue
     result.append(index)

Caching sentence word sets
To improve on the sequential search when multiple queries are made to the same list of sentences, you can build a cache of word sets corresponding to the sentences.  This will eliminate the work of parsing the sentences while going through them to find a match.
cachedWords = []

queryTokens = ["happy","apple"]

queryTokenSet = set(queryTokens)
if not cachedWords:
    cachedWords = [ set(sentence.split()) for sentence in sentences ]
result = [ index for index,words in enumerate(cachedWords) if not queryTokenSet.difference(words) ]

Token Indexing
If you are going to perform many queries against the same list of sentences, it will be more efficient to create a mapping between tokens and sentence indexes. You can do that using a dictionary and then obtain query results directly by intersecting the sentence indexes of the queried tokens:
tokenIndexes = dict()
for index,sentence in enumerate(sentences):
    for token in sentence.lower().split():
        tokenIndexes.setdefault(token,[]).append(index)

def tokenSet(token): return set(tokenIndexes.get(token,[]))

queryTokens = ["happy","apple"]

from functools import reduce
result = reduce(set.intersection , (tokenSet(token) for token in queryTokens) )

This  will allow you to economically implement complex queries using set operators.  For example:
import re

querySring = " happy & ( apple | orange | banana ) "
result = eval(re.sub("(\w+)",r"tokenSet('\1')", querySring))

# re.sub(...) transforms the query string into " tokenSet('happy') & ( tokenSet('apple') | tokenSet('orange') | tokenSet('banana') ) "

Performance Tests:
I made a few performance tests (finding two tokens in one sentence out of 80,000):
original algorithm: 105 ms           1x
set.difference:      88 ms         1.2x
regular expression:  60 ms         1.8x
"in" operator:       43 ms         2.4x
caching word sets:   23 ms         4.6x (excluding 187ms to build cache)
token indexing:       0.0075 ms  14000x (excluding 238ms to build tokenIndexes)

So, if you're going to be performing several queries on the same sentences, with  token indexing, you'll get 14 thousand times faster responses once the tokenIndexes dictionary is built.


text:
Q: Check if two arrays share the same elements I've written this code in a .playgraound
var a = [1, 2, 3]
var b = a
var c = a

if b === c
{
    "b and c still share the same array elements."
}
else
{
    "b and c now refer to two independent sets of array elements."
}

The result is "b and c now refer to two independent sets of array elements" but in "The Swift Programming Language" Apple says that

The example below uses the "identical to" operator (===) to check whether b and c still share the same array elements.

Can you explain me why they are different?

A: The reason the book says

The result is "b and c now refer to two independent sets of array elements"

is that the code earlier in the book stopped array sharing between b and c established by the assignment of a to both of them:
b.unshare() // Page 306, line 3

Array a has been unshared from b and c implicitly by appending an element to it on page 305, line 1.
With the code as you show the "b and c still share the same array elements." message will be printed.

A: b === c tests what will happen to c if you change one of the elements of b or vice versa. In your example, b === c evaluates to true, so when you change an element of b:
var a = [1, 2, 3]
var b = a
var c = a

b[1] = 10

you see the change reflected in c:
c[1] // returns 10

You can use the unshare() method to ensure that b refers to an independent array instance:
b.unshare()
b === c // returns false

b[2] = 10
c[2] // returns 3


text:
Q: room map game program reading from a file These are the directions: this file represents the game map for our interactive fiction game Specifcally, the first line contains the number of rooms on the map and each successive line represents each of these rooms; one line is one room. As such, the number on the first line should equal the number of lines below it in the file. The first line after the number of rooms is 1 and goes on from there. Each room line contains four numbers. These are the rooms that the current room connects to up, down, left and right, respectively. So, since Room 3 is listed as 3 4 2 10, it connects up, down, left and right to Room 3, Room 4, Room 2 and Room 10, respectively. To move to another room you can access from the room you pick you pick either up,down,left,right. I am not asking for anyone todo this AT ALL!!!. i am trying to get help with starting the program. I am stuck with how to start this program, i don't know how i would get the numbers and represent each column to u,d,l,r also and how do i print out those number for the line you picked? this is all i have so far but idk where to go from here.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
    char room;
    int room1;
    string room;
    ifstream infile;
    infile.open("GameFile.txt")
    while (infile.is_open())
    infile.getline(infile,line);

    return 0;
}

A: You want something like a quadruply linked list (i just made up this term). So I would just define a struct:
struct Room {
    int up;
    int down;
    int left;
    int right;
};

overload the input operator and push them line by line into a std::vector<Room>. Otherwise there is little help to offer given the information you provide.


text:
Q: Как сделать такой эффект свечения у кнопки? Как можно сделать такой эффект свечения у кнопки как на картинке?

A: Смысл в том, что нужно заюзать псевдоэлемент, который лежит под кнопкой и заблюрен. Ему задаешь градиент, который тебе нужен. Примерно так
    click
.gradient-button
    width: 100px
    height: 30px
    border: none
    background-color: #555
    color: #fff
    font-size: 1.2em
    position: relative
    border-radius: 5px
    &:after
        content: ''
        border-radius: 5px
        position: absolute
        width: 100%
        height: 30px
        filter: blur(3px)
        background: linear-gradient(90deg, red 0%, blue 100%)
        left: 0
        top: 0
        z-index: -1

A:

* {
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  height: 100vh;
  background: #212121;
  align-items: center;
  justify-content: center;
}

button {
  position: relative;
  height: 60px;
  width: 200px;
  border: none;
  outline: none;
  color: white;
  background: #111;
  cursor: pointer;
  border-radius: 5px;
  font-size: 18px;
  font-family: 'Raleway', sans-serif;
}

button:before {
  position: absolute;
  content: '';
  top: -2px;
  left: -2px;
  height: calc(100% + 4px);
  width: calc(100% + 4px);
  border-radius: 5px;
  z-index: -1;
  opacity: 0;
  filter: blur(5px);
  background: linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000);
  background-size: 400%;
  transition: opacity .3s ease-in-out;
  animation: animate 20s linear infinite;
}

button:hover:before {
  opacity: 1;
}

button:hover:active {
  background: none;
}

button:hover:active:before {
  filter: blur(2px);
}

@keyframes animate {
  0% {
    background-position: 0 0;
  }
  50% {
    background-position: 400% 0;
  }
  100% {
    background-position: 0 0;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Page</title>
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <button>hover me</button>
</body>

</html>

A: Решение SVG + CSS
Применены фильтры SVG для размытия текста и рамки при наведении курсора
Линейный градиент используется для анимации изменения цвета рамки после клика
Другими словами, анимации будет как в вопросе: при наведении размытие, после клика анимация рамки.

HOVER ME, THEN CLICK ME!

.container {
width: 50vw;
height:50vh;
background:#151515;
}
 .btn {
  fill:transparent;
 stroke:white;
 stroke-width:4;
 stroke:url(#linGrad);
     }
.btn:hover {
filter: url(#blue_glow);
}
 .txt1 {
 font-size:14px;
 font-weight:500;
 fill:white;
 }

 .txt1:hover {
 filter: url(#blue_glow);
 /* pointer-events:none; */
 }
<div class="container">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  viewBox="0 0 250 60" >
  <defs>
     <!-- Градиент для рамки, анимация после клика -->
  <linearGradient id="linGrad" x1="0%" x2="85%" y1="15%" y2="0%" >
   <stop stop-color="#1B9F36" offset="0">
      <animate
    attributeName="stop-color"
 dur="2s"
 values="#1B9F36;#121BC1;#1B9F36"
 begin="gr1.click"
 end="gr1.mouseout"
 repeatCount="indefinite"  />
   </stop>
   <stop stop-color="#121BC1" offset="1">
     <animate
  attributeName="stop-color"
  dur="2s"
  values="#121BC1;#06B2E3;#121BC1"
  begin="gr1.click"
  end="gr1.mouseout"
  repeatCount="indefinite" />
   </stop>
  </linearGradient>
       <!-- Размытие рамки и текста при наведении -->
    <filter id="blue_glow" filterUnits="userSpaceOnUse"
            x="-20%" y="-20%" width="120%" height="120%">
           <feGaussianBlur in="SourceGraphic" stdDeviation="2" result="blur5"/>
           <feColorMatrix result="red-blur" in="blur-merged" type="matrix"
                     values="0.4 0 0 0 0
                             0 1 0 0 0
                             0 0 1 0 0
                             0 0 0.2 1 0" />
      <feMerge>
        <feMergeNode in="red-blur"/>
        <feMergeNode in="blur5"/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
 </defs>
       <!-- Чёрный фон       -->
  <rect width="100%" height="100%" fill="#151515" />
         <!-- Кнопка -->
       <g id="gr1">
   <rect class="btn" x="10" y="10" width="230" height="40" rx="10"/>
      <text class="txt1" x="30" y="35"  >HOVER ME, THEN CLICK ME!</text>
       </g>
 </svg>
</div>


text:
Q: How do I easily level up characters In Final Fantasy VII? In Final Fantasy VII, I'm near the end of the 2nd CD: I would like to level up my characters in order to have chances to defeat Weapons.
Where I can find monsters that give a good amount of EXP (better if easy to beat)?
Can you suggest some alternative strategies to accomplish the grown of my characters? (I use Cloud, Tifa and Barret).

A: The best place to level up in ff7 is the Swamp area in the Northern Crater, it is in the final dungeon of disc 3, but is by far the best place to level. If you are leveling to fight the optional weapons (Ruby, Emerald, Ultima) then i would just progress until you can level here.
The enemies you want are Movers, they have little (0?) exp but insane AP and are easily killed, and Magic Pots give great exp and ap, but require an elixir to kill (must give it to them first). You can steal elixirs from Gighee Which is also found in the swamp.
General method in the swamp is Steal Elixirs from Gighee (Or just use W-Item Duplication on Elixirs), use Elixirs to kill Magic Pots. Also, while hunting these two be sure to kill Movers great AP, and just run from everything else. This place is so good I usually end up putting my save crystal here.
If that isn't preferred, where you currently are I would recommend Mideel area, the Spiral and Head Hunter (found in forest) enemies give good exp and ap for that part of the game.
If you want to auto level you can fight the Midgar Zolom (Just stand inside the Midgar Swamp with X taped down, turbo might be needed). You can also auto level on certain beachs by holding down, your character will run up and then down the beach in constant motion. Again having X taped down will auto kill monsters. For these methods you might want to consider Sneak Attack materia in your setup.
Hope this helps

A: Highest EXP/AP gains:
For simply getting as much AP and EXP as fast as possible, the Swamp area of the Northern Crater is the best because you can fight the Movers (which give very high AP) and Magic Pots (high EXP gains) there.
You'll need to give lots of Elixirs to the Magic Pots, but you can just duplicate them using the W-Item materia bug: equip W-Item, select Elixir, use it on someone or a Magic Pot, then for your second item select Elixir again, then deselect it and you'll have 1 more in your inventory. Select Elixir again, deselect it again, and you'll have another; keep repeating this as necessary.
Character Stat Boosting with Sources
If you want also wish to improve your characters by collecting sources (Power, Magic, Mind, etc.), the best area to gain levels and source items is the Sunken Gelnika.
Sources:
As a recap, sources come in several varieties, and when you use a source item on one of the characters, one of that character's stats will be increased by 1 point (depending on the type of source). Sources are very rare in the game, and there are a mere handful of enemies which morph into sources, but the Gelnika is the one area in the game where all enemies you find can be morphed into sources, and each type of source can be gotten by morphing at least one type of enemy there.
Here's the list:
Power source = +1 Strength (do more physical damage)
Guard source = +1 Vitality (take less physical damage)
Magic source = +1 Magic (do more magical damage)
*Mind source = +1 Spirit (take less magical damage)
Speed source = +1 Dexterity (get faster turns in battle)
Luck source = +1 Luck (have more luck, where luck is a factor)
*A special note about Mind sources and Spirit: since the game is bugged, the Magical Defense attribute of equipped armor is never used in the game's calculations, so Spirit is the only thing which actually protects your characters from magic attacks. Thus, Spirit is a very important stat, and the only way to increase your defense against magic attacks is to use Mind sources.
Morphing Enemies into Sources
1. Get Morph
You get it from the Temple of the Ancients. It is missable so if you didn't get it then...too bad.
2. Get Yuffie
Since Yuffie is an optional character, I guess it's possible for you to not have added her to your party, so refer to this guide to find her. Search for {OPT-1} to jump to the relevant section.
3. Go to the Sunken Gelnika
Get in the Submarine, travel to the south of Costa del Sol near the Gold Saucer. Dive and look out for a sunken airplane, while making sure to avoid the Emerald Weapon if it's lurking nearby. Steer your submarine into the sunken ship to enter it.
4. Get the Conformer
The Conformer is found on the Gelnika, which is nice and convenient, since you'll need it. You can find the Conformer hiding in room straight ahead of the room with the Save Point. The Conformer is in the chest on the lower level of the room, in the upper-left corner, hidden from view by a pipe.
5. Morph enemies with the Conformer
The method of obtaining unlimited sources on the Gelnika is to use the Morph command (gained by equipping the Morph materia) on the enemies you fight here. If you kill any of the enemies you find on the Gelnika with the Morph command, they will be transformed into a source, depending on which type of enemy you killed.
Normally, the Morph command does 1/8th the damage your normal attack would have done, which would make getting sources very difficult indeed. The trick to Morphing enemies easily is to have Yuffie in your party, and equip her with her ultimate weapon, the Conformer.
The Conformer does damage related to the level of the enemy you attack with it, bypassing many normal damage calculations, including the damage-reducing effect of Morph. Since the enemies on the Gelnika are all at very high levels, Yuffie's Conformer can easily hit them with Morph for 7000-8000 damage, making it easy for her Morph attack to be the killing blow.
6. Surviving in the Gelnika
A good way to make the tougher enemies in the Gelnika (mostly the 'Unknown' ones) more tolerable is to keep your characters in the back row and equip them with Ribbons or anti-Confuse/anti-Poison armor/accessories (anti-Confuse is more important). This way, your characters will take less damage and do less damage, which means they will have less chance to accidentally finish off enemies. Yuffie's should of course already be in the back row, since her Conformer (like all long-range weapons) will still do full-damage from the back row.
Also, if you are at somewhat low levels and find yourself relying on limit breaks to soften up enemies or simply to survive, buy a bunch of Hypers. Besides 'curing' Sadness* (which some of the enemies here can inflict), using an extra Hyper on your characters will give them Fury status, which means they will get their limit breaks twice as quickly. Honestly, Fury status is almost always useful during the rest of the game, so stocking up on a bunch of Hypers is always a good practice. (Don't forget that you can get as many as you need with the W-Item trick.) The only downside to Fury status is that your physical attacks will miss a bit more frequently, but I find the decreased accuracy usually isn't noticeable. If you're bothered by the reduced accuracy, you can just use magic to attack, which won't miss...
*On the other hand, having your characters in Sadness actually has an advantage as well: your characters will take 30% less damage. If you prefer Sadness over Fury, buy (or duplicate) a bunch of Tranquilizers.
Which enemies give which sources
Power sources come from Unknowns
Guard sources come from Unknown2s
Magic sources come from Unknown3s
Mind sources come from Serpents
Speed sources come from Poodlers
Luck sources come from Bad Raps
Other places to Morph enemies into sources
There are other places to get sources which may be more effective if you are looking to only increase 1 type of stat quickly. For more details, refer to this guide and search for {PER-2} which will take you to the stat maxing section.

A: I vaguely remember leveling off of the big worm (The Midgar Zolom?) SE of the Chocobo farm,  near Midgar. It was an impossible monster before, so it gave lots of experience, but at this point in the game, it wasn't too bad, and I could attack it repeatedly.

A: On your way to the under water reactor hit the alarm on the wall just before leaving junon to go to the reactor. Run around and fight the enemies, best place to level I found at that point in the game.

A: The earliest place to get good exp is Junon.  In the hall that leads to the underwater reactor, there is a switch next to the group of Shinra goons.  Press that and it makes mobs spawn.  I've read that if you're on Disc One, this will produce creatures from the beginning of Disc 2.
I was able to get all my limits to level 3 and max out 2 "all" Materia (which sells for 1.4 gil).  Seeing how there is an Inn that charges a whopping 30 gil a night and has a save point, this is by far the best place until you get the Tiny Bronco. Then you can go to Mideel and kill the head hunters.
As a side note Cloud at this point should have gotten or able to get his Double growth weapon (Force Stealer).  The use a platinum bangle that gives double growth as well.
If you like power leveling then Junon is the place to be. You will also still have all your party members.

A: Forest area by rocket town 90% of the time 1500+ exp and monsters are very easy to defeat power lvd there and gain 30 lvls per character in no time by the end of disc one had loads of materia mastered and nearly all characters lvl 60 +


text:
Q: How can a docker container listen to all docker events? I want to listen to docker events from within a separate docker container, but it is failing an I'm guessing it's because it doesn't have access to the events.
Is there any (simple) way of listening to all docker events from inside a docker container?
I'm using node and the code is working fine (works perfectly on local machine) so I don't think this is really a node question. It has to be related to docker I think.

A: You can share the Docker controlling socket with -v /var/run/docker.sock:/var/run/docker.sock, as shown here for instance. However, there are some caveats: basically, doing this effectively grants full administrator access to the target container.


text:
Q: Solve $\cot x \csc x + \cot x = 0$ $$\cot x \csc x + \cot x = 0$$
Give exact answers in radians.
I tried $$\cot x(\csc x +1)=0$$
$$\cot x =0, \csc x= -1$$
But I'm not sure if that is correct. Please show me how to do this problem. I wanna learn!
Thank you

A: Observe that
$$
\cot x \csc x + \cot x \;\; =\;\; \frac{\cos x}{\sin x} \frac{1}{\sin x} + \frac{\cos x}{\sin x} \;\; =\;\; 0
$$
which is equivalent to
$$
\frac{\cos x}{\sin^2x} \;\; =\;\; - \frac{\cos x}{\sin x}.
$$
Cross-multiplying we find that
$$
\frac{1}{\sin x} \;\; =\;\; -1
$$
or rather $\sin x = -1$.  This should be simple now.  Observe additionally that this also occurs when $\cos x = 0$ which should be simple as well.


text:
Q: how do I use 'tree /F' command to git-bash on Windows? I don't have enough reputation to comment there, so I have to ask a new question here.
I can use cmd //c tree to use Windows' tree in git-bash for Windows. It only shows directory tree. If I want it also display files, how should I do it?
I tried cmd //c tree /F, but I get Invalid drive specification error.

A: Try one (or both) of these variations:
cmd //c tree //F

or
cmd //c "tree /F"


text:
Q: Can Maui configure a shadow in a line? I´m developing an app in .net maui and i have a question i have not answered myself through browsing.
I'm trying to apply a shadow to a border and the following code works perfectly.
   <Border
    Style="{StaticResource light-theme-border}"
    Grid.Column="1"
    Grid.Row="3"
    Grid.ColumnSpan="7">
    <Border.Shadow>
        <Shadow
                Brush="red"
                Offset="1,11"
                Radius="20"
                Opacity="0.25"/>
    </Border.Shadow>
   </Border>

But when i write shadow directly inside the border properties it catches the property but i don't know how to dump the [brush, offset, radius & opacity] info:
    <Border
        Style="{StaticResource light-theme-border}"
        Grid.Column="1"
        Grid.Row="3"
        Grid.ColumnSpan="7"
        Shadow="???????????????????????????">
    </Border>

A: You can then define and consume it as a resource (same what you did with Style property):
<ContentPage.Resources>
        <ResourceDictionary>
            <Shadow
                x:Key="CommonShadow"
                Brush="red"
                Offset="1,11"
                Radius="20"
                Opacity="0.25"/>
    <Border
        Style="{StaticResource light-theme-border}"
        Grid.Column="1"
        Grid.Row="3"
        Grid.ColumnSpan="7"
        Shadow="{StaticResource CommonShadow}">
    </Border>

Or integrate it in your existing style of Border
<ContentPage.Resources>
        <ResourceDictionary>
    <Style x:Key="light-theme-border" TargetType="Border">
                <Setter Property="WidthRequest" Value="20" />
                <Setter Property="Shadow">
                    <Setter.Value>
                        <Shadow
                            Brush="red"
                            Opacity="1"
                            Radius="50"
                            Offset="20,20" />
                    </Setter.Value>
                </Setter>
            </Style>
    <Border
        Style="{StaticResource light-theme-border}"
        Grid.Column="1"
        Grid.Row="3"
        Grid.ColumnSpan="7">
    </Border>

Or integrate it in your existing style of Border as a static resource
<ContentPage.Resources>
        <ResourceDictionary>
             <Shadow
                x:Key="CommonShadow"
                Brush="red"
                Offset="1,11"
                Radius="20"
                Opacity="0.25"/>

            <Style x:Key="light-theme-border" TargetType="Border">
                  <Setter Property="WidthRequest" Value="20" />
                  <Setter Property="Shadow" Value="{StaticResource CommonShadow}"/>
            </Style>
        </ResourceDictionary>
</ContentPage.Resources>

    <Border
        Style="{StaticResource light-theme-border}"
        Grid.Column="1"
        Grid.Row="3"
        Grid.ColumnSpan="7">
    </Border>


text:
Q: Can a UISplitViewController be a tab within UITabViewController? Can I UISplitViewController be a tab within a UITabViewController.
I tried creating a new NIB with the Split View Controller configuration. And added the tab with UISplitViewController as the type to my mainwindow nib. I specified the NIB for the UISplitViewController.
Nothing happened. Can I use IB to link the UISplitViewController defined within my split.nib as a tab in my mainwindow.nib? Not sure how to set it up so that the tab controller can see the view created by the split view controller.

A: Apple guidelines states that you cannot use a UISplitViewController as a child of any other controller. It must be the root view controller of your application.
In some cases, you'll get an exception if you try to do this in code (as opposed to in InterfaceBuilder)


text:
Q: Log4j2 does not write logs to console or file (properties) i tried to add log4j2 to my project, and i want it to write logs to the file and to the console, but no one works...
My log4j2.properties file
appenders = myfileappender,console
appender.myfileappender.type = file
appender.myfileappender.name = myfileappender
appender.myfileappender.fileName = logs/app.log
appender.myfileappender.layout.type = PatternLayout
appender.myfileappender.layout.pattern = %C{1.} {%-5level} %d{HH:mm:ss} - %msg%n
appender.console.type = console
appender.console.name = console
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %C{1.} {%-5level} %d{HH:mm:ss} - %msg%n
rootLogger.appenderRefs = file,console
rootLogger.appenderRefs.file.ref = myfileappender
rootLogger.appenderRefs.console.ref = console
rootLogger.level = all

and my main class:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Main {
    private static final Logger logger = LogManager.getLogger();

    public static void main(String[] args) {
        logger.info("Info msg");
        logger.warn("Warn msg");
        logger.debug("Debug msg");
        logger.error("Err msg");
        logger.fatal("Fat msg");
    }
}

my properties file is in src/main/resources, main class is in src/main/java. I want log4j to write log files to {my-project-root}/logs/app.log

A: Use logback. Put this logback.xml file in your resources
<configuration>
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>logs/output.log</file>
    <append>false</append>
    <immediateFlush>true</immediateFlush>
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>

And add this line to your application.properties file
logging.config=example/path/logback.xml

A: I finally resolved that problem, but not with log4j2. I used logback instead.
Logback.xml file:
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/output.log</file>
        <append>false</append>
        <immediateFlush>true</immediateFlush>
        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <append>false</append>
        <immediateFlush>true</immediateFlush>
        <encoder>
            <pattern>%d{HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

and added this code:
private static final Logger logger;

    static {
        try {
            logger = logbackConfigure();
        } catch (JoranException e) {
            throw new RuntimeException(e);
        }
    }

    public static Logger logbackConfigure() throws JoranException {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        context.reset();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        configurator.doConfigure("src/main/resources/logback.xml");

        Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.setLevel(Level.INFO);
        return root;
    }

istead of:
private static final Logger logger = LogManager.getLogger();


text:
Q: (100) queries parameter: array expected. - facebook SDK C#             string query1 = String.Format("\"query1\":\"SELECT pid, object_id, src_big, owner FROM photo where object_id={0}\"", photoFbId);
            string query2 = String.Format("\"query2\":\"SELECT first_name, last_name FROM user where uid in (select owner from #query1)\"");

            var client = new FacebookClient(accessToken);
            dynamic imageArray = client.Query(query1,query2);

gives (100) queries parameter: array expected. in line dynamic imageArray = client.Query(query1,query2);
What have I done wrong? The Query method accepts params string so it should be fine..

A: If you pass more then one parameter to the Query method, it will automatically use the multi-query instead of single query.
The Facebook C# SDK automatically adds the query1 and query2. you only need to enter the query.
var fb = new FacebookClient("access_token");
dynamic result = fb.Query(
    string.Format("SELECT pid, object_id, src_big, owner FROM photo where object_id={0}", photoFbId),
    "SELECT first_name, last_name FROM user where uid in (select owner from #query1)");

You can then access the values of the fql by.
var result0 = result[0].fql_result_set;
var result1 = result[1].fql_result_set;

You can learn more about making requests using Facebook C# SDK at http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx

A: I downloaded the source.  Assuming that's the one you're using, there is no overload that takes two strings.
    public virtual object Query(string fql)
    {
        Contract.Requires(!String.IsNullOrEmpty(fql));

        var parameters = new Dictionary<string, object>();
        parameters["query"] = fql;
        parameters["method"] = "fql.query";

        return Get(parameters);
    }

    public virtual object Query(params string[] fql)
    {
        Contract.Requires(fql != null);

        var queryDict = new Dictionary<string, object>();

        for (int i = 0; i < fql.Length; i++)
        {
            queryDict.Add(string.Concat("query", i), fql[i]);
        }

        var parameters = new Dictionary<string, object>();
        parameters["queries"] = queryDict;
        parameters["method"] = "fql.multiquery";

        return Get(parameters);
    }


text:
Q: Concatenate i18next and Jade variable I want to output "You are logged in as [Username]" using i18next for the text and a Jade variable as the actual username, but I can't seem to get them working together.
As far as i can tell, i18n overwrites the WHOLE <p> to show "You are logged in as". The username is only shown, if I put it in a separate <p>, like so:
if (user)
  p(data-i18n='markup.loggedInAs')
  p #{user.username}

But then, of course, it gets rendered as a separate <p>, which is not what I want. I want both of them on a single line, ideally inside the same <p>. Is there a trick?
This:
if (user)
  p(data-i18n='markup.loggedInAs')
    | #{user.username}

doesn't work. The username is not shown at all :/
Thanks for your help.

A: Although the points in comments to your post are valid (word order is tricky in translation) I thought I'd point out how to solve the immediate problem.
p
  span(data-i18n='markup.loggedInAs')
  span #{user.username}

Note that this isn't tested, but I'm sure you can see how it (or something similar) would work. span is a better choice for marking up content that doesn't represent an actual paragraph.


text:
Q: Analogue to matlab function "randsrc" I am looking for a function in Python that is similar to randsrc in MATLAB.
I would like to rewrite:
data_points=32;
M=4;
data_source = randsrc(1, data_points, mslice[0:M - 1]);

What is the analogue to randscrc in Python?

A: Python has random module you can use. If you want to construct a list of random elements (as in your example), you can use random.choice and list generator:
[random.choice([1,2,'A',4]) for _ in range(15)]
which will return you:
['A', 1, 'A', 1, 1, 4, 1, 2, 1, 4, 2, 4, 4, 2, 1]
If you want a column of random elements, add brackets in generator:
[[random.choice([111,2,333,4])] for _ in range(15)]
[[2],
 [333],
 [4],
 [2],
 [4],
 [2],
 [111],
 [333],
 [333],
 [333],
 [111],
 [333],
 [2],
 [111],
 [2]]

If you want a random matrix, expand the generator:
[[random.choice([1,2,3,4]) for _ in range(5)] for _ in range(5)]
[[1, 2, 4, 3, 4],
 [4, 2, 1, 1, 1],
 [3, 1, 2, 1, 3],
 [1, 2, 3, 3, 3],
 [2, 1, 3, 1, 2]]

You can store any elemets in the choices "alphabet".


text:
Q: Dynamic SQL not working for changing variable column name in SQL Server I want to write a stored procedure which can be used to update IDs of owner name, backup contact, other contacts etc in a table. These IDs are to fetched from some other table. Instead of writing different stored procedure for all these contact information, I want to write a single dynamic SQL in which I can pass the column name as a variable name.
My stored procedure looks like:
CREATE PROCEDURE spUpdateUser
    (@recordid [NVARCHAR](50),
     @id [NVARCHAR](10),
     @user [NVARCHAR](50))
AS
BEGIN
    DECLARE @sql NVARCHAR(MAX);
    SET NOCOUNT ON;

    SET @sql = N'UPDATE [dbo].[table1]
                 SET'+ QUOTENAME(@user) + ' = (SELECT [dbo].[table2].User
                                               FROM [dbo].[table2]
                                               WHERE [dbo].[table2].id = ' + QUOTENAME(@id) + ')
                WHERE record = ' + QUOTENAME(@recordid)

   EXEC sp_executesql @sql;
END;
GO

After executing the query it runs without error but the user is not changed in table1.
What is missing in the procedure?

A: Don't inject your parameters, parametrise them:
CREATE PROCEDURE spUpdateUser
    -- Add the parameters for the stored procedure here
(   @recordid [nvarchar](50), --Are your IDs really an nvarchar?
    @id [nvarchar](10), --Are your IDs really an nvarchar?
    @user sysname --As this is an object, lets use the correct datatype
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    DECLARE @sql NVARCHAR(MAX),
            @CRLF nchar(2) = NCHAR(13) + NCHAR(10);
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    SET @sql= N'UPDATE [dbo].[table1]' + @CRLF +
              N'SET ' + QUOTENAME(@user) + N' = (SELECT [table2].User' + @CRLF + --3 part naming for columns is deprecated, don't use it
              N'       FROM [dbo].[table2]' + @CRLF +
              N'       WHERE [table2].id= @id)' + @CRLF + --3 part naming for columns is deprecated, don't use it
              N'WHERE record = @recordid;';

   --PRINT @SQL; --Your Best Friend
   EXEC sp_executesql @sql, N'@id nvarchar(10), @recordid nvarchar(50)', @id, @recordid; --Assumes that IDs are an nvarchar again
END;
GO

Note I've left some comments in there for you to consume and review as well.


text:
Q: Is there a windows equivalent to chroot? On a *nix system I can use a chroot to isolate two processes from each other and from the rest of the system.   Is there any similar security system under windows?  Or is there any way to prevent two processes from reading/writing to each others files?

A: Sandboxie http://www.sandboxie.com/
Not exactly like chroot. It does setup a sandbox for each program you specify. It can easily keep processes isolated.

A: I wouldn't use anything like this, you are running under Windows mate.
NTFS has the most fine grained access rights you can find. Its not hard to let a prozess start with lower privileged user, and only giving that user access to the files of this single application.
No need to use something like chroot, which is not a security tool, when you can already define what user is allowed to do what in what directory.
Its no different than like giving the Apache under Linux its own user, only allowed to work inside his folders.

A: To solve this specific need (program assumes it's running off of a root directory), the SUBST command is probably what you want. It's a holdover from DOS, and still exists in windows 10.
the SUBST command will mount a directory as a new drive letter.
then you can run the software from the newly created drive, and it will think it's on your new drive S if you run it from that path.

A: I'm not sure you will gain anything on Windows by chrooting - do you have a specfic need?
In case any the top result on google is http://www.winquota.com/wj/.
Perhaps application virtualization might be an option?  Microsoft has the following to say about it:

In a physical environment, every application depends on its OS for a range of services, including memory allocation, device drivers, and much more. Incompatibilities between an application and its operating system can be addressed by either server virtualization or presentation virtualization; but for incompatibilities between two applications installed on the same instance of an OS, you need Application Virtualization.

A: There is a chroot.exe included in Gow (Gnu On Windows)

A: If you are not uploading files from the website, simply create a read only ISO of your website and make that your root directory, then mount it.
Another solution is to use DISKPART and create a READONLY partition/drive with the webpages.
Hope this was useful.


text:
Q: functionName is not a function? I am trying to use a callback function to place data into an array. When i try to call my callback function 'myCallback' i get an error saying TypeError: callbackFunction is not a function. Here is an example of what the code looks like.
var content = [];

var function1 = function(){
  var function2 = function(){
    query = function(){
      //CAML code
    }
    success = function(callbackFunction){
      callbackFunction("text");// TypeError: callbackFunction is not a function
    }
    failure = function(){
      //Error code
    }
  }
  function2();
  runQuery(one, query, success, failure, two);//Main function
}

function1();

function callbackfunction(data){
  content.push(data)
}

I am following THIS Stack Overflow answer. Maybe I am getting something confused? Not really sure why it is throwing me the error when it is clearly defined in the code.
Thanks pals.

A: You redefined the variable, you need to pass it in.
var content = [];

var function1 = function(callbackfunction){
  var function2 = function(){
    query = function(){
      //CAML code
    }
    success = function(){
      callbackFunction("text");// TypeError: callbackFunction is not a function
    }
    failure = function(){
      //Error code
    }
  }
  function2();
  runQuery(one, query, success, failure, two);//Main function
}

function1(callbackfunction);

function callbackfunction(data){
  content.push(data)
}

And if that is your actual code, you will have issues with global variables if you make more than one call.

A: The variable named callbackFunction passes to the success function has any type but a function and can't be called.

A: You code is not very complete, but I could try to guess that problem is fllowing. You are trying to call a scoped method from inside the success callback, but you overshaddow its declaration by local variable.
success = function(callbackFunction){
  callbackFunction("text");// TypeError: callbackFunction is not a function
}

Try like this:
success = function(){
  callbackFunction("text");// TypeError: callbackFunction is not a function
}

And also move the declaration of the callback to be at the beginning of your code for better readability.