text:
Q: The problem in adding a role when the user has the invitations I have this script for invitations, how can I when the number of invitations is reached the one who made the invitations receives the role?
member.guild.fetchInvites().then(guildInvites => {
    const inv = invites[member.guild.id];
    invites[member.guild.id] = guildInvites;
    const invite = guildInvites.find(i => !inv.get(i.code) || inv.get(i.code).uses < i.uses);
    const inviter = bot.users.get(invite.inviter.id);
    const logChannel = member.guild.channels.find(channel => channel.id === "");
    logChannel.send("<@" + member.user.id + "> " + "** joined**" + " invited by " + inviter.tag + `(${invite.uses} invites)`);
    var role= member.guild.roles.find(role => role.name === "Test");
    if(invite.uses == 25) {
        member.inviter.addRole(role);
    }
});

A: You just need to use invite.inviter (the user who created the invite) instead of member (the member who joined the server).
member.guild.fetchInvites().then(async guildInvites => {
    const inv = invites[member.guild.id];
    invites[member.guild.id] = guildInvites;
    const invite = guildInvites.find(i => !inv.get(i.code) || inv.get(i.code).uses < i.uses);
    const inviter = bot.users.get(invite.inviter.id);
    const logChannel = member.guild.channels.find(channel => channel.id === "");
    logChannel.send("<@" + member.user.id + "> " + "** joined**" + " invited by " + inviter.tag + `(${invite.uses} invites)`);
    if(invite.uses == 25) {
        const role = member.guild.roles.find(role => role.name === "Test");
        const inviterMember = await member.guild.fetchMember(invite.inviter.id);
        inviterMember.addRole(role);
    }
});


text:
Q: How to copy a number of files using command line? I have a 200k files folder that i want to divide into 25k files folders using cp or any other cli command that could do the thing

A: I used this command :
files=(*);
num=$((${#files[@]}/8));
k=1
for ((i=0; i<${#files[@]}; i+=$num)); do
tar cvzf files$k.tgz -- "${files[@]:$i:$num}"
((k++))
done

from this post: How to tar.gz many similar-size files into multiple archives with a size limit shared by Jacob Vlijm. It compress all the files in several .tgz files so that is good for me. You can change the number to divide, here 8 gaves me 8 compressed files with 25k files inside + 1 compressed file with only 2 files inside. That did the job for me.

A: You can use the 'find' command with xargs and passing multi command to first read a value from a file and set it to a variable  which we will use it in new directory name as an ID and then create that directory next move the files into it and increment the ID counter and save it in a file to keep the last value of it.
here is the command,
find -maxdepth 1 -type f |xargs -n25000 bash -c 'readID=$(< ../ID.txt); echo mkdir directory_$readID; echo mv -v $@ -t directory_$readID/; echo $(expr ${readID} + 1)> ../ID.txt'

P.s. note  that please write the start ID in ID.txt file before executing the above command
echo "1" > ../ID.txt

this ID.txt is one level up from current working directory.
once you checked the command and saw what's going on to be happen, then remove 'echo' command from  this command 'echo mv -v $@ -t directory_$readID/;'  and behind 'mkdir' to perform actual move, and reset the ID.txt
echo "1" > ../ID.txt

A: You could tar the directory tree, "split" it, and "cat" it back together.
This might help.  Not verified the commands, but I remember it works, from 400 years ago.
https://unix.stackexchange.com/questions/1588/break-a-large-file-into-smaller-pieces

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to embedd YouTube video when using React and get rid of blocking scroll error? I have one very simple UI showing a text and one embedded video.
When I view in mobile mode smaller resolution,

*

*I cannot start the YouTube video nor interact with it at all. (ON desktop view works fine)

*and see the console warning that am posting here as screenshoot.

*scrolling is blocked

UPDATE:
THIS IS SHOWN ALSO FOR DESKTOP, so it is not the issue that I cannot click and start the video
The code is using react material ui library and is super simple as below
<Card>
            <CardContent>
                <Typography variant={'h5'} align={'center'}>
                    {m.name}
                </Typography>
                {m.description&& <VideoView meta={m.description.video} />}
                {m.description.text && <p>{m.description.text}</p>}
            </CardContent>
        </Card>

and here is VideoMeta.tsx
import React from 'react';

import { Video } from '@/c/components/types';

type Props = {
    meta: Video;
};

const VideoView: React.FC<Props> = (p) => {
    return (
        <iframe
            width="100%"
            height="315"
            src={p.meta.url}
            title="YouTube Video Player"
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
        />
    );
};
export default VideoView;

So injecting the IFRAME as youtube suggests.
The code above generates this kind of test view

This is not working on mobile view in google chrome neither on mobile phones.
Video is shown but

*

*scrolling is blocked

*Cannot click on the video to start and play it! so no interaction


text:
Q: Variation of Fermionic Field Operator Suppose we have a Hamiltonian containing some interaction term
$$V = \sum _{\sigma \sigma '\sigma ''\sigma '''}\iint d^3rd^3r'\hat{\psi }_{\sigma}^\dagger (\textbf{r})\hat{\psi }_{\sigma'}^\dagger (\textbf{r}')V_{\sigma \sigma' \sigma'' \sigma'''}(\textbf{r}-\textbf{r}')\hat{\psi }_{\sigma''} (\textbf{r}')\hat{\psi }_{\sigma'''} (\textbf{r})\tag{1}$$
and we wish to find the functional derivative
$$\frac{\delta \hat{H}}{\delta \hat{\psi }_s (\textbf{r})}. \tag{2}$$
how do we go about this? The definition of the functional derivative is the coefficient of the $ \hat{\psi }_s (\textbf{r}) $ term in the integrand of the variation of the Hamiltonian. But here we have to integrals, meaning that we have two contributions, given by (dropping the hat but still referring to them as operators)
$$ \delta V = \sum _{\sigma _1\sigma _2\sigma _3\sigma _4}\iint d^3rd^3r'\psi ^\dagger _1(r)\psi ^\dagger _2(r')V_{1234}(r-r')\Big[ \left( \psi _3(r') + \delta \psi _3 \right)\left( \psi _4(r) + \delta \psi _4 \right) - \psi _3(r')\psi _4(r) \Big] $$
$$ = \sum _{\sigma _1\sigma _2\sigma _3\sigma _4}\iint d^3rd^3r'\psi ^\dagger _1(r)\psi ^\dagger _2(r')V_{1234}(r-r')\Big[ \delta \psi _3\psi _4(r) + \psi _3(r')\delta \psi _4 + \delta \psi_3\delta \psi _4 \Big]. \tag{3}$$
The next move is to use anti-commutativity to replace $\psi _3(r')\delta \psi _4$ with $-\delta \psi _4\psi _3(r')$ from which we can read off the coefficients. It also gives the expected result when comparing it with the commutator via
$$\left[ \hat{\psi }_{s }^\dagger(\textbf{r}) ,\hat{H} \right] = - \frac{\delta \hat{H}}{\delta \hat{\psi }_s (\textbf{r})}.\tag{4}$$
But I'm having a hard time rigorously justifying that last step. What is the meaning of a small variation in the field operator $\delta \hat{\psi }_i (\rho)$? Is it a well defined mathematical/physical entity? Why does it anti-commute with the regular annihilation field operator?

A: *

*Note that in supermathematics differentiation comes in two versions: Left (right) differentiation, i.e. acting from left (right), respectively. Functional/variational differentiation  similarly comes in two versions:
$$ \int \!d^4x ~ \delta \phi(x)~ \frac{\delta_L F}{\delta \phi(x)} ~=~\delta F~=~ \int \!d^4x ~~ \frac{\delta_R F}{\delta \phi(x)}~ \delta \phi(x).  \tag{A}$$
Since we only consider infinitesimal variations $\delta F$, it is enough to truncate Taylor series in $\delta \phi$ at linear order.

*The left and right derivatives are equal up to a sign factor
$$ \frac{\delta_L F}{\delta \phi(x)}
~=~(-1)^{|\phi|(|F|+1)} \frac{\delta_R F}{\delta \phi(x)}.\tag{B} $$
Here $|\cdot|$ denotes the Grassmann-parity. We should stress that the infinitesimal variation $\delta \phi$ of a field $\phi$ carries the same Grassmann-parity, i.e. $|\delta \phi|=|\phi|$.

*Hence with the canonical anticommutator relation (CAR)
$$ \{\hat{\psi}^{\dagger}_{\alpha}({\bf x}), \hat{\psi}_{\beta}({\bf y})\}_{+}~=~\hbar\delta_{\alpha\beta}~\delta^3({\bf x}-{\bf y})\hat{\bf 1}
,\tag{C}$$
we find OP's eq. (4):
$$\frac{1}{\hbar}[\hat{\psi}^{\dagger}_{\alpha}({\bf x}),\hat{H}]
~=~ \frac{\delta_L \hat{H}}{\delta \hat{\psi}_{\alpha}({\bf x})}
~=~ -\frac{\delta_R \hat{H}}{\delta \hat{\psi}_{\alpha}({\bf x})}.\tag{D}$$


text:
Q: Inline-block vertical-align middle extra spacing issue Line-height is 24px, but the parent element now have 25px height.
My question is why the parent element (block, inline-block or table) will have a extra vertical spacing when a inline-block come with vertical-align: middle?
How can i fixed this issue without float or flexbox? Thanks.

$('span').after($('.block').css('height'));
body {
  line-height: 24px;
}

.block {
  color: #fff;
  background-color: blue;
}

.inline-block {
  display: inline-block;
  vertical-align: middle;
  background-color: red;
  color: #fff;
  padding-left: .5em;
  padding-right: .5em;
}

    .inline-block

    .inline-block

    .inline-block

    .inline-block

  .block

.block height:

A: This seams to fix the issue

$('span').after($('.block').css('height'));
body {
  line-height: 24px;
}

.block {
  color: #fff;
  background-color: blue;
  line-height: 1; //remove space
}

.inline-block {
  display: inline-block;
  vertical-align: middle;
  background-color: red;
  color: #fff;
  padding-left: .5em;
  padding-right: .5em;
  line-height: 24px; //set line-height
}

    .inline-block

    .inline-block

    .inline-block

    .inline-block

  .block

.block height:


text:
Q: Cordova build/run android fails: Cannot read property 'tag' of null I am building an Ionic app and I'd like to use the plugin firebasex.
Unfortunately, when running Ionic cordova build/run android, I am getting the following error: Cannot read property 'tag' of null
It seems my config.xml is OK.
The only thing I found was a missing "name" tag, but it is present in my xml.
If I run cordova run android --verbose, I get the following output:
No scripts found for hook "before_run".
No scripts found for hook "before_prepare".
Checking config.xml and package.json for saved platforms that haven't been added to the project
Config.xml and package.json platforms are the same. No pkg.json modification.
Package.json and config.xml platforms are different. Updating config.xml with most current list of platforms.
PlatformApi successfully found for platform android
Checking config.xml for saved plugins that haven't been added to the project
Checking for any plugins added to the project that have not been installed in android platform
No differences found between plugins added to project and installed in android platform. Continuing...
Generating platform-specific config.xml from defaults for android at C:\[...]\platforms\android\app\src\main\res\xml\config.xml
Cannot read property 'tag' of null
TypeError: Cannot read property 'tag' of null
    at Object.resolveParent (C:\[...]\node_modules\cordova-common\src\util\xml-helpers.js:192:58)
    at Object.graftXMLMerge (C:\[...]\node_modules\cordova-common\src\util\xml-helpers.js:92:37)
    at ConfigFile_graft_child [as graft_child] (C:\[...]\node_modules\cordova-common\src\ConfigChanges\ConfigFile.js:110:42)
    at PlatformMunger_apply_file_munge [as apply_file_munge] (C:\[...]\node_modules\cordova-common\src\ConfigChanges\ConfigChanges.js:81:34)
    at PlatformMunger.reapply_global_munge (C:\[...]\node_modules\cordova-common\src\ConfigChanges\ConfigChanges.js:268:14)
    at updateConfigFilesFrom (C:\[...]\platforms\android\cordova\lib\prepare.js:113:18)
    at Api.module.exports.prepare (C:\[...]\platforms\android\cordova\lib\prepare.js:44:20)
    at Api.prepare (C:\[...]\platforms\android\cordova\Api.js:177:45)
    at C:\[...]\AppData\Roaming\npm\node_modules\cordova\node_modules\cordova-lib\src\cordova\prepare.js:105:36
    at _fulfilled (C:\[...]\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:854:54)

My config.xml:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.my.app" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <allow-navigation href="http://localhost/*" />
    <allow-navigation href="https://localhost/*" />
    <allow-navigation href="ionic://*" />
    <feature name="IonicWebView">
        <param name="android-package" value="com.ionicframework.cordova.webview.IonicWebView" />
    </feature>
    <feature name="File">
        <param name="android-package" value="org.apache.cordova.file.FileUtils" />
        <param name="onload" value="true" />
    </feature>
    <allow-navigation href="cdvfile:*" />
    <feature name="FileTransfer">
        <param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer" />
    </feature>
    <feature name="Camera">
        <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />
    </feature>
    <feature name="StreamingMedia">
        <param name="android-package" value="com.hutchind.cordova.plugins.streamingmedia.StreamingMedia" />
    </feature>
    <feature name="Capture">
        <param name="android-package" value="org.apache.cordova.mediacapture.Capture" />
    </feature>
    <feature name="Base64">
        <param name="android-package" value="com.badrit.Base64.Base64Plugin" />
    </feature>
    <feature name="SocialSharing">
        <param name="android-package" value="nl.xservices.plugins.SocialSharing" />
    </feature>
    <feature name="FileChooser">
        <param name="android-package" value="com.megster.cordova.FileChooser" />
    </feature>
    <name>myapp</name>
    <description>super app</description>
    <author email="contact@contact.contact" href="http://contact.contact/">contact</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
    <allow-intent href="market:*" />
    <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
    <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
    <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
    <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
    <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
    <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
    <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
    <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
    <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
    <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
    <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
    <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
    <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
    <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
    <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
    <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
    <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
    <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    <preference name="loglevel" value="DEBUG" />
    <preference name="webView" value="com.ionicframework.cordova.webview.IonicWebViewEngine" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="19" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <engine name="android" spec="^8.0.0" />
</widget>

Thanks for helping!

A: Remove android platform and add it again
ionic cordova platform rm android
ionic cordova platform add android


text:
Q: Why does the default font for a WinForm only change when display settings is set to "Medium (125%)? When the Display Settings is set to either Small or Large the default font for a WinForm is set to Microsoft Sans Serif, 8.25pt. And everything on the form scales properly. However, when it is set to Medium it changes the default font to Microsoft Sans Serif, 7.8pt, which causes various breaking issues on the form.
Is there a specific reason why the font's size only changes on the Medium setting?

A: Yes, by default if you go past Medium (anything more than 125%) then Windows starts to help and emulates a video adapter set at 96 dots per inch.  Same as Small.  This works by Windows letting the program actually draw into an in-memory bitmap and rescaling the bitmap before blitting it to the screen.  This is an appcompat feature and the result is in general not considered pretty, particularly text becomes 'fuzzy'.  It does however help keep the program usable on very high resolution screens and prevents the main window from having the size of a postage stamp.  Disabling this feature is the subject of this answer, otherwise the exact opposite of what you are looking for.
It works this way because 125% scaling has been around for a long time already, at least as far back as 2001 with the XP release.  So programs are expected to know how to deal with it.  Enabling automatic DPI scalling at 125% is not an option.


text:
Q: Llamada a variable dinamica Javascript Que tal. Mi duda es la siguiente:
Yo creo una variable en javascript dentro de un each:
window["opcion" + v.id] = {var1: 1, var2: 2};

Si yo quiero acceder a ella dentro del mismo each ¿Cómo debo hacer referencia a ella?
Podria ser así: "opcion"+v.id ó opcion+v.id
Espero puedan respuesta a mi duda.

A: Utilizando la primera opción lo puedes lograr:

var v = {id:1}
window["opcion" + v.id] = {var1: 1, var2: 2};

// accedemos al objeto utilizando acceso por indice
console.log(window["opcion"+v.id]);
console.log(window["opcion"+v.id].var1);
console.log(window["opcion"+v.id].var2);

Javascript es un lenguaje bien dinamico por lo que nos ayuda mucho en ciertas circunstancias.

A: Hacemos un each a un select para obtener cada uno de sus hijos option que por cada iteracion agregamos un nuevo valor a la variable global window espero sea lo que buscas
Si lo que quieres es agregar para despues utilizar los valores puedes usar la function push y agregar valores por cada iteracion.
espero te ayude saludos.

$("#myselect").find("option").each(function(){
  window["option"+$(this).attr("value")] = {var1: 1, var2: 2};
  //obtener el objeto completo
  console.log("objeto:",window["option"+$(this).attr("value")])
  //obtener la propiedad var1 dentro del objeto
  console.log("var1:",window["option"+$(this).attr("value")].var1)
  //obtener la propiedad var2 dentro del objeto
  console.log("var2:",window["option"+$(this).attr("value")].var2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect" class="" name="">
    <option value="opcion1">opcion 1</option>
    <option value="opcion2">opcion 2</option>
    <option value="opcion3">opcion 3</option>
    <option value="opcion4">opcion 4</option>
  </select>


text:
Q: Strange symbols in Hue I am running a query in hue and as result I take values with this symbol:
ted�
nick� koro

Is this has to do with ASCII or UNIX? I do not have access to the source data.

A: This result is sticky unicode characters , u can select it and convert it to nvarchar
Select Cast(table.? as nvarchar(50)) from table


text:
Q: Remover play automático de script Javascript Boa noite, pessoal. Eu achei um código aqui na stack para playlist aleatória de áudio e adaptei para que pudesse rodar vídeos, porém sou nova em Javascript e não sei fazer quase nada. Preciso até de um tutorial de repente. Mais completo, é claro, pois os que assisti não me ajudaram muito.
O código abaixo é o código da playlist que preciso. O único problema é que vou rodar a playlist em um slide do Reveal.js e usei a configuração autoplaymedia=true. Essa opção permite que o vídeo só carregue quando o slide com o vídeo é exibido. Porém para funcionar, o javascript não pode carregar o vídeo automaticamente e sim o Reveal.js. Eu preciso basicamente que seja removida do script abaixo a opção de reproduzir automaticamente, pois é o que está sendo feito.
/* Objects */
var _player = document.getElementById('player');

/* Aplication */
var tracks = [

'http://media.w3.org/2010/05/sintel/trailer.mp4',

function playNext() {
  var track = tracks[Math.floor(Math.random() * tracks.length)];

  _player.src = track;
  return _player.play();
}

/* Events */
window.addEventListener('load', playNext);
_player.addEventListener('ended', playNext);

Link para codepen (baseado no código de Caio Tarifa):
Link para codepen

A: Nesse seu caso para retirar a reprodução automática é simples.
Basta retirar  return _player.play(); do seu script.
Porém não vai ter como reproduzir o vídeo se não colocar o parâmetro  controls  na div video
Script

/* Objects */
var _player = document.getElementById('player');

/* Aplication */
var tracks = [
  'http://media.w3.org/2010/05/sintel/trailer.mp4',
  'http://mirror.cessen.com/blender.org/peach/trailer/trailer_iphone.m4v',
  'https://ia800209.us.archive.org/20/items/ElephantsDream/ed_1024.mp4',
];

function playNext() {
  var track = tracks[Math.floor(Math.random() * tracks.length)];

  _player.src = track;

}

/* Events */
window.addEventListener('load', playNext);
_player.addEventListener('ended', playNext);
<video id="player" controls>
  O seu navegador não suporta vídeo em HTML5.
</video>


text:
Q: NServiceBus and Azure Service Bus message lost I've been experiencing a weird but reoccuring behavior when using NServiceBus and Azure Service Bus.
When publishing the API, I notice that sometimes (sadly this is not stable behavior that will occur every time) where the processing of the request appears to be completed but the message does not arrive in the destination queue.
This is hard to reproduce, since the behavior is not occurring with every deployment, but here's at least the basic processing of the request:
Using the model, I create a command, and use this to send it over an injected IBus. There is no database interaction besides the authentication. The bus itself is created using the following configuration:
var configuration = new BusConfiguration();
configuration.EndpointName("Api");
configuration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
configuration.UseTransport<AzureServiceBusTransport>();
configuration.AzureConfigurationSource();
configuration.UsePersistence<InMemoryPersistence>();

var conventionsBuilder = configuration.Conventions();
conventionsBuilder.DefiningCommandsAs(t => t.Namespace != null && t.Namespace.StartsWith("Abc.") && t.Namespace.EndsWith("Commands"));
conventionsBuilder.DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("Abc.") && t.Namespace.EndsWith("Events"));
conventionsBuilder.DefiningMessagesAs(t => t.Namespace != null && t.Namespace.StartsWith("Abc.") && t.Namespace.EndsWith("RequestResponse"));

ISendOnlyBus bus = Bus.CreateSendOnly(configuration);

I've tried the following methods to reproduce it locally:

*

*Start local emulator while hitting the local development endpoint every 20ms.

*Use local IIS.

*Use local IIS with a one minute timeout and hitting it every 90 seconds for 5 seconds.

*Use local IIS with recycles + stop and starts

Locally I've not been able to reproduce, every message always arrived.
On Azure it runs on a small cloud service.
Any thoughts or pointers would be hugely appreciated.


text:
Q: Get direct link videos from Vimeo in PHP I want a direct link to videos from Vimeo with a PHP script.
I managed to find them manually, but my PHP script does not work.
Here is the initiative:
For example I took this video: http://vimeo.com/22439234
When you go on the page, Vimeo generates a signature associated with the current timestamp and this video. This information is stored in a JavaScript variable, around line 520 just after:
window.addEvent ('domready', function () {
Then when you click Play, the HTML5 player reads this variable and sends an HTTP request:
http:// player.vimeo.com/play_redirect?clip_id=37111719&sig={SIGNATURE}&time={TIMESTAMP}&quality=sd&codecs=H264,VP8,VP6&type=moogaloop_local&embed_location=

But it also works with:
http:// player.vimeo.com/play_redirect?clip_id=37111719&sig={SIGNATURE}&time={TIMESTAMP}&quality=sd

If this URL does not open with the IP address that opened http://vimeo.com/22439234, this returns the HTTP code 200 with an error message.
If this URL is opened with the correct IP address, the header "Location" redirects to link to the video file:
http://av.vimeo.com/XXX/XX/XXXX.mp4?aksessionid=XXXX&token=XXXXX_XXXXXXXXX
When I build this link http://player.vimeo.com/play_redirect?... manually ("right click"> "source code"> "line 520") it works.
But with PHP and regex it returns the HTTP code 200 with an error message.
Why ?
From my observations, Vimeo does not check the headers of the HTTP request for http:// player.vimeo.com/play_redirect?...
GET, HEAD, with cookies, without cookies, referrer etc. ... does not change.
With PHP, I use the function file_get_contents() and get_headers().
    <?php
    function getVimeo($id) {

    $content = file_get_contents('http://vimeo.com/'.$id);

    if (preg_match('#document\.getElementById\(\'player_(.+)\n#i', $content, $scriptBlock) == 0)
        return 1;

    preg_match('#"timestamp":([0-9]+)#i', $scriptBlock[1], $matches);
    $timestamp = $matches[1];
    preg_match('#"signature":"([a-z0-9]+)"#i', $scriptBlock[1], $matches);
    $signature = $matches[1];

    $url = 'http://player.vimeo.com/play_redirect?clip_id='.$id.'&sig='.$signature.'&time='.$timestamp.'&quality=sd';

    print_r(get_headers($url, 1));
    }

A: The algorithm looks like this:

*

*Input data: vimeoUrl.

*content = getRemoteContent(vimeoUrl).

*Parse content to find and extract the value from data-config-url
attribute.

*Navigate to data-config-url and load the content as JSON Object:
$video = json_decode($this->getRemoteContent($video->getAttribute('data-config-url')));

*Return $video->request->files->h264->sd->url — this will return a
direct link for SD quality video.

Here is my simple class, that working for this moment.
class VideoController
{

    /**
     * @var array Vimeo video quality priority
     */
    public $vimeoQualityPrioritet = array('sd', 'hd', 'mobile');

    /**
     * @var string Vimeo video codec priority
     */
    public $vimeoVideoCodec = 'h264';

    /**
     * Get direct URL to Vimeo video file
     *
     * @param string $url to video on Vimeo
     * @return string file URL
     */
    public function getVimeoDirectUrl($url)
    {
        $result = '';
        $videoInfo = $this->getVimeoVideoInfo($url);
        if ($videoInfo && $videoObject = $this->getVimeoQualityVideo($videoInfo->request->files))
        {
            $result = $videoObject->url;
        }
        return $result;
    }

    /**
     * Get Vimeo video info
     *
     * @param string $url to video on Vimeo
     * @return \stdClass|null result
     */
    public function getVimeoVideoInfo($url)
    {
        $videoInfo = null;
        $page = $this->getRemoteContent($url);
        $dom = new \DOMDocument("1.0", "utf-8");
        libxml_use_internal_errors(true);
        $dom->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $page);
        $xPath = new \DOMXpath($dom);
        $video = $xPath->query('//div[@data-config-url]');
        if ($video)
        {
            $videoObj = json_decode($this->getRemoteContent($video->item(0)->getAttribute('data-config-url')));
            if (!property_exists($videoObj, 'message'))
            {
                $videoInfo = $videoObj;
            }
        }
        return $videoInfo;
    }

    /**
     * Get vimeo video object
     *
     * @param stdClass $files object of Vimeo files
     * @return stdClass Video file object
     */
    public function getVimeoQualityVideo($files)
    {
        $video = null;
        if (!property_exists($files, $this->vimeoVideoCodec) && count($files->codecs))
        {
            $this->vimeoVideoCodec = array_shift($files->codecs);
        }
        $codecFiles = $files->{$this->vimeoVideoCodec};
        foreach ($this->vimeoQualityPrioritet as $quality)
        {
            if (property_exists($codecFiles, $quality))
            {
                $video = $codecFiles->{$quality};
                break;
            }
        }
        if (!$video)
        {
            foreach (get_object_vars($codecFiles) as $file)
            {
                $video = $file;
                break;
            }
        }
        return $video;
    }

    /**
     * Get remote content by URL
     *
     * @param string $url remote page URL
     * @return string result content
     */
    public function getRemoteContent($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, 'spider');
        $content = curl_exec($ch);

        curl_close($ch);

        return $content;
    }

}

Using:
$video = new VideoController;
var_dump($video->getVimeoDirectUrl('http://vimeo.com/90747156'));

A: Try add a valid user-agent to headers for an each request.
For this you must use cURL or HttpRequest instead file_get_contents().
After such manipulations I got a working link for downloading the video file.
Here my code:
function getVimeo($id) {
    // get page with a player
    $queryResult = httpQuery('http://vimeo.com/' . $id);
    $content = $queryResult['content'];

    if (preg_match('#document\.getElementById\(\'player_(.+)\n#i', $content, $scriptBlock) == 0)
        return 1;

    preg_match('#"timestamp":([0-9]+)#i', $scriptBlock[1], $matches);
    $timestamp = $matches[1];
    preg_match('#"signature":"([a-z0-9]+)"#i', $scriptBlock[1], $matches);
    $signature = $matches[1];

    $url = 'http://player.vimeo.com/play_redirect?clip_id=' . $id . '&sig=' . $signature . '&time=' . $timestamp . '&quality=sd';

    // make the request for getting a video url
    #print_r(get_headers($url, 1));
    $finalQuery = httpQuery($url);
    return $finalQuery['redirect_url'];
}
// make queries via CURL
function httpQuery($url) {
    $options = array(
        CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.168 Chrome/18.0.1025.168 Safari/535.19',
        CURLOPT_RETURNTRANSFER => true,
    );
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    $result = $info;
    $result['content'] = $content;

    return $result;
}

echo getVimeo(22439234);


text:
Q: Jquery for replace bullet unicode I am using following jQuery code to replace [bullet/] with its unicode character:
html = html.replace(/\[bullet/gi, '•');

However it's not working. Does anyone know what I've done wrong?

A: Two problems there:

*

*[ is a special character in regular expressions (it marks the beginning of a character class), so your regex is invalid (you should have been getting an error about this in the web console, telling you what was wrong). To literally match a [, you have to escape it:
html = html.replace(/\[bullet/gi, '•');
// Backslash here ---^

*Separately, that will match [bullet, not [bullet/]. If you want to match the whole thing, you have to put the whole thing in:
html = html.replace(/\[bullet\/\]/gi, '•');

Note that like [, / is a special character (the delimiter), so you have to escape it as well. I also escaped ], but you don't really need to outside a character class.
This also works if you're using the entity:
html = html.replace(/\[bullet\/\]/gi, '•');

Gratuitous example:

var str;

str = "foo [bullet/] bar [bullet/] baz";
snippet.log("Before: " + str);
str = str.replace(/\[bullet\/\]/gi, '•');
snippet.log("After: " + str);

str = "foo [bullet/] bar [bullet/] baz";
snippet.log("Before: " + str);
str = str.replace(/\[bullet\/\]/gi, '•');
snippet.log("After: " + str);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


text:
Q: Random spawn avoiding colliders I am working on a 2D game with colleagues that is basically a fighting game on a vertical map with platforms. Right now I am spawning items on the map for player to gather, but I was wondering how could I do that while checking that I'm not in one of the platform's collider to avoid spawning the item in?

A: You should take a look at the overlap functions from Physics2D (for example here). Just generate a drop position and pass it to this function, if it returns null then the position is free. If you get unexpected results make sure to set the layer mask to the same as the platforms or whatever objects you don't want to intersect with.


text:
Q: Find all elements containing a value in an attribute I use this to take some attributes:
window.document.getElementsByClassName("atbk")

However the class atbk is used in different elements. I would like to keep the attributes which only have in their href a common word /url
I tried this:
window.document.getElementsByClassName("atbk").href.indexOf("/url")

but it is not helpful. Is there anything I could do?

A: You can use the css selector [href*="/url"] to select elements containing a substring in an attribute.
window.document.querySelectorAll('.atbk[href*="/url"]');

A: Try this:
var list = window.document.getElementsByClassName("atbk");
var newlist =[];
for (z = 0; z < list.length; z++)
{
     if (list[z].href.indexOf('/url') > -1)
     {
         newlist.push(list[z]);
     }
}

// use newlist...


text:
Q: How can Mysql Query Acceleration How can I make this query faster. Currently in 4ms. It works very slowly.
SELECT  oe.hareket down to 0.2 seconds. How can I optimize it. Thanks in advance.
SELECT
  og.ogrenciId,
  og.adSoyad,
  eo.istikamet,`enter code here`
  (
    SELECT
      oe.hareket
    FROM
      ogrencietkinlik oe
    WHERE
      oe.istikamet = 1
      AND oe.ogrenciId = eo.ogrenciId
      and oe.zaman BETWEEN "2019-02-15 00:00:00"
      AND "2019-02-1523:59:59"
    ORDER BY
      oe.ogrencietkinlikId DESC
    LIMIT
      0, 1
  ) as hareket,
  (
    SELECT
      oadr.lat
    FROM
      ogrenciadres oadr
    WHERE
      og.ogrenciId = oadr.ogrenciId
    ORDER BY
      oadr.ogrenciadresId DESC
    LIMIT
      0, 1
  ) as lat,
  (
    SELECT
      oadr.lng
    FROM
      ogrenciadres oadr
    WHERE
      og.ogrenciId = oadr.ogrenciId
    ORDER BY
      oadr.ogrenciadresId DESC
    LIMIT
      0, 1
  ) as lng,
  (
    SELECT
      oadr.acikAdres
    FROM
      ogrenciadres oadr
    WHERE
      og.ogrenciId = oadr.ogrenciId
    ORDER BY
      oadr.ogrenciadresId DESC
    LIMIT
      0, 1
  ) as acikAdres
FROM
  ogrenci og
  LEFT JOIN eslestirmeservisogrenci eo ON eo.ogrenciId = og.ogrenciId
  AND eo.servisId = "5"
WHERE
  og.okulId = "4"
  and og.firmaId = "2"
  and og.durum = 0
  and eo.firmaId = "2"
  and eo.durum = 0
ORDER BY
  eo.sira ASC


text:
Q: Spyder Ipython: pop up of function arguments after '"(" for functions of inherited cython class How can I modify my cython class or my ipython settings and spyder settings, so that, while working in ipython and in the editor, the function arguments are displayed automatically?
I have written a class in cython (cyclass, with cdef class) which is inherited to another python class (pyclass). Now, in workspace I have a pyclass object and want to  access the cyclass functions with automated argument pop up. Is this possible?
I'm glad for any help, thank you


text:
Q: Using an existing expression/func to build out another expression/func I want to be able to use a generic method to select a property and pass that into the Any() method.
private List<TModel> _models;

public bool Any<TModel, TProperty>(
  Expression<Func<TModel, TProperty>> propertySelector,
  TModel model)
{
  // ....
}
// OR
public bool Any<TModel, TProperty>(
  Func<TModel, TProperty> propertySelector,
  TModel model)
{
  // ....
}

I'm not sure how to take the propertySelector and use it with the Any() on a List<TModel>.
This is close, but I'm missing something:
_models.Any(m => propertySelector(m) == propertySeletor(model));

Operator '==' cannot be applied to operands of type 'TProperty' and 'TProperty'

What am I missing here?
The question is more of a contrived example, as the Expression will ultimately be consumed by entity-framework-core to build a query.

A: If the question is how to build Expression<Func<TModel, bool>> from Expression<Func<TModel, TProperty>> and TModel representing equal predicate, it could be done like this:
// Expression<Func<TModel, TProperty>> propertySelector
// TModel model
var parameter = propertySelector.Parameters[0];
var left = propertySelector.Body;
var right = Expression.Invoke(propertySelector, Expression.Constant(model));
var body = Expression.Equal(left, right);
var predicate = Expression.Lambda<Func<TModel, bool>>(body, parameter);

The essential parts are the Expression.Equal (the expression equivalent of == operator) and the expression for invoking the property selector on the passed object instance.
In case the query provider does not support invocation expressions, it could be replaced with
var right = propertySelector.Body.ReplaceParameter(
    propertySelector.Parameters[0],
    Expression.Constant(model));

where ReplaceParameter is the usual ExpressionVisitor based helper for replacing ParameterExpression with another arbitrary expression (pretty much like string.Replace, but with expressions):
public static partial class ExpressionUtils
{
    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
        => new ParameterReplacer { Source = source, Target = target }.Visit(expression);

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node)
            => node == Source ? Target : node;
    }
}

A: The Any methods in your question look like they were intended to be extension methods on a source sequence but they were missing the parameter for the target object.
Conceptually, this is what I believe you were looking to do:
public static bool Any<TEntity, TProperty>(this IEnumerable<TEntity> source, Func<TEntity, TProperty> selector, TEntity other)
{
    if (source is null)
        throw new ArgumentNullException(nameof(source));
    if (selector is null)
        throw new ArgumentNullException(nameof(selector));
    if (other == null)
        throw new ArgumentNullException(nameof(other));

    TProperty otherProperty = selector(other);

    return source.Any(item => EqualityComparer<TProperty>.Default.Equals(selector(item), otherProperty));
}

Now, that'll work on objects in memory, but since you have the entity-framework-core tag, we'll need something that deals with expressions.
To do that, we must first evaluate the property to get the value against which we'll be comparing each entity's selected property.  In memory, we just call selector(other) and we're done.  Since we have to deal with an expression now, we need to compile the expression first.  That's fairly simple.
The next step is to build an expression that represents selector(item) == otherValue.  Fortunately, we don't need to replace the parameter since we're not trying to fold two separate lambdas into the same expression.  We can simply reuse selector's first parameter.  We then call Expression.Invoke with the selector and its parameter, which will be translated into the column reference in the SQL.
Finally, we build the lambda that we can pass along to the built-in Any method.
public static bool Any<TEntity, TProperty>(this IQueryable<TEntity> source, Expression<Func<TEntity, TProperty>> selectorExpression, TEntity other)
{
    if (source is null)
        throw new ArgumentNullException(nameof(source));
    if (selectorExpression is null)
        throw new ArgumentNullException(nameof(selectorExpression));
    if (other == null)
        throw new ArgumentNullException(nameof(other));

    ParameterExpression itemParameter = selectorExpression.Parameters[0];
    ConstantExpression otherValue = Expression.Constant(selectorExpression.Compile()(other), typeof(TProperty));

    BinaryExpression equalExpression = Expression.Equal(Expression.Invoke(selectorExpression, itemParameter), otherValue);

    Expression<Func<TEntity, bool>> predicate = Expression.Lambda<Func<TEntity, bool>>(equalExpression, itemParameter);

    return source.Any(predicate);
}

In my own testing, using SQL Profiler to confirm, I was able to get the condition to evaluate in the SQL query.  After changing the property selection expression, the query changed accordingly.


text:
Q: How to save files from C to browser storage with emscripten The game engine that I'm using to run my game in the browser runs lua and from my game i save files using normal fopen / write / fclose. The engine C/C++ code is compiled to JS through emscripten. What is a good way to get these file writes to end up in local storage, or some other in browser cache location? I have searched the web and looked at the documentation but information is very sparse, I have not found any clear answers to how this is supposed to work.
A previous contributor to the game engine added a js library to the emscripten build, that would override fclose to call back to javascript. But this fclose override does not seem to get called anymore, it is not included in the final .js file at all.

A: Emscripten Filesystem API covers your case using IndexedDB.
Here is the Filesystem API overview. It has four types:

*

*MEMFS: A volatile, in-memory storage. This is the default filesystem type which is mounted at / at runtime.

*NODEFS: This uses node.js fs api, which is not your case.

*IDBFS: This makes use of IndexedDB and you may use it for offline storage.

*WORKERFS: This is intended to be used inside of a worker.

You can use IDBFS with Emscripten's own FS API (This is JavaScript-side API though). You need to mount it first in order to use it. You can achieve it by using FS.mkdir,FS.mount, and FS.syncfs. Here is a rough example in C:
#include <emscripten.h>

int main() {
    // EM_ASM is a macro to call in-line JavaScript code.
    EM_ASM(
        // Make a directory other than '/'
        FS.mkdir('/offline');
        // Then mount with IDBFS type
        FS.mount(IDBFS, {}, '/offline');

        // Then sync
        FS.syncfs(true, function (err) {
            // Error
        });
    );

    // Use fopen / write / fclose in C here.
    int off_file = fopen("/offline/any_file");
    ...

    // Don't forget to sync to make sure you store it to IndexedDB
    EM_ASM(
        FS.syncfs(function (err) {
            // Error
        });
    );
}

Here is a more detailed example from Emscripten repository.


text:
Q: For UNEVEN structured data, 'comparing and replacing' values using Pandas I have 2 csv files with UNEVEN structured data. I want to compare the 'STag' and 'E1' columns values of both the files using ITERATION and if they are equal then replace the respective 'E1_CUI' column value of 'file2_data' with 'E1_CUI' column value of 'file1_data'. I got the ValueError: Can only compare identically-labeled Series objects. For reference please consider below example.
CODE
import pandas as pd
file1_data = {
    'STag': ['Title_1', 'Title_1', 'Abs_1', 'Abs_3', 'Abs_3', 'Abs_4', 'Abs_4'],
    'E1': ['pacnes', 'PI', 'acne', 'pacnes', 'pI', 'kera', 'PPI'],
    'E1_CUI': ['C3477', 'C9871', 'C2166', 'C3477', 'C9871', 'C2567', 'C9871']
}
df1 = pd.DataFrame(file1_data)
df1

    E1      E1_CUI  STag
0   pacnes  C3477   Title_1
1   PI      C9871   Title_1
2   acne    C2166   Abs_1
3   pacnes  C3477   Abs_3
4   pI      C9871   Abs_3
5   kera    C2567   Abs_4
6   PPI     C9871   Abs_4

file2_data = {
    'STag': ['Title_1', 'Abs_1', 'Abs_3', 'Abs_4'],
    'E1': ['pacnes', 'acne', 'pI', 'kera'],
    'E1_CUI': [0, 0, 0, 0]
}
df2 = pd.DataFrame(file2_data)
df2

    E1      E1_CUI  STag
0   pacnes  0       Title_1
1   acne    0       Abs_1
2   pI      0       Abs_3
3   kera    0       Abs_4

for row,col in df1.iterrows():
    if (df1['STag'] == df2['STag'] and df1['E1'] == df2['E2']):
        df2['E1_CUI'] = df1['E1_CUI']

ERROR
ValueError: Can only compare identically-labeled Series objects

Expected Output DataFrame
    E1      E1_CUI  STag
0   pacnes  C3477   Title_1
1   acne    C2166   Abs_1
2   pI      C9871   Abs_3
3   kera    C2567   Abs_4


text:
Q: Finding a matrix U such that B=UA. A=
\begin{bmatrix}
1 &  0 & 1 \\
2 &  3 & 1 \\
\end{bmatrix}B=
\begin{bmatrix}
1 &  3 & 0 \\
4 &  3 & 3 \\
\end{bmatrix}
How does one go about solving this problem?
Find the matrix U such that B=UA and express U as a product of elementary matrices.
Basically, I tried solving the problem using trial and error trying to go from A to B and applying those elementary row operation to the identity matrix to make U. However, this method is still not efficient enough in my head.
So, is there a faster method? (Even by trial and error, I could not find the matrix. I am not good with trial and error.)

A: Hint: (the first two columns of $B$) is $U$ times (the first two columns of $A$).
If the first two columns of $A$ formed the identity matrix, $U$ would just be the first two columns of $B$.  It isn't, but you can take some row operations...
EDIT: In row reduction of $A$, the first step might be subtracting $2$ times row $1$ from row $2$.  This is accomplished by the matrix multiplication $E_1 A$, where $E_1$ is the elementary matrix $\pmatrix{1 & 0\cr -2 & 1\cr}$.
One more row operation, corresponding to an elementary matrix $E_2$, gives you
a matrix whose first two columns are the identity, i.e.
$$E_2 E_1 A = \pmatrix{1 & 0 & *\cr 0 & 1 & *\cr}$$
(where I'm not specifying what the $*$ entries are).
Similarly, there are elementary matrices $E_3$, $E_4$ such that the first two
columns of $E_3 E_4 B$ form the identity matrix.  If it happens that
$E_3 E_4 B = E_1 E_2 A$ (which is something you should check!), then
$B = E_4^{-1} E_3^{-1} E_1 E_2 A$, so you can take $U = E_4^{-1} E_3^{-1} E_1 E_2$ (note that the inverse of an elementary matrix is an elementary matrix).

A: For the first part: Firstly observe that since $A,B$ have dimension $2\times 3$ then $U$ has dimension $2\times2$. Thus $$U=\begin{pmatrix}u_1 &u_2 \\ u_3 & u_4\end{pmatrix}$$ Multiplying U with A and setting equal to B gives you the set of equations $$\begin{cases}u_1+2u_2=1 \\0u_1+3u_2=3\\u_1+u_2=0\end{cases}$$ and similarly for $u_3,u_4$. The result is $$U=\begin{pmatrix}-1 &1 \\ 2 & 1\end{pmatrix}$$
For the second part: An elementary matrix is a matrix that differs from the identity matrix by one single elementary row operation. For this I do not see another way (to the moment) than trial and error.

A: We want to perform row operations on $A$ in order to transform it into $B$. By inspection, notice that we can do this by:

*

*Adding ($2$ times row $1$) to row $2$ to get:
$$
\begin{bmatrix}
1 &  0 & 1 \\
4 &  3 & 3 \\
\end{bmatrix}
$$

*Scaling (row $1$) by $3$ to get:
$$
\begin{bmatrix}
3 & 0 & 3 \\
4 & 3 & 3 \\
\end{bmatrix}
$$

*Adding ($-1$ times row $2$) to row $1$ to get:
$$
\begin{bmatrix}
-1 & -3 & 0 \\
4 & 3 & 3 \\
\end{bmatrix}
$$

*Scaling (row $1$) by $-1$ to get:
$$
\begin{bmatrix}
1 & 3 & 0 \\
4 & 3 & 3 \\
\end{bmatrix}
$$

It remains to translate each row operation to an elementary matrix and multiply them together.

A: Denote $A^T$ the matrix transpose of $A$ and $C^{-1}$ the matrix inverse of square matrix $C$. Then we have:
$$UA=B\implies U(A.A^T)=B.A^T\implies U=B.A^T (A.A^T)^{-1}$$
$$\implies U=\begin{pmatrix}-1 &1 \\ 2 & 1\end{pmatrix}$$


text:
Q: Search and replace with sed Last week I accidently externalized all my strings of my eclipse project. I need to revert this and my only hope is sed. I tried to create scripts but failed pathetically because I'm new with sed and this would be a very complicated operation. What I need to do is this:
Strings in class.java file is currently in the following format(method) Messages.getString(<key>). Example :
    if (new File(DataSource.DEFAULT_VS_PATH).exists()) {
        for (int i = 1; i <= c; i++) {
            if (!new File(DataSource.DEFAULT_VS_PATH
                    + Messages.getString("VSDataSource.89") + i).exists()) { //$NON-NLS-1$
                getnewvfspath = DataSource.DEFAULT_VS_PATH
                        + Messages.getString("VSDataSource.90") + i; //$NON-NLS-1$
                break;
            }
        }
    }

The key and matching Strings are in messages.properties file in the following format.
VSDataSource.92=No of rows in db =
VSDataSource.93=Verifying db entry :
VSDataSource.94=DB is open
VSDataSource.95=DB is closed
VSDataSource.96=Invalid db entry for
VSDataSource.97=\ removed.
key=string

So I need the java file back in this format:
    if (new File(DataSource.DEFAULT_VS_PATH).exists()) {
        for (int i = 1; i <= c; i++) {
            if (!new File(DataSource.DEFAULT_VS_PATH
                    + "String 2" + i).exists()) { //$NON-NLS-1$
                getnewvfspath = DataSource.DEFAULT_VS_PATH
                        + "String 1" + i; //$NON-NLS-1$
                break;
            }
        }
    }

How can I accomplish this with sed? Or is there an easier way?

A: No source control? tsk, tsk.  I'd suggest fixing that problem before running this script that worked for me on a very small sample:
#!/bin/bash
set -x
for i in `seq 92 97`
do
    X=$(sed -n s/^VSDataSource.$i=//p messages.properties)
    sed -i "s+Messages.getString(\"VSDataSource.`echo $i`\")+\"`echo $X`\"+g" class.java
done

Of course, change the args to seq and sed (*java instead of class.java, perhaps).  Seriously, though, there's no way this is the best solution to your problem.  If it has an 'externalize strings' button, shouldn't your IDE have an 'internalize strings' button?

A: The "trick" is to make a sed script out of the message.properties:
$ sed 's!/!\\!;s!\([^=]*\)=\(.*\)!s/"\1"/"\2"/g!' message.properties > message.sed
$ sed -f messages.sed class.java > class.java.reverted
$ rm messages.sed

You start with something like:
VSDataSource.92=No of rows in db =
VSDataSource.93=Verifying db entry :
VSDataSource.NN=Foo/bar

And end up with:
s/"VSDataSource.92"/"No of rows in db= "/g
s/"VSDataSource.93"/"Verifying db entry : "/g
s/"VSDataSource.NN"/"Foo\/bar"/g


text:
Q: when mouseover or out change icon marker What i want is when user do mouseover (hover) then the icon change. My code is below:
handler = Gmaps.build("Google", {
markers: {
  maxRandomDistance: null
}
});
handler.buildMap({
provider: {},
internal: {
  id: "map-canvas"
}
}, function() {
var markers;
markers = handler.addMarkers(ar);
_.each(ar, function(json, index) {
  json.marker = markers[index];
  $(".location-" + json.id).on("mouseover", function() {
    json.picture = {
      url: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
      width: 36,
      height: 36
    };
    json.marker.setMap(handler.getMap());
    json.marker.panTo();
    handler.removeMarker(json.marker);
    handler.addMarker(json);
  }).on("mouseout", function() {
    json.picture = '';
    handler.removeMarker(json.marker);
    handler.addMarker(json);
  });
});
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});

Using this code, the color of the marker can change from red to green. However, when the user remove their mouse from the hover area, the color does not change back to the original color. Please can anyone suggest me on this issue?
Thanks

A: Hai thank for @apneadiving answer. I modify my code to this
hoverPicture = {
url: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
width: 33,
height: 33
};
handler = Gmaps.build("Google", {
markers: {
  maxRandomDistance: null
}
});
handler.buildMap({
provider: {},
internal: {
  id: "map-canvas"
}
}, function() {
var markers;
markers = handler.addMarkers(ar);
_.each(ar, function(json, index) {
  var gr;
  json.marker = markers[index];
  gr = {};
  gr.marker = void 0;
  $(".location-" + json.id).on("mouseover", function() {
    gr = {
      lat: json.lat,
      lng: json.lng,
      picture: hoverPicture
    };
    json.marker.panTo();
    handler.removeMarker(json.marker);
    gr.marker = handler.addMarker(gr);
  }).on("mouseout", function() {
    handler.removeMarker(gr.marker);
    json.marker = handler.addMarker(json);
  });
});
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});

So the new icon need to insert to variable after addMarker

A: Try something like:
_.each(ar, function(json, index) {

  var json.marker = markers[index];
  var initialPicture = json.picture;
  var hoverPicture = {
    url: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
    width: 36,
    height: 36
  }

  $(".location-" + json.id).on("mouseover", function() {
    json.picture = hoverPicture;
    json.marker.setMap(handler.getMap());
    json.marker.panTo();
    handler.removeMarker(json.marker);
    handler.addMarker(json);
  }).on("mouseout", function() {
    json.picture = initialPicture;
    handler.removeMarker(json.marker);
    var newMarker = handler.addMarker(json);
    json.marker = newMarker;
  });
});


text:
Q: How do I dynamically run a React Native app inside another React Native app? Can it be done besides basic integration of code? Ideally, a RN app should be able to dynamically download the bundle of a nested app from the server. Then it should execute the bundle inside some kind of customized root in the view. It should also have a basic life cycle control over the nested app. Is it technically possible?

A: You are probably looking for something like CodePush.
The root component of your application have to be wrapped into codePush's higher-order component:
import codePush from "react-native-code-push";

class MyApp extends Component {
}

MyApp = codePush(MyApp);

Then you can release js bundle updates any time from the cli:
code-push release-react <appName> <platform>


text:
Q: Ruby equivalent of virtualenv? Is there something similar to the Python utility virtualenv?
Basically it allows you to install Python packages into a sandboxed environment, so easy_install django doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.
For example:
$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin

Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer

Is there something like this for RubyGems?

A: RVM works closer to how virtualenv works since it lets you sandbox different ruby versions and their gems, etc.

A: Neither sandbox, RVM, nor rbenv manage the versions of your app's gem dependencies. The tool for that is bundler.

*

*use a Gemfile as your application's dependency declaration

*use bundle install to install explicit versions of these dependencies into an isolated location

*use bundle exec to run your application

A: I recommend direnv. It is an environment switcher for the shell.
Before each prompt it checks for the existence of an ".envrc" file in the current and parent directories. If the file exists (and authorized), it is loaded into a bash sub-shell and all exported variables are then captured by direnv and then made available the current shell.
Here is how to use direnv with ruby-install
+ ruby-install
Add this to the ~/.direnvrc
use_ruby() {
  local ruby_root=$HOME/.rubies/$1
  load_prefix "$ruby_root"
  layout_ruby
}

Install ruby-install (brew install ruby-install) and install a bunch of rubies.
ruby-install ruby 1.9.3
ruby-install ruby 2.0.0
ruby-install ruby 2.2.0

And then make a couple of symlinks for convenience:
ln -s .rubies/1.9 ruby-1.9.3-p*
ln -s .rubies/2.0 ruby-2.0.0
ln -s .rubies/2.2 ruby-2.2.0

And finally in any project's .envrc:
use ruby 2.0
This will put all gems under the project's .direnv/ruby directory (makes opening gems easier). bundler will put wrapper binaries in  .direnv/bin (no more bundle exec!).
+ rbenv
It's also possible to use rbenv by adding the use rbenv command in any .envrc file. This will activate rbenv which in turn will put the ruby wrappers in the PATH.
Note that it's not necessary to install rbenv in the .bashrc or .zshrc for this to work.
+ RVM
Here is the most complicated .envrc that I use on ruby projects:
rvm use 1.8.7
layout ruby
PATH_add .direnv/bundler-bin

rvm is used to select the right ruby version for you
layout commands automatically set some of the usual environment variables. For now only the ruby layout exists. What it does is set the GEM_HOME environment variable and it's bin directory to your path. Because it depends on the ruby version, make sure to call it after "rvm". Since each ruby layout directories have their own GEM_HOME, you don't need to use rvm's gemsets.
PATH_add prepends and expands the given relative path. In that case, I use this to segregate the bundler binstubs from my own bin scripts with bundle install --binstubs .direnv/bundler-bin
If you want to find out what those commands exactly do, for now: cat direnv stdlib | less

A: Here's two cents from an experienced Python developer currently learning Ruby. Using rbenv together with its rbenv-gemset plugin is the closest thing to Python Virtual Environments I have found so far.
rbenv is a tool to manage multiple Ruby versions against the same platform. If you are a Python developer you have probably stumbled upon pyenv. Well, they share the very same purpose and, as a matter of fact, pyenv was actually born as a fork of rbenv.
Without entering in to much technical details, rbenv intercepts Ruby commands using SHIM executables injected into your PATH, and determines which Ruby version has been specified by your application, and passes your commands along to the correct Ruby installation.
A Ruby version can be specified for a project in many different ways. One of the most common is to place a .ruby-version file in the project root directory containing the desired version.
However, whenever a version is used to install gems, those will be shared among all the projects using that version.
Here's where rbenv-gemset plugins comes in handy. In a similar fashion to the .ruby-version file you may initialize a .ruby-gemsets file containing the path of the directory where the gems should be installed for this project (by default a local .gems directory in the project root). Thus isolation between project is achieved.
Here's an oldie but good article about the topic.

A: I'll mention the way I do this with Bundler (which I use with RVM - RVM to manage the rubies and a default set of global gems, Bundler to handle project specific gems)
bundler install --binstubs --path vendor

Running this command in the root of a project will install the gems listed from your Gemfile, put the libs in ./vendor, and any executables in ./bin and all requires (if you use bundle console or the Bundler requires) will reference these exes and libs.

A: No one seems to have mentioned rbenv.

A: If you only need to install gems as non-root, try setting the GEM_HOME environment variable.  Then just run gem.
For example:
$ export GEM_HOME=$HOME/local/gems
$ gem install rhc

A: Mineshaft is a project that I've been working on for some time and am continuing development work on.
It offers the ability to both create virtual environments akin to how virtualenv works and can also install Ruby globally as well.


text:
Q: Proving whether $\{p(x) \in P(F) \mid p(0) + p'(0) = 0\}$ form a subspace I am trying to determine whether this subset of polynomials,
$$
\{p(x) \in P(F) \mid p(0) + p'(0) = 0\}
$$
forms a subspace. I believe that it does, but my attempt could be missing something. Here is what I've done so far. I'll call this set $U$ for convenience.
Identity. For the zero function, we have
$$
(0 + 0')(0) = 0(0) + 0'(0) = 0(0) + 0(0) = 0 + 0 = 0,
$$
so $0 \in U$.
Closed under addition. Let $f,g \in U$. Then
$$
f(0) + f'(0) = 0 \text{ and } g(0) + g'(0) = 0.
$$
It then follows that
$$
(f+g)(0) + (f+g)'(0) = f(0) + g(0) + f'(0) + g'(0) = (f(0) + f'(0)) + (g(0) + g'(0)) = 0 + 0 = 0,
$$
so $f+g \in U$.
Closed under scalar multiplication. Let $\alpha \in F$ and $f \in U$. Then
$$
(\alpha f)(0) + (\alpha f)'(0) = \alpha f(0) + \alpha f'(0) = \alpha (f(0) + f'(0)) = \alpha \cdot 0 = 0,
$$
so $\alpha f \in U$.
How does this look?


text:
Q: Knockout Nested Foreach binding taking too much time Please check this binding as when I update the main observable array then binding is taking too much time: about 12 to 15 sec to bind .
When size is less then it is not taking too much time but when size is more than 200 then it takes time to bind html .
I have reduced my json too but still not much improvement.

            Room category

            Points

            Board Basis
            Offer
            Total for   Nights
            Policy
            Book

                   <%--

--%>

 0 && $parent.IsCombineRoom">+

 0 ? 'ad-ch-div' : 'ad-ch-div' }" >

                999

                 0">

                        AED

                    = 0 ? 'line_div text-red' : 'line_div green-color ') }">

                <a data-bind="click: function () { BookNow(IsCombineRoom, IsCombineRoom ? $index() : 0, RoomTypesDispNew()[$parentContext.$index()], $parents[1].XMLHotelCode, $parents[1].OfficeID, $parents[1].ContractName) }, text: IsSelected ? 'Added' : BookingStatus.replace(' ', '') == 'OnRequest' ? 'Book On Request' : BookingStatus.replace(' ', '') == 'PackageRate' ? 'Book PackageRate' : 'Book Available', attr: { style: BookingStatus.replace(' ', '') == 'OnRequest' ? 'background:#ff5d00!important;' : '', title: RowSpan + ' Units', class: 'pull-right full-width button btn-small btn_booknow text-center back_blue_btn textcap' }">Book Available


text:
Q: How do I create a SQLite query and embed it into an SQLite Database I am struggling to find an answer on how I can create a SQL query and embed it into an actual SQLite Database by my software.
OK, I am using a program language to create an SQLite database from scratch. This all works fine and has done for a few years. The software creates the database, then tables and then imports daily data. Once finished I will open the SQLite database in Navicat and then create/save the necessary SQL Queries, then I send the database to a non-technical collegue who will run the queries and do his job.
To save me loads of time I would like my program to create and embed the SQL queryies into the database at creation.

A: SQLite is an embedded database; it is supposed to be integrated into some program that actually does something with the data.
If you want to access the database directly in Navicat, you could create a view for each of those queries.
This still requires you to execute something like
SELECT * FROM NaughtyOrNiceReport

in Navicat, but it's the best you can do.

A: Like CL. said, there is no way to embed queries into an SQLite DB you're opening outside of a program where it's integrated.
By why not just generate another file with your queries? Your buddy could run the queries from the file. As far as I see here, it shouldn't be  problem to do so in Navicat and it's probably just a text file or something similar which is easy to generate.


text:
Q: Excel automatically converting 7 digit CAS number to another number (date?) Problem: I am working with 2 list. One called HYPHEN and one called CAS Number in columns A and B respectively.
Column C uses a formula that combines column A and B and sorts them such that if a hyphen is present in column A, this is inserted before the adjacent CAS number which is then inserted below and the sequence continues so that all hyphens and CAS numbers are included. I've attached an image to better explain this and the Formula to replicate this is given below.

A CAS number is a unique Identify for a material/chemical and usually is written as 000-00-0, however occasionally you get materials with CAS numbers of 0000-00-0 (or other variations).
For the most part column C is correct because all but one CAS numbers are in the usual format. However As highlighted in red 6132-04-3 is being converted to 1545801.
What I have tried:
I have realised that 6132-04-3 is being converted to 03/04/6132 so I'm pretty sure that this is being recognised as a date which is causing the problem. I have tried to format the cells to all be a text format, I have added a comma before the CAS number but nothing returns the desired value of 6132-04-3 and instead always returns 1545801.
To replicate the issue: Column A and B can have any data entered. To replicate the output of column C the formula is given below:
Formula for Column C:
=FILTERXML(""&SUBSTITUTE(TEXTJOIN(",",TRUE,A2:B26),",","")&"","//b")
(Formula provided by @Gary's Student on Stack Overflow)
Any thoughts on how to prevent the red CAS number being converted when it is sorted in Column C would be really appreciated.

A: This is a crude way to fix it by adding then removing an arbitrary character:
=MID(FILTERXML(""&SUBSTITUTE(TEXTJOIN(",",TRUE,IF(A2:B26="","","x"&A2:B26)),",","")&"","//b"),2,99)

If you have the issue of some of your strings containing a comma, just use a different separator:
=MID(FILTERXML(""&SUBSTITUTE(TEXTJOIN("|",TRUE,IF(A2:B26="","","x"&A2:B26)),"|","")&"","//b"),2,99)

A: Looks like you could use:

Formula in D2:
=SUBSTITUTE(FILTERXML("<t><s>'"&TEXTJOIN("</s><s>'",,A2:B10)&"</s></t>","//s"),"'","")

Or:
=MID(FILTERXML("<t><s>'"&TEXTJOIN("</s><s>'",,A2:B10)&"</s></t>","//s"),2,99)

A: I can suggest you this:
Go to Format Cells ---> Number ---> Custom ---> Type
In this "Type" field write this #000-00-0
Press "OK"


text:
Q: regular expressions with escaping round brackets I am trying to write the expression that will accept the following phone numbers format:
508 736 756
505050505
+48 505 505 505
(+48) 505 505 505
++48 505 505 505
(++48) 505 505 505
(23)692 36 99
23 692 36 99

I wrote the following expression
^(([+]{0,2}?)?([+]{0,2}?)?([0-9 ]+)?)$

However, this expression only covers the formats listed below:
508 736 756
505050505
+48 505 505 505
++48 505 505 505
23 692 36 99

I have an issue with the escaping of the parenthesis characters: (). That's why I can't cover the following formats:
(+48) 505 505 505
(++48) 505 505 505
(23)692 36 99

I tried escaping them with a backslash but it wouldn't work for some reason.

...[(]?[+]{0,2}[)]?...

DEMO: https://regex101.com/r/hY5tG4/2

A: You can use following regex :
^((\(\+{0,2}[0-9]{1,2}\)|\+{0,2}[0-9]{0,2})?([0-9 ]+)?)$

Demo
Note that you omitted the numbers within parenthesis.Also about the parenthesis and the numbers between them you can not make the brackets optional because the comes together and if you make them optional the regex engine will match some phone numbers like (23692 36 99.
And note this regex will match numbers like (2) 692 36 99 if the length of numbers within brackets must be 2 you can change the renge in regex.


text:
Q: Howto upload files and limit acces to logged in users In a web application we use ckeditor to let the user generate content. We want to make it possible, that the user is able to upload files. We would like to upload this to a folder.
This folder should now only be accesible for logged in users. Is there a way to combine Cake's Auth-Component to control access to this folder?

A: You'll have to store the files in a folder not accessible from the browser outside of the webroot and send the files through php.
See this section of the book that explains how to send files using the response object. You action will use whatever auth adapter you've configured. So only people who are allowed to access that action will receive the file.
I've written a plugin that deals with files and storage systems. Take a look at it if you like. It's managing the file references in the different storage adapters (local FS, S3, dropbox, memory...). It can also resize images. It features event so that you can modify files as needed before and after they're stored.


text:
Q: Building general trees in java (with recursion) I have been stuck on a problem for quite a few days. My end goal is to perform preorder, inorder, and postorder traversals on a general tree. The problem I am having is just populating the tree. I am only able to add nodes to the root and to the root's children. I am not able to move "down" past the roots children. I woke up one morning with the idea of building the tree recursively from a bottom-up approach. I have never used recursion so first of all, is this possible? I would basically build the tree by creating the nodes at the bottom of the tree and then work my way up?
Here is my node class:
//Represents node of the Tree<T> class
public class Node<T>
{
  public T data;
  public List<Node<T>> children;

  //Default constructor
  public Node()
  {
     super();
     children = new ArrayList<Node<T>>();
  }

  public Node(T data)
  {
     this();
     setData(data);
  }

  //Return the children of Node<T>
  public List<Node<T>> getChildren()
  {
     if(this.children == null)
     {
        return new ArrayList<Node<T>>();
     }
     return this.children;
  }

  //Sets the children of a Node<T> object
  public void setChildren(List<Node<T>> children)
  {
     this.children = children;
  }

  //Returns the number of immediate children of this Node<T>
  public int getNumberOfChildren()
  {
     if(children == null)
     {
        return 0;
     }
     return children.size();
  }

  //Adds a child to the list of children for this Node<T>
  public void addChild(Node<T> child)
  {
     if(children == null)
     {
        children = new ArrayList<Node<T>>();
     }
     children.add(child);
  }

  public void addChildAt(int index, Node<T> child) throws IndexOutOfBoundsException
  {
     if(index == getNumberOfChildren())
     {
        addChild(child);
        return;
     }
     else
     {
        children.get(index);
        children.add(index, child);
     }
  }

  public boolean isLeaf()
  {
     if(getNumberOfChildren() == 0)
        return true;
     return false;
  }

  public T getData()
  {
     return this.data;
  }

  public void setData(T data)
  {
     this.data = data;
  }

  public String toString()
  {
     StringBuilder sb = new StringBuilder();
     sb.append("{").append(getData().toString()).append(",[");
     int i = 0;
     for(Node<T> e : getChildren())
     {
        if(i > 0)
        {
           sb.append(",");
        }
        sb.append(e.getData().toString());
        i++;
     }
     sb.append("]").append("}");
     return sb.toString();
  }
}

Here is my tree class:
//Tree class
public class Tree<T>
{
   private Node<T> root;

   //Default constructor
   public Tree()
   {
      super();
   }

   //Returns the root
   public Node<T> getRoot()
   {
      return this.root;
   }

   //Set the root of the tree
   public void setRoot(Node<T> root)
   {
      this.root = root;
   }

   //Returns the Tree<T> as a List of Node<T> objects
   public List<Node<T>> toList()
   {
      List<Node<T>> list = new ArrayList<Node<T>>();
      walk(root, list);
      return list;
   }

   //String representation of ttree
   public String toString()
   {
      return toList().toString();
   }

   //Preorder traversal
   private void walk(Node<T> element, List<Node<T>> list)
   {
      list.add(element);
      for(Node<T> data : element.getChildren())
      {
         walk(data, list);
      }
   }
}

This is my main driver program:
//Importing packages
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
import java.io.BufferedReader;
import java.util.List;
import java.util.ArrayList;

//Class header
public class treeTraversals
{
   //Main method
   public static void main (String[] args) throws IOException
   {
      //Defining variables
      String file;
      int size = 0;
      int id = 1;
      int counter = 1;

      Scanner keyboard = new Scanner(System.in);

      //Request file
      System.out.print("Enter the filename: ");
      file = keyboard.nextLine();

      //Read file
      File treeFile = new File(file);
      Scanner inputFile = new Scanner(treeFile);
      BufferedReader reader = new BufferedReader(new FileReader(file));

      //Find size of input file
      while(reader.readLine() != null)
      {
         size++;
      }
      reader.close();

      String[] parent = new String[size+1];
      String[] child = new String[size+1];

      //Add file vaules to arrays
      while(inputFile.hasNext())
      {
            String line = inputFile.nextLine();
            StringTokenizer st = new StringTokenizer(line);

            while(st.hasMoreTokens())
            {
               String previousValue = st.nextToken();
               String nextValue = st.nextToken();

               parent[counter] = previousValue;
               child[counter] = nextValue;

               counter++;
            }
      }
      System.out.println();

      //Output to the screen
      System.out.println("The Tree");
      System.out.println();

      for(int l = 1; l <= size; l++)
      {
         System.out.print(parent[l] + " ");
         System.out.println(child[l]);
      }

      //Create the root of the tree
      Tree tree = new Tree();
      Node root = new Node(parent[id]);
      tree.setRoot(root);

      Node active = new Node();

      //Fill tree with nodes
      for(id = 1; id <= size; id++)
      {
         Node parentNode = new Node(parent[id]);
         Node childNode = new Node(child[id]);
         active = root;
         int passage = 0;

         //Adds children to the root node
         if(parentNode.getData().equals(active.getData()))
         {
            active.addChild(childNode);

            System.out.println(tree.toList());
         }
         //Adds children to the root's children
         else if(!parentNode.getData().equals(active.getData()))
         {
            boolean marked = false;
            int i = -1;
            int n = 0;

            while(i != active.getNumberOfChildren() && marked == false && n <= 2)
            {
               active = root;
               active = (Node)active.getChildren().get(n);

               if(active.getData().equals(parentNode.getData()))
               {
                  active.addChild(childNode);
                  marked = true;
               }
               i++;
               n++;
            }

            active = root;
            if(n >= 3 && marked == false)
            {
               for(int p=0; p < active.getNumberOfChildren(); p++)
               {
                   active = (Node)active.getChildren().get(p);

                   if(active.getData().equals(parentNode.getData()))
                   {
                      active.addChild(childNode);
                      //p++;
                      marked = true;
                   }
                   else
                   {
                       active = root;
                       active = (Node)active.getChildren().get(p);
                       active = (Node)active.getChildren().get(p);
                       if(active.getData().equals(parentNode))
                       {
                           active.addChild(childNode);
                           System.out.println("No");
                           p = 0;
                       }
                    }
                 }
              }
           }
           //See the nodes in the tree
           System.out.println(tree.toList());
        }
     }
  }

Lastly, here is the text file that is provided:
a  b
a  c
a  d
b  e
b  f
d  g
d  h
d  i
e  j
e  k
g  l
g  m
k  n
k  o
k  p

Please, any help would be appreciated, I'm stuck on my own approach so I'm asking: how would I even start if I'm going with a recursive approach?

A: I have neglected the order for now, and just given an Tree.insert(parentData, data).
With the hope that this helps getting you started.
public class Node<T> {
    private T data;
    private List<Node<T>> children;

    Node<T> find(T data) {
        if (this.data.equals(data)) {
            return this;
        }
        for (Node<T> node : children) {
            Node<T> found = node.find(data);
            if (found != null) {
                return found;
            }
        }
        return null; // Not found.
    }

public class Tree<T> {

    public find(T data) {
        return root == null ? null : root.find(data);
    }

    public boolean insert(T parentData, T data) {
        Node<T> found = find(parentData);
        if (found == null) {
            return false;
        }
        found.getChildren().add(new Node(data));
        return true;
    }

As one sees, having a find(data) method for retrieving the (parent) Node helps.
The search method find here disregards any sorting of the values, and does a preorder search.
As far as order is concerned, normally on has nodes of the form:
class Node<T> {
    List<Node<T>> children; // 0, 1, ... N
    List<T> values; // 0, 1, ... N-1
}

With an sort ordering:
children[0]
values[0}
children[1}
values[0]
children[2]
...
children[N-1]
values[N-1]
children[N]

One might retain the values in the entire tree in this order.
Sorting and preorder/postorder walks and bread fírst/depth first walks are different notions.


text:
Q: Convert Canadian Postal Code to Longitude and Latitude I have a list of 100 Canadian postal codes (e.g. M4B 1C7). Is there anyway to convert these postal codes into approximate longitude and latitude values? Currently, I am using the following website to do this manually: https://geocoder.ca/
Is there a quicker way to do this in R? I came across the tidygeocoder package , but I am not sure if this will work for Canadian postal codes.

A: As noted by @Dave2e above, the data are available for download here, although you have to register and agree to the terms of use (basically, you can't redistribute the data or break any other laws: I've quoted them below for convenience). It seems weird that the postal code data isn't more conveniently available, but apparently its intellectual property status is contentious - Canada Post sells access to the database.
This solution may not be robust into the future: I have used other sources for this data before, which have then disappeared from the web. The files were available as of 18 April 2021.
Once you've downloaded and unzipped the CSV files, it's pretty straightforward.
library(tidyverse)
cc <- (read_csv("CanadianPostalCodes202104.csv")
 ## if all you want is lat/long: file also includes city, province abbreviation,
 ## time zone - maybe useful for troubleshooting/proofreading
   %>% select(POSTAL_CODE, LATITUDE, LONGITUDE)
   %>% rename(postcode="POSTAL_CODE", lat="LATITUDE", lon="LONGITUDE")
)
mydata <- tibble(postcode=c("M4B 1C7","L8P 2V7"))
mydata_aug <- left_join(mydata, cc, by="postcode")
##   postcode   lat   lon
## 1 M4B 1C7   43.7 -79.3
## 2 L8P 2V7   43.2 -79.9

A picture of the locations (this would be prettier if I bothered to put this into a proper spatial context with province boundaries etc.): I'm not sure what's up with the dozen or so locations that are apparently south of the Canada-US border. For example, this database apparently thinks that Stouffville ON is at 44.8°N 93.3°W, which according to Google maps is smack in the middle of West Bloomington, Minnesota USA: it's actually at 43°58′N 79°15′W according to Wikipedia ...

Terms of use (in part):

You may not (nor allow any third party) to, resell, incorporate Zip File into in any product or services, copy, distribute, sell, disclose, lend, transfer, convey, modify, decompile, disassemble or reverse engineer Zip File for any purpose whatsoever.

You shall not under any circumstances: (i) use information from Zip File to build a database for resale or for access by a third party in direct competition with Service Objects; (ii) allow information from Zip File to be used in any way to verify information from a third party that resells data in direct competition with Service Objects; or (iii) provide access to or information from Zip File to a third party that resells data in direct competition with Service Objects or to a third party that plans to resell to a further third party access to Zip File or information obtained from Zip File.

You agree to comply strictly with all applicable laws and regulations in connection with your use of Zip File.

A: https://pypi.org/project/pgeocode/ is extremely fast if you use the bulk submission method. The problem with pgeocode is that it really only resolves to the Forward Sortation Area (i.e. first 3 characters) not the full postal code.
The pgeocode application uses files from GeoNames.org and I see that there is a complete file (i.e. full postal code) for Canada, but I have yet to figure out how to use it.  If anybody knows please let me know.


text:
Q: How to trigger list of jenkins jobs sequentially in a loop I am new to Groovy DSL, I am getting a list of successful jenkins job names from a script which satisfies my condition which will vary on each execution, EX1: JOB_A,JOB_B.. EX2: JOB_C,JOB_Y...I need to trigger these result list of jobs at the time of execution of the script sequentially in a for loop from Script console using Groovy script. How can i achieve this?

A: If you are in a pipeline you can use
jobList.each{ jobName ->
    build: jobName
}


text:
Q: Best practice: Monitor processes I was wondering what the best practice solution would be to constantly monitor and resart processes, because there are multiple ways in doing it.
Additional info:
I have a unix program which uses multiple processes to work. There's a main process, it always starts first and is not likely to die or terminate without stopping the program.
Then I spawn multiple "module" processes, which take care of some work and communicate through the main process. Those modules sometimes die because of exceptions, and because it's an external program I can't resolve the issues, so I have to restart them if they die.
I've made a program to check if any of the modules died and restart them, but I need to run it manually. My program checks if the pid files of the modules exist and if they listen on a specific tcp port. If the pid file doesn't exist or the socket can't establish connection, it restarts the module.
My thoughts so far:

*

*Cron job to run the checks every minute and restart any dead modules. (kind of an overkill, because they don't die that frequently)

*Daemon running in the background, which starts the modules and receives notifications if they die, so it doesn't have to check them constantly. (SIGCHLD signal, os.wait)

If I use the daemon method, how should I communicate with the daemon through my interface? (socket, or maybe a file which gets read if the daemon receives a specific signal)
Usually I would just go with the daemon because it seems to be the best practice method to restart the modules asap(cron only runs once a minute), but I've wanted to get some opinions from more experienced users. (I've never done something like this before, and asking doesn't hurt anyone :D)
I apologize if these questions are answered somewhere else, but I couldn't find any related question.
P.S. If I forgot something or you need more infos, please feel free to ask. :)

A: I would investigate running the monitoring process as part of a dedicated monitoring framework.   Monit is one example, however there are of course others.
This has the advantage of providing additional features which might be useful, such as email alerts and analytics.  In my experience, you should be able to use your existing program without too much modification, and Monit itself uses few system resources if that is a concern.


text:
Q: The conversion of the varchar value '5566778891' overflowed an int column I am using SQL Server database and there's a column named Cell(VARCHAR) data type. While reading using reader.Read() I get the Conversion error. Can anyone kindly explain the reason for the error?
This is my code:
string myConnection = dbController.connectionString;
        string query1 = "SELECT ID, Name from Manager Where Cell = " + managerNo.Text;
        using (var conn = new SqlConnection(myConnection))
        using (var cmd = new SqlCommand(query1, conn))
        {
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                managerID = reader.GetString(0);
                mgrID.Text = managerID;
                managerNames.Text = reader.GetString(1);
            }
            conn.Close();
        }

I am reading the value from a textbox (managerNo). I have tested the query on SQL Server Management Studio as well:
select Name, DOB
from Contact
where Cell = 1233453411

When I use Cell = 1233453411 without the value as string I get the conversion error, however using Cell = '1233453411' as a string the result is fetched.
Whats the reason for this and how to solve this issue.
Thanks.

A: This is a comparison between two different types, a string and an integer:
where Cell = 1233453411

SQL Server has to decide which type to use.  It decides on the more restrictive type, which is the number.  So, the string gets converted to a number.
Say, you have a cell phone in New York with a number like: 917-555-5555.  Well, that becomes a number like 9,175,555,555 and this exceeds the value of the maximum integer.  Hence, you would get a conversion overflow.
The moral:  Always use similar types when making comparisons.
EDIT:
What should you do?  Don't store telephone numbers as numbers; they should be stored as strings (for instance, leading zeroes can be important).
If could do a quick-and-dirty and put single quotes around the value of the parameter.  But, what you should really do is change your SQL code to use a parameter with a string type.  It is bad programming to just stuff values (particularly user input) into a query string.

A: Your code is working fine in SQL Server 2008 R2. (Below is tested code)
private void button1_Click(object sender, EventArgs e)
        {
        string str = "Server=.\\SQL2008R2;Database=Practice;User ID=sa;Password=123;Trusted_Connection=True;Connection Timeout=0";

        string query1 = "SELECT * from tblTest Where Cell = " + textBox1.Text;
        using (var conn = new SqlConnection(str))
        using (var cmd = new SqlCommand(query1, conn))
        {
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {

                string aa = reader.GetString(0);
            }
            conn.Close();
        }

Otherwise using can change you query like in below format.
string query1 = "SELECT * from tblTest Where Cell = '" + textBox1.Text + "' ";

Thanks


text:
Q: Why is !found instead of found necessary in the while loop condition of this linear search of an array? I'm just starting with Java and have a pretty silly question about a linear search of array.
Why is it necessary to put !found and not just found in the while loop condition? I'm a bit confused because in my thinking, the while loop should run when we have not found the target and the index is smaller than the array length, so it should be while((found)&&(index<myArray.length)) instead?
public class LinearSearch {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int target = 2;
        boolean found = false;
        int index = 0;
        int indexOfTarget = -1;
        int [] myArray = {18,38,2,20,24,14,5};
        while ((!found)&&(index<myArray.length)) {
            if (myArray[index]==target) {
                indexOfTarget=index;
                found = true;
            }
            index++;
        }
        if(found) System.out.println("Found element at position "+indexOfTarget);
        else System.out.println("Target not found");
    }

}

A: Your code also works, as long as you make sure you break out of the loop when the index reaches the array's limit.
There are many ways to understand this.
//using !found, you need to break
while (!found) {
   if (myArray[index]==target) {
       indexOfTarget=index;
       found = true;
       break;//also break when you find a match
   }
   index++;
   if (index == myArray.length) break;
}
``


text:
Q: Angular Tour of Heroes HttpClient CRUD methods I am currently learning angular with the Tour of heroes tutorial.
In the HTTP chapter, I dont understand how the corresponding heroes are called from the server, as it appears, there is only a url passed to the simulated server, for any of the HttpClient.get (or other CRUD) methods...
private heroesUrl = 'api/heroes'

and the corresponding get method for all Heroes (~array):
getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
}

if return only one single Hero:
/** GET hero by id. Will 404 if id not found */

    getHero(id: number): Observable<Hero> {
      const url = `${this.heroesUrl}/${id}`;
      return this.http.get<Hero>(url).pipe(
        tap(_ => this.log(`fetched hero id=${id}`)),
        catchError(this.handleError<Hero>(`getHero id=${id}`))
      );

what will be returned from this url? I mean it is just a url, how is the database api connection reacting in the background in response to the url (or the id passed)?
same goes for other post methods:
addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(..)
}

it has a url parameter, but how gets the actual hero passed to the server? and where is the hero id created?

A:
what will be returned from this url?

When you perform an HttpClient.get, the result is always an observable. So you will receive an observable.

I mean it is just a url, how is
  the database api connection reacting in the background in response to
  the url (or the id passed)?

As you can see in the app.module.ts :
 // The HttpClientInMemoryWebApiModule module intercepts HTTP requests
    // and returns simulated server responses.
    // Remove it when a real server is ready to receive requests.
    HttpClientInMemoryWebApiModule.forRoot(
      InMemoryDataService, { dataEncapsulation: false }
    )

it has a url parameter, but how gets the actual hero passed to the
  server? and where is the hero id created?

You can find more informations on 'how it works' here : https://github.com/angular/in-memory-web-api


text:
Q: WCF MessageSecurityException: The security timestamp is invalid because its creation time I have an app that connects to our WCF service to send data.
It uses custom user validation to authenticate the user.
Currently, if the client time is significantly different to our server's (the default 5 mins), then this error will fault the connection.
I'm trying to catch this specific error so that on the server side, I can notify someone when it occurs and for the user/client that it occurred for.
I want to do this because allowing a larger clock skew won't solve our problem, there can be huge variation on the client's machine times. We don't control the client machines, however we can get them to update their time.
I have tried to put a generic try/catch in the validate method, and that does capture other exceptions (like if the authentication fails - I throw a FaultException) , it doesn't seem to catch the clock skew issue. I'm guessing this isn't the correct place to catch this, but I'm at a loss as to where else it should go.
I would implement passing the client time as part of the login (as I have seen suggested elsewhere), however I'm not able to do this at this time and really need a way to identify clients with incorrect date/times in the meantime.
If it helps, the service is using: basicHttpBinding and its security mode is: TransportWithMessageCredential


text:
Q: How to secure access to AWS Elasticsearch from a mobile application I'm building a mobile app that requires access to an AWS Elasticsearch  (ES) cluster and would like to make sure only the app can make queries.
Assuming I'm not going to distribute AWS user credentials with my mobile application, what would be a secure way to allow read access to an AWS Elasticsearch cluster?
Reading this AWS post I gathered that I can setup a reverse proxy to sign my requests to Elasticsearch. If I follow this route, how would I secure access to the EC2 instance port where the proxy is listening to?

A: For mobile applications what you want to set up is Web Identity Federation.  This is will give users temporary credentials to access aws resources needed for your mobile application.
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html
Setting up
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html
Article from Amazon on Web Identity Federation with Mobile Applications
https://aws.amazon.com/articles/4617974389850313


text:
Q: Unable to select element in Selenium WebDriver from list box I am new to Selenium Web Driver and unable to select element in the list box and getting below error:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"ext-element-13"}

WebElement item = launch.driver.findElement(By.id("ext-element-13"));
Select page_dropdown = new Select(item);

for(int i=0; i<page_dropdown.getOptions().size(); i++)
{
    page_dropdown.selectByIndex(i);
    System.out.println("Page drop down having values " + page_dropdown.getFirstSelectedOption().getText());
}

ABC Program : Summary

ABC-001: Poor Control

ABC-002: Low Density

A: As per provided HTML code, i am expecting it is not Select drop down. so select command may not work here..
secondly if i am correct

is location of your drop down and below one is one of option correct?

ABC Program : Summary

here you may need to use sendkeys
driver.findElement(By.xpath("//*[@role='listbox']")).sendKeys("ABC Program : Summary");

you can also use xpath=//*[@data-ref='listEl'] in above code if there are more listbox elements in page
if above one does not work, just try by directly clicking on required option
driver.findElement(By.xpath("//*[contains(text(),'ABC Program : Summary')]")).click();

if even above one does not work, then you need to click on ul and then required option.
there may be change in locators, if they are not working let me know, will try for another xpath


text:
Q: Как закрыть родительское окно при открытии дочернего? CustomTkinter Не могу закрыть окно авторизации, которое вызывает рабочую форму. Открывшееся окно работает, все кнопки нажимаются. Окно авторизации становится просто неактивным, не работают кнопки и его нельзя закрыть даже на крестик.
Второе окно делаю в отдельном файле, а все функции и интерфейс приложения описаны в классах. Может быть в этом дело?
class Auth(ctk.CTk):
def __init__(self):
    super().__init__()
    #настройки окна
    self.geometry("350x300")
    self.title("JustLan Admin")
    self.resizable(False, False)
    self.my_font = ctk.CTkFont(family="Times New Roman", size=24)

    #плашка
    self.back_frame = ctk.CTkFrame(master=self)
    self.back_frame.pack(pady=25, padx=20, fill="both", expand=True)

    #элементы на плашке
    self.auth_button = ctk.CTkButton(master=self.back_frame, text="Войти", font=("Times New Roman", 20), width=160, height=38, command=self.login)
    self.auth_button.pack(pady=3)

#команды
def login(self):
    if (self.login_entr.get() == "root" and self.pass_entr.get() == "root"):
        self.error_label.configure(text="")
        os.system('python workspace.py')
        self.destroy()
    else:
        self.error_label.configure(text="Неверный логин или пароль")

if __name__ == "__main__":
    app = Auth()
    app.mainloop()

Пробовал разное
self.destroy()
sys.exit(0)
self.master.destroy()

С использованием
self.withdraw()
os.system('python workspace.py')

все получалось как я хотел (первое окно закрылось, второе открылось), но возникала ошибка призакрытии рабочей области, точнее приложение закрывалось, но требовало остановки в pycharm
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.9/tkinter/init.py", line 1889, in call
try:
KeyboardInterrupt

A: Для закрытия первого окна авторизации одновременно с закрытием рабочей области я использовал
 self.withdraw()
 os.system('python workspace.py')
 sys.exit(0)

Мое приложение состоит только из 2 окон, поэтому я не проверял как это будет работать с 3+ окнами.