text:
Q: Getting Molecular Weight for Stoichiometry Calculations I love the units system in Mathematica, it's an extremely useful addition to the language. Unfortunately there are still some sharp corners that I run into on a daily basis. For example, if I want to do a stoichiometry calculation, I would like to be able to do the following:
Vol = Quantity[300,"Microliters"]
Concentration = Quantity[2,"Millimolar"]
CdMW = ChemicalData["CadmiumOxide","MolecularWeight"]
mgCd = UnitConvert[Concentration*Vol*CdMW,"Milligrams"]

But this does not work, because "MolecularWeight" reports units of AtomicMassUnit, which Mathematica indicates is incompatible with "Grams"/"Moles", even though in practice (at least for stoichiometry calculations) they are effectively the same.
I have a workaround using the following code:
CdMW = Quantity[QuantityMagnitude[ChemicalData["CadmiumOxide","MolecularWeight]],"Grams"/"Moles"]

But I find this to be quite inelegant, and somewhat less than readable.
Is this the best way to do this, or is there a better approach?

A: The "MolarMass" property has the same magnitude but the right unit dimensions for this application:
CdMW = ChemicalData["CadmiumOxide", "MolarMass"]
(* Quantity[128.413, ("Grams")/("Moles")] *)
mgCd = UnitConvert[Concentration*Vol*CdMW, "Milligrams"]
(* Quantity[0.077048, "Milligrams"] *)

As an aside, you can use WolframAlpha in your notebook for some inputs like this.  Here the input string "convert 300 microliters 2mM cadmium oxide to milligrams" works:


text:
Q: New to linux and trying to update from 21.10 to 22.04.1 I downloaded ubuntu 21.10 a while back and made it my main OS but since have rarely used my PC
I am a novice with Ubuntu and encountering difficulties when trying to update.
This error appears when I run sudo apt-get update
Error:9 http://ppa.launchpad.net/flatpak/stable/ubuntu impish Release
  404  Not Found [IP: 185.125.190.52 80]
Ign:10 http://archive.ubuntu.com/ubuntu impish-backports InRelease
Err:11 http://archive.ubuntu.com/ubuntu impish Release
  404  Not Found [IP: 91.189.91.39 80]
Err:12 http://archive.ubuntu.com/ubuntu impish-security Release
  404  Not Found [IP: 91.189.91.39 80]
Err:13 http://archive.ubuntu.com/ubuntu impish-updates Release
  404  Not Found [IP: 91.189.91.39 80]
Err:14 http://archive.ubuntu.com/ubuntu impish-backports Release
  404  Not Found [IP: 91.189.91.39 80]
Reading package lists... Done
E: The repository 'http://security.ubuntu.com/ubuntu impish-security Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://ppa.launchpad.net/flatpak/stable/ubuntu impish Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://archive.ubuntu.com/ubuntu impish Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://archive.ubuntu.com/ubuntu impish-security Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://archive.ubuntu.com/ubuntu impish-updates Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://archive.ubuntu.com/ubuntu impish-backports Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como faço para chamar o campo email da tabela default auth_user?? precisava para fazer o usuarios se registrar com email, usuário e senha meu register.html esta assim
<!DOCTYPE html>

    <meta charset="UTF-8">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

    <title>Sistema de cadastramento de Bens</title>

Cidadãos cadastradoos

        Voltar

Entrar no Sistema de Bens

<form method="post">
    {% csrf_token %}

        {{form.username.errors}}
        Username:

        {{form.username}}

        {{form.password1.errors}}
        Senha:

        {{form.password1}}

        {{form.password2.errors}}
        Confirmação de senha:

        {{form.password2}}

        <input type="submit" value="Cadastrar" class="btn btn-primary">

</form>

tentei colocar o email nesse padrão mais nãp foi. Alguém poderia me ajudar??
minha models.py
from django.db import models
from django.contrib.auth.models import User
class Cidadao(models.Model):
    nomebens = models.CharField(max_length=100)
    nomecompleto = models.CharField(max_length=150)
    numSerie = models.CharField(max_length=100)
    endereco = models.CharField(max_length=250)
    email = models.EmailField()
    observacao = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.user

A: Usando function based views.
Criando Formulario:
app usuario, gerenciador de usuario
  #app usuario
from django import forms
from django.contrib.auth.models import User # utilizando autentificacao

class NovosuarioForm(forms.Form):
usuario = forms.CharField(required=True) #campos que seram requisitados
email = forms.EmailField(required=False)
senha = forms.CharField(required=True)

def is_valid(self): # verif se o formulario é valido

    formularioValido = True # inicia como true...

    if not super(NovosuarioForm, self).is_valid():
        print("preencha todos os campo") # caso for preenchido apenas o nome sem senha retornara invalido
        formularioValido = False

    #query que ira verificar se ja existe o usuario com mesmo nome
    novo_usuario = User.objects.filter(username=self.data['usuario']).exists()

    if novo_usuario: # apresenta uma mensagem  avisando que usuario existe
        print("usuario ja cadastrado")
        formularioValido = False # ou pode excluir, e evitando duplicata no model

    return formularioValido

Como ira usar o User, não precisa do model, pois ira reutilizar os campos da tabela do django.
view do usuario
    # app usuario VIEW...
from django.shortcuts import redirect
from django.shortcuts import render
from django.contrib.auth.models import User
from django.views.generic.base import View
from perfis.models import Perfil # aplicação do usuario
from usuarios.forms import NovosuarioForm # gerenciador de usuario

#Duas aplicacões, A do usuario e um gerenciador de novos cadastros
#então um startap usuarios, que vai gerenciar
# outro startap que sera o perfil cadastrados

class RegistrarView(View):

def get(self, request): #get retorna a formulario
    return render(request, "criarLogin.html")

def post(self, request):# add dados
    form = NovosuarioForm(request.POST) # do app usuario

    if form.is_valid(): # verif se é valido
        dados_form = form.data
        #variavel usuario puxa de User que cria usuario usando o form especificado
        usuario = User.objects.create_user(dados_form['nome'],
                                           dados_form['email'], dados_form['senha'])
        # do model pefil, salvara o nome
        perfil = Perfil(nome=dados_form['nome'],
                        usuario=usuario)

        perfil.save() #feito ,agora salva

        return redirect('ja_foi_adicionado.html')

    return render(request, "algumtemplate.html", {'form': form})

MODEL perfil:
from django.db import models
from django.contrib.auth.models import User

class Perfil(models.Model):
    nome = models.CharField(max_length=255, null=False)
    usuario = models.OneToOneField(User, related_name="perfil", on_delete='NOTHING')

O template de registrar novo usuario e login ficam dentro do app "usuario"
<form method="post">

    {% csrf_token %}

    <input type="text"name="nome">
    <input type="text"  name="email">
    <input type="password" name="senha" >

    <button type="submit" value="Login">

</form>

URLS DO USUARIO
from django.urls import path
from usuarios.views import RegistrarView
from django.contrib.auth import views

urlpatterns = [
    path('cadastrar/', RegistrarView.as_view()),
    # e os path de login e logout
]

Urlpatterns
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('perfil.urls')),
    path('', include('usuarios.urls'))
]

O setting:
LOGIN_URL = '/login/'
LOGOUT_URL = '/logout/'
LOGIN_REDIRECT_URL = '/'

INSTALLED_APPS = [
    'perfil',
    'usuarios'
]

view perfil
from perfis.models import Perfil,
from django.contrib.auth.decorators import login_required

    @login_required
    def get_logado(request):
        return request.user.perfil

caso queira outra referencia:
simpleisbetterthancomplex.com


text:
Q: Invalid svg to png conversion via rsvg in mediawiki While uploading this file  to my wiki instance, application uses librsvg to convert it into png thumbnails. But the result is like this Link
This dragon seems to be generated in Inkscape, so i tried to use inkscape as a converter. It worked for this image (but not for some others), but it has X dependencies, so I cannot use it.
Here I found, that wikimedia projects use rsvg for such conversions.
Can anyone help me with this strange behavior?
Mediawiki settings for svg support:
# Svg support
$wgFileExtensions[] = 'svg';
$wgAllowTitlesInSVG = true;
$wgSVGConverter = 'rsvg';

Environment:
CentOS release 5.6 (Final)
rsvg version 2.16.1

A: rsvg has a number of issues, please file a bug and mark it as blocker of https://bugzilla.wikimedia.org/show_bug.cgi?id=8901 . It might already be in the list of known bugs, check.

A: The answer is damn simple — librsvg library was too old. 2.22.3+ solves this issue.


text:
Q: Crystal Reports - Trying to reset page numbers based on database field instead of group The issue that I am having is that I need to update page numbers based on data in the page header.  What I am trying to do is create a packing slip.  All the customer and order information is in the page header.  I need to reset the pages if there is more than one page for an order.  Right now, I am getting the number of N of M pages, but M is the total number of pages for all orders (example 1 of 18 pages, because there are 17 orders and one order is two pages long).  I want it to be 1 of 1 of there is only one order for the packing slips, but 1 of 2 if there is more than one page.  Does this make sense?  Any ideas? Thanks

A: Try this:

*

*Right Click the page footer in the left margin

*Click SECTION EXPERT

*Click the FORMULA BUTTON to the right of RESET PAGE NUMBER AFTER PageNumber = 2

A: Assuming you are grouping by order number and starting a new page for each new order - by having checked the New Page After option in the Section Expert for the group footer - then you can check the option to Reset Page Number After in the Section Expert for the group footer.


text:
Q: Centos 6.6 postgresql error: cannot execute binary file I am running this on centos 6.6
PSQL='/usr/bin/psql'

su - postgres "$PSQL" template1 -f 'sql.sql'

But starting psql always fails to start
Starting postgresql-9.4 service:             [FAILED]

and then I get this error
/usr/bin/psql: /usr/bin/psql: cannot execute binary file

Thank you for all the help.

A: Try this:
PSQL='/usr/bin/psql'
su - postgres -c "$PSQL template1 -f 'sql.sql'"


text:
Q: Publishing images without their source I have more than a million images those I will like to use as training data. How do I make this data available freely without compromising security?
I want the users to be able to use it quickly for training purpose, without giving hackers a chance to rebuild images from the open source data. At the same time I do not want that the training quality will be affected in any way.
In other words how do I safely open-source images?

For e.g. This code generates numpy array. I just want to make it very difficult to reconstruct the original image from the ndarray "x" in this case.
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
i = load_img('some_image.jpg' )
x = img_to_array(i)
x = x.reshape((1,) + x.shape)

I can share the array x once I know that the hackers can not use the data and create the same image.

A: If you aim to publish open-source pictures, a good start would be to understand how WikiCommons works. They had and must face many challenges of this kind, there is a lot of things to learn from there.
If your audience needs the complete picture to be served to make their models work, then no matter how you try to obfuscate the array containing the data. Smart guys that have enough time and creativity will be able to reconstruct the original picture. This is not a viable solution, it only provides a false secure feeling.
If you choose a destructive approach, not to serve the actual picture, but some digest/hash/fingerprint of it, then you will probably reduce the risk of reconstructing the original picture (beware there are very clever guys with strong cryptographic skills). But then your audience will not be able to learn from the picture itself so you may not achieve your goal.
Less destructive and may not fit your requirement: adding noise. It will not prevent disclosure of sensitive material (human eyes and brain are somehow good to classification) and it is a well know technique for AI confusion. Not a good solution too.
In anyway, if you serve without care sensitive material that does not fit open source, then you may get yourself and other people in trouble. This is not a good option.
My advice,

*

*If your pictures really suit to open source policy, then serve them as this and do not worry about hackers, they are customers as well;

*If your picture are sensitive, then do not serve them as open source. Instead provide a framework with a layer of security and implement required regulations you must take into account (ToS, IP, Copyright, GDPR).

A: All machine learning algorithms take the real images and convert the images to tensors, and process them in batches (multiple images at a time).
Couple of options for you:

*

*You can share your images with your teammates and relay on trust.

*You can somehow obfuscate the images as bunch of files, or you can create the algorithm to convert them to numpy array (or tensor), obfuscate them, and provide the procedure to revert them back without losses.

But in all these cases, non wanted people can somehow guess your procedure/obfuscation.
Ideal would be to create the Machine Learning model (like VGG, ResNet, Inception) from your images, and then you can distribute your model that learned what you planed from your images.
Bottom line, in ML you need images to learn something from them, and not the images per se.
Privacy is really a problem as we can see from this document dealing with how copyright is causing a decay in public datasets.
There are no many solutions to this problem, because privacy really matters. However, this idea with GANs may be encouraging.
If you don't use GANs, it is hard to tell what would be the right set of transforms you would need to undertake to escape the privacy policy concerns.
Just if you try to flip images, scale them, remove the metadata, normalize them, or transform one pixel is not enough. You would need make them indistinguishable from the originals.


text:
Q: How to disable checkBox if other checkBox is checked c# I have an array of checkBox in my windows form application. I am wondering is there a way to disable that array of checkBox if one or more checkBox in that array is checked?
for example:
if A is checked, B,C,D,E is disabled
if A, and C is checked, B, D, E is disabled
Sorry for the confusion. In the following example, A, C, E is checked. What I want is B, D then is disable
[x]A []B [x]C []D [x]E

This is my array list
Another example:
This example showed D is checked, then A, B, C and E should be disabled
[]A []B []C [x]D []E

Code:
CheckBox[] myCheckBoxArray = new CheckBox[5];

myCheckBoxArray[0] = checkBoxA
myCheckBoxArray[1] = checkBoxB
myCheckBoxArray[2] = checkBoxC
myCheckBoxArray[3] = checkBoxD
myCheckBoxArray[4] = checkBoxE

A: I think what you are after is a simple 'if' statement:
if (checkBoxA.Checked == true)
{
    checkBoxB.Checked = false;
    ....
}

And so on and so forth. You can also check multiple boxes at the same time, using the '&&' operator, like so:
if (checkBoxA.Checked == true && checkBoxB.Checked == false)
{ do.something(); }

To apply this to your array, simply append the following:
if (checkBoxA.Checked == true)
{
    myCheckBoxArray[i].Checked = false;
}

You can't group sections of an array in the manner that you're asking - you might be able to call certain array members if they met a certain condition, however you do not necessarily know their condition before you change their 'Checked' status. In this context, you must either change the entire array, or each checkbox one-by-one. Alternatively, create your array in your if statement. This is an expensive process, however, and largely pointless.

A: I have fixed my question
 CheckBox[] checkBox1 = new CheckBox[5];
            checkBox1 [0] = checkBoxA;
            checkBox1 [1] = checkBoxB;
            checkBox1 [2] = checkBoxC;
            checkBox1 [3] = checkBoxD;
            checkBox1 [4] = checkBoxE;

            foreach(CheckBox items in checkBox1 )
            {
                if (!items.Checked)
                {
                    items.Enabled = false;
                }
            }


text:
Q: WKWebView is not loading perticular url in swift Unable to load "https://dev-react.ndh01.com" this url only in WKWebView in swift. But it is loading in browser and Android Webview

A: you are not doing anything wrong and technically your webpage is loading properly, but this website is not optimized for all screen sizes, you can verify this by rotating your test device whether you using a simulator or physical device
import UIKit
import WebKit

class WebViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    preferences.javaScriptCanOpenWindowsAutomatically = true
    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences
    let webview = WKWebView(frame: .zero, configuration: configuration)
    view.addSubview(webview)
    webview.load(URLRequest(url: URL(string: "https://dev-react.ndh01.com")!))

    webview.translatesAutoresizingMaskIntoConstraints = false

    webview.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    webview.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    webview.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    webview.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

}

}

if you are using a simulator try pressing Cmd + right/left arrow to rotate the device to landscape
you will find a screen showing your web page


text:
Q: Using HXT to modify XML I'm trying to modify an XML file of the form:
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>https://s3.xyz.amazonaws.com/xyz/xyz.ipa</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>display-image</string>
                    <key>url</key>
                    <string>https://s3.xyz.amazonaws.com/xyz/xyz.57x57.png</string>
                </dict>
            </array>
        </dict>
    </array>
</dict>

I want to modify the contents of the node <string>https://s3.xyz.amazonaws.com/xyz/xyz.ipa</string>
I can find the related sibling node with the following
import Text.XML.HXT.Core

main = do
  plistString <- readFile "manifest.plist"
  let plistDoc = readString [withValidate no, withSubstDTDEntities no] plistString
  node <- runX  $ plistDoc >>> deep (hasText ( == "software-package"))
  print node

but I don't seem to be able to select the associated sibling nodes (tried followingSiblingAxis and moveUp >>> getChildren) which would then allow me to manipulate the required node. Is it a problem to do with the difference between NavigatableTree and NTree; the node I'm shows as NTree (XText "software-package") []]
It would really help me if any answers assume a very limited exposure to arrows.
Thanks.

A: I've solved the problem in a different way. It doesn't feel as robust (matching a substring for xyz.ipa), but it unblocked me while I await inspiration:
import Text.XML.HXT.Core
import Data.Char (toUpper)

uppercase = map toUpper

main = do
  plistString <- readFile "manifest.plist"
  let plistDoc = readString [withValidate no, withSubstDTDEntities no] plistString
  node <- runX . xshow $ plistDoc >>> processTopDown (ifA (hasText ( isInfixOf "xyz.ipa")) (changeText uppercase) (this))
  print node


text:
Q: ORDER on mdx query is not working I'm having a problem to order a column with a MDX query.
this is my query:
with
     Member
     [Measures].[MemberUN] as '[Employee].[Employee Department].CurrentMember.UNIQUE_NAME'
     member
     [Measures].[Memberlevel] as '[Employee].[Employee Department].CurrentMember.LEVEL.ordinal'
Select
ORDER([Employee].[Employee Department].allmembers,[Measures].[Memberlevel]) on 1,
{[Measures].[MemberUN],[measures].[MemberLevel]} on 0
From [Adventure Works]

For some reason it's not ordering the table with the level ordinal.
Thank!

A: The default setting for sorting of MDX does not break the level hierarchy, i. e. it keeps the main order of first the parent, then its children. It only applies the sorting to the children of the same parent. If you want to break the hierarchy in your sorting, use BASC ("breaking sort ascending") instead of the default setting ASC, or use BDESC instead of DESC. The following query sorts in the way that you probably intended:
with
     Member
     [Measures].[MemberUN] as '[Employee].[Employee Department].CurrentMember.UNIQUE_NAME'
     member
     [Measures].[Memberlevel] as '[Employee].[Employee Department].CurrentMember.LEVEL.ordinal'
Select
ORDER([Employee].[Employee Department].allmembers, [Measures].[Memberlevel], BASC) on 1,
{[Measures].[MemberUN],[measures].[MemberLevel]} on 0
From [Adventure Works]


text:
Q: How to view Xcode arm64 compiler output as assembly language? Is there any way to view Xcode's arm64 compiler output in the form of assembly language, either using Xcode, the command-line developer tools that come bundled with Xcode, other developer tools from Apple, or some 3rd party utility?

A: (Since no one else answered, I'll post what I ended up with...)
Using the command-line tools that came with the released (Mac App store) Xcode installation:
clang -arch arm64 -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include -S my_source_file.c

produced an .s file containing arm64 assembly language.


text:
Q: How to setup IdentityServer4 to be an external identity provider There is a lot of information and documentation available regarding how to add external identity providers such as Google, Facebook, Microsoft, etc.
Does IdentityServer4 support being the external identity provider for another for another OpenID Connect server (perhaps another IdentityServer4 instance)?
If so, how do you set this up? If my IdentityServer4 instance (Instance A) is acting as the external provider for another IdentityServer4 instance (Instance B), what kind of client do I need to setup on Instance A for Instance B?
Any documentation or samples on the subject would be extremely helpful.

A: Yes, you can achieve this with IdentityServer. In this case it would work 'like' any other 3rd party identity provider (Facebook, Google, etc.)
So for example -- in this case you should configure your app with an authentication that your own identity provider exposes, instead of 'Google' -- refer to this documentation page:
http://docs.identityserver.io/en/latest/topics/signin_external_providers.html?highlight=external%20identity%20provider
You may run into issues (at least this was the case in 2017) -- see this older question
IdentityServer used as external identity provider for another IdentityServer fails to properly redirect
Hopefully this puts you to the right track. Happy hacking!


text:
Q: How to read a .data file encoded using NSKeyedArchiever iPhone I use NSKeyedArchiver to archive data in my iPhone app into a .data. Long story, short, I lost all my data. I use "iPhone back up extractor" and it works great. I found a .data file for my app.
To be clear, I found a .data file and I would to open and see what the contents look like. I understand no software (Ex: notepad) might be able to read that file and I may have to use Xcode. If you know of any way, Xcode/notepad/someProgram, please let me know.
This is the code that I implement when I build the app:
- (NSString *)locPath {
    return pathInDocumentDirectory(@"tableArray.data");
}

- (void)archieve{
    // Get the path to the document directory
    NSString *path = [self locPath];

    // grab the array
    NSMutableArray *tableArray = [someViewController tableArray];

    // archive the array to file
    [NSKeyedArchiver archiveRootObject:tableArray toFile:path];
}

This code is called during applicationWillTerminate, applicationDidEnterBackground, etc...
The data is restored/called upon in the didFinishLaunchingWithOptions like this:
// Get the path to the document directory
NSString *path = [self locPath];

// Unarchive .data into an array
NSMutableArray *tableArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

Any help is appreciated! Thanks!!!
PS: Link for iPhone back up extractor is http://supercrazyawesome.com/

A: The easiest way I found is to get the document directory using this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dir = [paths objectAtIndex:0];
NSLog(@"Directory: %@", dir);

In there, the Documents dir will contain the .data file


text:
Q: Un formato de fechas que entre en los datos DATE de phpmyadmin Tengo una tabla Seguro con la siguiente lista de variables:
int idSeguro;
String nif;
String nombre;
String ape1;
String ape2;
int edad;
int numHijos;
LocalDate fechaCreacion;

Y lo quiero relacionar con esta tabla que tengo en phpMyAdmin.

Y este esto es lo que me veo al intentar introducir una fila en la tabla.

¿Como consigo introducir correctamente la fecha?

A: Ya lo he arreglado. Me habia olvidado que al introducir un valor en la tabla en la variable DATE debia ponerlo con sus comillas, al igual que los String.
int d=s.executeUpdate("insert into seguro values("+seguro.idSeguro+",'"+seguro.nif+"','"             +seguro.nombre+"','"+seguro.ape1+"','"+seguro.ape2+"','"+seguro.edad+"',"
                +seguro.numHijos+",'"+seguro.fechaCreacion+"')");


text:
Q: In JavaScript, when a local variable is hoisted, is it in scope even before it is declared? In the book Secrets of the JavaScript Ninja, p. 43 - 46, it has some code like:
function assert(flag, msg) {
    if (!flag) {
        console.log("Assertion failed for: " + msg);
    }
}

function outer() {
    var a = 1;

    function inner() { }

    assert(typeof b === "number", "b is in scope");
    var b = 1;
}

outer();

And the conclusion is, since the assertion failed, that "b is not in scope yet, until it is declared".  But I am thinking it is otherwise, because first of all, b can be having a local scope already, but just that it is not a "number" yet.  b in fact is already a local scope b, and will shadow any global b.
For example:
var b = 123;

function foo() {
    b = 456;

    var b = 789;
}

foo();

console.log(b);   // prints out 123

since it prints out 123, so we can see that when the line b = 456; is executed, b is already a local scope b. (even though before the assignment it is uninitialized yet).
Also, we can print it out instead of assigning to b:
var b = 123;

function foo() {
    console.log(b);  // prints out undefined

    var b = 789;
}

foo();

console.log(b);     // prints out 123

so again, we can see that the first print out is not 123 but is undefined, meaning the b is a local scope b, and therefore, b really is already in scope in the book's example.
Is the above description and concept correct?

A: Indeed, the book's conclusion is wrong. var b anywhere inside a function means b exists anywhere inside the function. That's what "hoisting" is. All var and function declarations are hoisted to the top, regardless of where they occur in the scope. The value has simply not been assigned yet.

A: Regarding the code:
assert(typeof b === "number", "b is in scope");
var b = 1;

The statement:

"b is not in scope yet, until it is declared"

is wrong. b is 'in scope' (because it's declared, it's created before any code is executed) but has not yet been assigned a value, so typeof b returns undefined and the test fails.

Is the above description and concept correct?

Yes, more or less. A simpler proof is:
function foo() {
  alert(b);
  var b = 5;
}

function bar() {
  alert(x);
  x = 5;
}

foo() // 'undefined' since b is "in scope" but hasn't been assigned a value yet

bar() // throws an error since x isn't "in scope" until the following line.


text:
Q: g++ is not recognized as an internal or external command, works from bin directory When I use it with c:\mingw\bin\gcc it works but when I try to run it from some other directory it doesn't. I'v set the environment variable path to:

c:\mingw\bin;

I am using windows 10.


text:
Q: Contains: Get a specific word in a specific starting/ending point This question is similar to this one, however, I would like to do this without having to create any extra separated function, is it possible?
What do I have:

*

*Load_XXXX.5gpl_TempCycle

*RO_Mass_Load_XXXX.AAAA-31974-B

*RO_Mass_Load_XXXX.AAAA-31980

*RO_Mass_Load_Test_4a-B_TempCycle_20170427-41309

*Load_Test_4a_TempCycle

I wanna take out:

*

*only the ones that start with "Load_".

*or finishes with "-B"

Problem:
If I use Contains(string), it will take out all of them.
What do I need:
A Contain (or something else?) that takes out strings that start with "Load_" or finishes with "-B".
Result expect:

*

*RO_Mass_Load_XXXX.AAAA-31980

*RO_Mass_Load_Test_4a-B_UUU_20170427-41309

Code not working(it gets everything out):
if (item.Full_File_Name.Contains("-B") || item.Full_File_Name.Contains("Load"))

Any ideas or help?

A: You have prepared functions for that: StartsWith and EndsWith
if (item.Full_File_Name.EndsWith("-B") || item.Full_File_Name.StartsWith("Load"))

If we want one or the other, we should use:
if (!item.Full_File_Name.EndsWith("-B") && !item.Full_File_Name.StartsWith("Load_"))


text:
Q: select from db with phpoo i guys, where i am again with noob questions
i made before 1 page alone for select data from my db and it works, is this the code:
    <?php
$ligacao = mysql_connect("localhost", "root", "") or die
("problemas na ligaçao ao MySQL");
mysql_select_db("test", $ligacao);
$sql = "select nome, telefone from teste";
$resultado = mysql_query($sql, $ligacao);
while ($registo = mysql_fetch_row($resultado)){
      print ("$registo[0] --- $registo[1]
");
}
mysql_close();
?>

now i tryed to put that in classes and functions to run safe and i did something like this
in the class folder:
    <?php
class vari{
    /* variables needed */
    protected $hostname;
    protected $username;
    protected $dbpass;
    protected $db;
    protected $sql;
    protected $ligacao;
    protected $resultado;
    protected $registo;

    public function liga() {
        $db = new vari;
        $db->hostname = 'localhost';
        $db->username = 'root';
        $db->dbpass = '';
        $db->db = 'mysql_select_db("test", $this->liga)';
        $db->sql = '"select nome, telefone from teste";';
        $db->ligacao = 'mysql_connect($this->hostname, $this->username, $this->dbpass)';
        $db->resultado = 'mysql_query($this->sql, $this->ligacao)';
        $db->registo = 'mysql_fetch_row($this->resultado)';

        mysql_select_db($db->db, $db->ligacao);
        while ($db->registo = 1){
            print ("$db->registo[0] --- $db->registo[1]
");
        }
        mysql_close();
}
}

and in the index put that:
    <?php
include 'class/classes.php';

$data= new vari;

$data->liga();
?>

after all that hard work i go to see what hapenned and i have an infinit looping like this:
PHP Error Message

Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /home/test1/class/classes.php on line 24

Free Web Hosting
1[0] --- 1[1]
1[0] --- 1[1]
1[0] --- 1[1]
1[0] --- 1[1]
1[0] --- 1[1]
1[0] --- 1[1]

what is wrong with that code? i get the meaning of function and class a litle bit, im learning but the problem here is with the variables i think, can you guys help me fix that? sorry for the long post...
and thanks straight away for the awsers ;)
kjonh2

A: As many have pointed out,  you shouldn't be using mysql_, but to answer your question directly, you have this line in your code:
$db->db = 'mysql_select_db("test", $this->liga)';

well, since $this->liga isn't a property, but rather the current method/function name, it just calls itself. You need to move that line further down the code and change it use $this->ligacao


text:
Q: In Spearman's rank correlation: 4 out of 26 observations totally change the conclusion, what should I do? After I remove these 4 observations, the results change from weak and not statistically significant to the opposite (rho=0.559 with p<0.01). Should I just remove them or what should I do? Although the Spearman correlation is robust against outliers, can I call these observations outliers? If so, how should I deal with them?
I am calculating the correlation coefficients by using this Excel file, which is taken from this website. Is it accurate?
Here are the data:
X:    6 51  111 123 157 168 195 195 200 205 214 222 229 234 241 256 314 340 352 368 427
    431 442 473 501 523 994
Y:    2 16  12  41  28  11  36  13  16  17  15  18  19  33  75  12  75  22  50  5   26
     45 14  9   27  9   98

A: The phenomenon you observe is caused by the use of Spearman's $\rho$ coefficients, which has the undesirable property that it is easily swayed by the presence in the sample of even a few observations that happen to depart from the bivariate ellipse fitting of the bulk of the data.
The general solution to this problem is to replace the Spearman $\rho$ by a robust alternative. In a nutshell, robust estimation procedures were designed to fit a model that is cannot be easily swayed by a handful of non-conforming data-points.
A popular such algorithm is FastMCD [1,2]. The aim of FMCD is to find the model that best fits the central observations in your dataset. Observations that are far from the FMCD fit are flagged as outliers. They do not part take in the estimation of the coefficients fitted by FMCD. They should be modelled separately from the remaining bulk of the data: their very distance from the FMCD fit makes them unduly influential on any classical statistical analysis that would include them alongside the rest of the data-set.
Now, I turn to your specific problem. Here is the code to run FMCD on your dataset:
X <- c(6, 51,  111, 123, 157, 168, 195, 195, 200, 205, 214, 222, 229, 234, 241, 256,
       314, 340, 352, 368, 427, 431, 442, 473, 501, 523, 994)
Y <- c(2, 16,  12,  41,  28,  11,  36,  13, 16, 17, 15, 18, 19, 33, 75, 12,
       75, 22, 50, 5,  26, 45, 14, 9, 27, 9, 98)
library("rrcov")
library("fBasics")
a1 <- CovMcd(cbind(X, Y), nsamp="exact")
  #Spearman rho on the observation not classified as outliers:
spearmanTest(X[a1@raw.wt==1], Y[a1@raw.wt==1])

These observations row index: (2,3,6,8,9,10,11,12,13,16,18,20,23,24,26) are, in the sense of FMCD, those most central point in your dataset. Furthermore, the following observations:  (4,7,15,17,19,22,27) have been identified by FMCD to be highly influential: they stand so far out from the model fitting the bulk of the data that they, if left unchecked, will (either alone, or together) single handedly sway the resulting fit. Finally, the Spearman $\rho$ of the observations not flagged as outliers by FMCD is now $\approx0.07$ (p=0.77).
In short, the main advantage of the FMCD fit lies in its resilience (the technical term is robustness) to the contamination of the sample by a few inconsistent data points. For example, it would be very difficult to find 4 points such that by removing them will significantly alter the solution found by FMCD.
EDIT:
As suggested by @amoeba I'm illustrating the resilience of the FMCD to the removal of 4 data points from the set (those with indexes 20 23 24 26, these were picked by @amoeba, see comments below). Looking at the estimation results obtained re-running FMCD on this amputated data-set, 14 of the 16 observations  not classified as outliers by the FMCD fit of the original data-set (and not subsequently removed from the data-set) still are classified as such. The Spearman $\rho$ of the good data went from $0.07$ (p=0.77) on the original data to $0.21$ (p=0.43) on the data set with the four observations selected by @amoeba removed (so the conclusions of the analysis remain the same).
@whuber suggested plotting a scatterplot of the rank of the data to better show the effect of the outliers. The observations flagged as outliers by FMCD are shown as red dots.
@Thomas Speidel. Spearman's $\rho$ has good robustness property, so long as the rate of contamination of the sample is smaller than 5%. For a more in depth (including formal) study of these issues, see [ 3]:

*

*P. J. Rousseeuw and K. van Driessen (1999) A fast algorithm for the minimum covariance determinant estimator. Technometrics 41, 212–223.

*Ricardo A. Maronna, Douglas R. Martin, Victor J. Yohai (2006).
Robust Statistics: Theory and Methods (Wiley Series in Probability and Statistics).

*Christophe Croux & Catherine Dehon, 2010. "Influence functions of the Spearman and Kendall correlation measures," Statistical Methods and Applications, vol. 19(4), pp 497--515.


text:
Q: Do ESFs have different abilities? As a member of the Vanu Sovereignty, I know that the Scythe has a speed-boosting ability, but it looks like the TR Mosquito has landing gear or something, which I don't seem to have. What's that do? I assume that the NC has a third?

A: Short answer: No.
Longer answer: All Empire-Specific Fighter aircraft (Scythe, Mosquito and Reaver) start with the same basic afterburner ability. The acceleration and top speed this ability can achieve vary between specific fighters and can be altered by that aircraft's Performance certifications.
If the pilot has invested points into the appropriate Utility Slot certifications, they may also be able to equip additional abilities, such as the Scout Radar (nearby enemies shown on map), Decoy Flares (disrupts missile lock-on attempts), Ejection System    (pilots can bail out safely) and Fire Suppression System (removes the effects of critical damage). The abilities are the same across all factions.
Other abilities are also available in the Defense Slot category, such as Composite Armor, Nanite Auto Repair System and Vehicle Stealth. These are passive systems that do not need to be activated.

A: Simply put, each empire/faction has a special characteristic:

*

*VS fighters are more maneuverable and have the best hover ability.

*TR fighters are the fastest both in speed and standard fire rate.

*NC fighters are the most durable, with excellent armor and have the hardest-hitting weapons.

In battle these advantages are not very prominent, but they can make a big difference.


text:
Q: cosmos gremline cross container mapping Cosmos DB Gremlins two graph ( container ) - graph1 & graph 2 .
graph1- - person(node )
graph2- - city(node )
can we make edge between person and city where they are located different container ?

A: can we make edge between person and city where they are located different container ?
No, AFAIK it is not possible. You can only connect two nodes in the same container.


text:
Q: Dynamically predicting the time based on hourly average I have a table like this below
Date      Start Time  End Time    Hours  Capacity  Hourly Avg
2021-03-12  09:00      11:00        2      2         1
2021-03-13  09:00      12:00        3      6         2
2021-03-14  09:00      11:00        2      4         2

I have a set of orders with me, So based on the above table i need to propagate and find out at what time the below orders will be processed.
Q.No. Order no
1   "S0001"
2   "S0009"
3   "S00010"
4   "S0023"
5   "S0022"
6   "S0021"
7   "S00201"
8   "SO7532"
9   "SO7567"
10  "SO7456"
11  "SO7447"
12  "SO7908"

For example, The expected output will be like below,Based on the hourly average on top i need to split and forecast a time when this will be processed.
 Q.No. Order no    Expected Processing time
    1   "S0001"        2021-03-12 10:00:00
    2   "S0009"        2021-03-12 11:00:00
    3   "S00010"       2021-03-13 10:00:00
    4   "S0023"        2021-03-13 10:00:00
    5   "S0022"        2021-03-13 11:00:00
    6   "S0021"        2021-03-13 11:00:00
    7   "S00201"       2021-03-13 12:00:00
    8   "SO7532"       2021-03-13 12:00:00
    9   "SO7567"       2021-03-14 10:00:00
    10  "SO7456"       2021-03-14 10:00:00
    11  "SO7447"       2021-03-14 11:00:00
    12  "SO7908"       2021-03-14 11:00:00

I'm doing it with PostgreSQL version 11, But didn't able to do this dynamically.Any help on this will , Will be grateful.
Below is a sample code i use to find the expected time of processing of the orders,But i have remaining x orders which cannot be processed today and need to be processed tomorrow and so on based on the capacity and the hourly average.
Basically i need the below code to be recursive and do it same for other days.
I'm stuck at doing it dynamically.Any solution for this ?
 With orders_to_be_processed_estimation AS
    (
    select *,NTILE(orders_picked_today/hourly_average)
OVER(ORDER BY queue_no) as partitions
    from pending_orders_to_be_picked_details
    ORDER BY partitions,queue_no
    )
    SELECT *,NOW() + INTERVAL '1 hour' * partitions
FROM  orders_to_be_processed_estimation

Thanks you

A: demo:db<>fiddle
SELECT
    o.id,
    o.no,
    c.gs as processed
FROM (
    -- Second part
    SELECT
        *,
        row_number() OVER (ORDER BY id)
    FROM orders
) o
JOIN (
    -- First part
    SELECT
        gs,
        row_number() OVER (ORDER BY proc_date, start_time, end_time)
    FROM capacities,
        generate_series(proc_date + start_time + interval '1 hour', proc_date + end_time, interval '1 hour') gs,
        generate_series(1, hourly_avg)
) c
ON o.row_number = c.row_number

First part:
SELECT
    *,
    -- 3
    row_number() OVER (ORDER BY proc_date, start_time, end_time)
FROM capacities,
    -- 1
    generate_series(proc_date + start_time + interval '1 hour', proc_date + end_time, interval '1 hour') gs,
    -- 2
    generate_series(1, hourly_avg)

Which returns (note the three last columns):
> proc_date  | start_time | end_time | hours | capacity | hourly_avg | gs                  | generate_series | row_number
> :--------- | :--------- | :------- | ----: | -------: | ---------: | :------------------ | --------------: | ---------:
> 2021-03-12 | 09:00:00   | 11:00:00 |     2 |        2 |          1 | 2021-03-12 10:00:00 |               1 |          1
> 2021-03-12 | 09:00:00   | 11:00:00 |     2 |        2 |          1 | 2021-03-12 11:00:00 |               1 |          2
> 2021-03-13 | 09:00:00   | 12:00:00 |     3 |        6 |          2 | 2021-03-13 10:00:00 |               1 |          3
> 2021-03-13 | 09:00:00   | 12:00:00 |     3 |        6 |          2 | 2021-03-13 10:00:00 |               2 |          4
> 2021-03-13 | 09:00:00   | 12:00:00 |     3 |        6 |          2 | 2021-03-13 11:00:00 |               1 |          5
> 2021-03-13 | 09:00:00   | 12:00:00 |     3 |        6 |          2 | 2021-03-13 11:00:00 |               2 |          6
> 2021-03-13 | 09:00:00   | 12:00:00 |     3 |        6 |          2 | 2021-03-13 12:00:00 |               1 |          7
> 2021-03-13 | 09:00:00   | 12:00:00 |     3 |        6 |          2 | 2021-03-13 12:00:00 |               2 |          8
> 2021-03-14 | 09:00:00   | 11:00:00 |     2 |        4 |          2 | 2021-03-14 10:00:00 |               1 |          9
> 2021-03-14 | 09:00:00   | 11:00:00 |     2 |        4 |          2 | 2021-03-14 10:00:00 |               2 |         10
> 2021-03-14 | 09:00:00   | 11:00:00 |     2 |        4 |          2 | 2021-03-14 11:00:00 |               1 |         11
> 2021-03-14 | 09:00:00   | 11:00:00 |     2 |        4 |          2 | 2021-03-14 11:00:00 |               2 |         12

*

*Generate an hourly time series from start to end. Because we are only interested in hourly end times, we leave out the first hour, so start is an hour later

*Generate a simple integer series from 1 to the hourly average capacity (= n). This duplicates the currently created time records n times. Now you have as much as records as you expect: One record per free capacity per hour.

*Now we have to create a join condition to be able to join the orders table. This can be done using the row_number() window function which adds a cumulative row count to the generated series.

Second part is simple: I added the row_number() here as well to ensure the same row numbers as at the other table. However, if your id column looks that nice in your real case, it is not necessary, so you can join directly on it, of course.
Unrelated:
It is not a good idea to store generated/calculated data in the table. So, if you once changed, e.g., the end_time, you need to change also the column hours and the hourly_avg manually. These data can be easily calculated if necessary.

A: I would use a running sum on the capacity to get "start" and "end" limits.  Then join:
select pop.*,
       (s.starttime +
        (ceiling( row_number() over (partition by s.date order by pop.seqnum) / s.hours) - 1) * interval '1 hour'
        )
       ) as estimated_start_time
from (select pop.*,
             row_number() over (order by queue_no) s seqnum
      from pending_orders_to_be_picked_details pop
     ) pop left join
     (select s.*,
             sum(capacity) over (order by starttime) - capacity as start_capacity

      from scheduling s
     ) s
     on pop.seqnum >= s.start_capacity and
        pop.seqnum < s.start_capacity + s.capacity

The calculation for the expected hour is a little tricky.  It divides the queued orders into groups for each hour.


text:
Q: How to get firstInstallTime in android 2.2? I want the first install time on android version 2.2. I have done in android 2.3, how to do in android 2.2
Here is my code
try
    {
        long installed = context.getPackageManager().getPackageInfo("com.simsys.securex", 0).firstInstallTime;
        String DateTimeStamp=getDate(installed, "dd/MM/yyyy hh:mm:ss");
        String dateTimeSync="Installed_Date:";
        String dateTimeSync2=dateTimeSync.concat(DateTimeStamp);
        TextView txtCurrentTime= (TextView)findViewById(R.id.textViewdatetime);
        txtCurrentTime.setText(dateTimeSync2);
    }
    catch (NameNotFoundException e)
    {
        e.printStackTrace();
    }

A: PackageManager packageManager = context.getPackageManager();
ApplicationInfo appInfo = packageManager.getApplicationInfo("com.simsys.securex", 0);
String sourceDir= appInfo.sourceDir;
long dateTimeSync= new File(sourceDir).lastModified();


text:
Q: How to iterate over a complex associative array? I'm working with the following array.
Array
(
[device_id] => 432552343242
[host_name] => computer
[serial_number] => 32525243
[manufacturer] => HP
[model] => ProLiant BL460c Gen9
[locations] => Array
    (
        [0] => Array
            (
                [name] => New York
            )

    )

[cpu_count] => 1
[core_count] => 6
[is_virtual] =>
[operating_system] => Array
    (
        [version] => 6.6 Santiago
        [product] => Array
            (
                [vendor] => Varied
                [description] => ProductAdapter for handling various Unix or
Linux based Operating Systems (HP-UX, AIX, Solaris, Ubuntu, etc...)
                [name] => Unix Operating Systems
            )

        [name] => Linux Server
    )

[users] => mydomain.com/users
[applications] => mydomain.com/applications
[qualified_name] => Array
    (
        [0] => Array
            (
                [name_type] => UnixName
                [name] => cbc.com
            )

        [1] => Array
            (
                [name_type] => DNSFQDN
                [name] => abc.com
            )

        [2] => Array
            (
                [name_type] => DNSDomain
                [name] => bbc.com
            )

        [3] => Array
            (
                [name_type] => OriginalHostname
                [name] => cnn.com
            )

    )
)

When I try to loop through the array in order to insert it into a database I get 13 entries.
Here is my code.
$array = json_decode($result, true);
foreach($array as $key=>$value) {
$hostname = $array['locations'];

$stmt = $mysqli->prepare("INSERT INTO test (Hostname) VALUES (?)");
$stmt->bind_param("s", $hostname);
$stmt->execute();
$stmt->close();
}

I know why its adding it 13 teams. Its looping through each index in the array and inserting the hostname for each one. How can I just get it to insert it ones? Do I have to create a for statement? Or a foreach within a foreach? Any help would be appreciated? Newbie here.

A: You are looping as many times as you have indexes in your biggest array, BUT you don't use $key and $value. Your code is exactly doing what you said to him to do:

*

*for each value -> so 13 loop

*

*get the $array['location'] value

*insert it into your database

*end of your foreach

If you just want to insert your $array['locations'], why are you using a foreach ?
You are inserting just one value, and you know it's index, so you don't really need to use a foreach
With a foreach you can do:
$array = json_decode($result, true);
foreach($array as $key=>$value) {
    if ($key === "location")
    {
        //$hostname = $array['locations'];
        $hostname = $value;

        $stmt = $mysqli->prepare("INSERT INTO test (Hostname) VALUES (?)");
        $stmt->bind_param("s", $hostname);
        $stmt->execute();
        $stmt->close();
    }
}

But there is no real need.
I would more write it like that:
$array = json_decode($result, true);
$hostname = $array['location'];

$stmt = $mysqli->prepare("INSERT INTO test (Hostname) VALUES (?)");
$stmt->bind_param("s", $hostname);
$stmt->execute();
$stmt->close();

[EDIT]
If you want to loop to insert differents elements of your array, you should use the $key and $value variables.
$array = json_decode($result, true);
foreach($array as $key=>$value) {
    if ($key === "location")
    {
        $hostname = $value; //contains $array['location']

        $stmt = $mysqli->prepare("INSERT INTO test (Hostname) VALUES (?)");
        $stmt->bind_param("s", $hostname);
        $stmt->execute();
        $stmt->close();
    } else if ($key === 'device_id')
    {
        $devide_id= $value; //contains $array['device_id']

        $stmt = $mysqli->prepare("INSERT INTO test (DeviceId) VALUES (?)");
        $stmt->bind_param("s", $devide_id);
        $stmt->execute();
        $stmt->close();
    } else if ($key === 'device_id')
    {
        $devide_id= $value; //contains $array['device_id']

        $stmt = $mysqli->prepare("INSERT INTO test (DeviceId) VALUES (?)");
        $stmt->bind_param("s", $devide_id);
        $stmt->execute();
        $stmt->close();
    } else if ($key === 'device_id')
    {
        $devide_id= $value; //contains $array['device_id']

        $stmt = $mysqli->prepare("INSERT INTO test (DeviceId) VALUES (?)");
        $stmt->bind_param("s", $devide_id);
        $stmt->execute();
        $stmt->close();
    } else if ($key === 'device_id')
    {
        $devide_id= $value; //contains $array['device_id']

        $stmt = $mysqli->prepare("INSERT INTO test (DeviceId) VALUES (?)");
        $stmt->bind_param("s", $devide_id);
        $stmt->execute();
        $stmt->close();
    } else if ($key === '...')
    {
        //etc
    }
}

But if you know exactly the keys of your values in your array, I would do it more like that:
$hostname  = $array['location'];
$devide_id = $array['device_id'];

$stmt = $mysqli->prepare("INSERT INTO test (Hostname) VALUES (?)");
$stmt->bind_param("s", $hostname);
$stmt->execute();

$stmt = $mysqli->prepare("INSERT INTO test (DeviceId) VALUES (?)");
$stmt->bind_param("s", $devide_id);
$stmt->execute();

$stmt->close();


text:
Q: Modifying vlookup range or looping its range Hope you're doing great, need help with below code that is supposed to match first column from 2 files then vlookup and copy paste the matched results. the problem is that i'm limited by vlookup range that only works for one column so i tried to make a loop to make it work on multiple number of cells as shown below but it's not working, any help or hints would be really welcomed, Thanks.
edit
the problem lies where iis used in the funcStr for the vlooukp table range and column's number, i need the range to be increased and column number to constinatly change to get the whole row copied instead.
Sub solution()

Dim oldRow As Integer
Dim newRow As Integer
Dim lrow_output As Integer
Dim WB_Input As Workbook
Dim WB_Output As Workbook
Dim WS_Input As Worksheet
Dim WS_Output As Worksheet
Dim funcStr As String
Dim i As Integer

Set WB_Input = Workbooks("File.xlsm")
Set WB_Output = Workbooks("output1.xlsx")

Set WS_Input = WB_Input.Worksheets("input")
Set WS_Output = WB_Output.Worksheets("Sheet1")

With WS_Output
    lrow_output = .Cells(.Rows.Count, 1).End(xlUp).Row
End With
For i = 2 To 6
With WS_Input
    funcStr = "=IFERROR(VLOOKUP(" & Cells(1, 1).Address(False, False) & "," & "'[" & WB_Input.Name & "]" & .Name & "'!" & Range(.Columns(1), .Columns(i)).Address & ",i,0),"""")"
End With
With WS_Output
    .Cells(1, i).Formula = funcStr
    .Cells(1, i).Copy
    Range(.Cells(1, i), .Cells(lrow_output, i)).PasteSpecial xlPasteFormulas
    WS_Output.Calculate
    Range(.Cells(1, i), .Cells(lrow_output, i)).Copy
    Range(.Cells(1, i), .Cells(lrow_output, i)).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    End With
Next i
End Sub


text:
Q: Passing input parameters to node mssql query function I'm using a Node.js server to make requests to an Azure sql database.
As far as I understand the following function does not prevent sql injection:
Current code: (working but unsafe)
var executeQuery = async function(query, response) {
    const pool = new sql.ConnectionPool(dbConfig)

    pool.on('error', err => {
        console.log('sql errors', err);
    });

    try {
        await pool.connect();
        let result = await pool.request().query(query);
        response.send(result.recordset);
        return {success: result}
     } catch (err) {
        return {err: err};
     } finally {
        console.log('request complete')
        pool.close();    // closing connection after request is finished
     }
};

app.get("/api/workOrders/byId/:workOrderId", function(req, res) {
    console.log(req.params);
    var query = "SELECT * FROM [WorkOrder] WHERE [idWorkOrder]=" + req.params.workOrderId;
    executeQuery(query, res);
});

I would like to have the executeQuery function standalone, but I did not find an answer for that yet. Anyway, this is the code I constructed from mssql documentation:
New Code (not working)
app.get("/api/test/:workOrderId", function(req, res) {
console.log(req.params.workOrderId);

(async function() {
        const pool = new sql.ConnectionPool(dbConfig)
        pool.on('error', err => {
            console.log('sql errors', err);
        });

        try {
            await pool.connect();
            let result = await pool.request()
              .input('input_parameter', sql.VarChar(50), req.params.workOrderId)
              .query('SELECT * FROM [Quotation] WHERE [idWorkOrder]= @input_parameter');

              console.log(result);

            res.send(result.recordset);
            return {success: result}
         } catch (err) {
             return {err: err};
         } finally {
          console.log('request complete')
          pool.close();    // closing connection after request is finished
    }
  });

})

This version should be injection proof, but It does not return anything. Is there an option to pass the input values to the executeQuery function as in the current code?

A: You can pass the value of req.params.workOrderId into your async function and then use that value inside. check the following code.
app.get("/api/test/:workOrderId", function(req, res) {
console.log(req.params.workOrderId);

(async function(workOrderId) {
        const pool = new sql.ConnectionPool(dbConfig)
        pool.on('error', err => {
            console.log('sql errors', err);
        });

        try {
            await pool.connect();
            let result = await pool.request()
              .input('input_parameter', sql.VarChar(50), workOrderId)
              .query('SELECT * FROM [Quotation] WHERE [idWorkOrder]= @input_parameter');

              console.log(result);

            res.send(result.recordset);
            return {success: result}
         } catch (err) {
             return {err: err};
         } finally {
          console.log('request complete')
          pool.close();    // closing connection after request is finished
    }
  })(req.params.workOrderId); // <===pass value to the function

})


text:
Q: Random walks with exponential decreasing steps Let $g$ be the golden number (or another algebraic integer in $(0,1)$ that fullfills an equation with coefficients $\pm 1$). Consider the random walk on $\mathbb{R}$ starting with $0$ and walking $g^{n}$ with probability $1/2$ left or right in step $n+1$. What is the probability to return to $0$ exactly $m$-times. Here $m$ maybe $0$ and $\infty$ as well. If $g$ ist not as described the walk will of course not return at all.

A: In the case of the golden number $g = (\sqrt{5}-1)/2$, we have
$g^n = (-1)^n (F_{n-1} - F_n g)$ where $F_n$ is the $n$'th Fibonacci number.
Let $a_i, i=0,1,2,\ldots$ be $+1$ if the $i+1$'th step is to the right, $-1$ if it is to the left.  Then we return to the origin after $n$ steps iff
 $\sum_{i=0}^{n-1} a_i F_i = 0$ and $\sum_{i=0}^{n-1} a_i F_{i-1} = 0$.
Note that $\sum_{i=0}^{n-1} a_i F_i \equiv 1 \mod 2$ if $n \equiv 2 \mod 3$
and $\sum_{i=0}^{n-1} a_i F_{i-1} \equiv 1 \mod 2$ if $n \equiv 1 \mod 3$, so
the only possibilities for return are with $n$ divisible by $3$.  Moreover, if
 $a_{n-3}, a_{n-2},a_{n-1}$ are not either $[1,1,-1]$ or $[-1,-1,1]$ then we have
$$ \eqalign{\left| \sum_{i=0}^{n-1} a_i F_i \right| &\ge F_{n-1} - F_{n-2} + F_{n-3} - \sum_{i=0}^{n-4} F_i  \cr &= -1-\dfrac{  \sqrt {5}-1 }{2}  \left( \dfrac{1-\sqrt {5}}{2}
 \right) ^{n-3}+ \dfrac{ \sqrt {5}+1}{2}  \left( \dfrac{\sqrt {5
}+1}{2} \right) ^{n-3}\cr
&> 0 \ \text{for}\ n \ge 4}$$
So the only ways to ever return to the origin are to return to the origin after every $3$ steps, each three steps being either $+,-,-$ or $-,+,+$.
The probability of having exactly $m$ returns to the origin is then the probability that the first $3m$ steps follow this pattern but the next $3$ do not, thus $3 \times 4^{-m-1}$.
EDIT: A simpler argument in the case of the golden number:
Note that if $(a_0, a_1, a_2)$ is not $(1,-1,-1)$ or $(-1,1,1)$,
$$|a_0  + a_1 g + a_2 g^2| \ge 3 - \sqrt{5} > g = \sum_{n=3}^\infty g^n$$
So if you don't return to the origin after the first $3$ steps, you are too
far away to ever return.  Similarly for $(a_{3n}, a_{3n+1}, a_{3n+2})$ where
$\sum_{i=0}^{3n-1} a_i g^i = 0$...
A similar argument works for the next case, where $g$ is the real root
(approximately $0.5436890127$) of $X^3 + X^2 + X - 1$.  If
$(a_0,a_1,a_2,a_3)$ is not $(1,-1,-1,-1)$ or $(-1,1,1,1)$,
$$|a_0 + a_1 g + a_2 g^2 + a_3 g^3| \ge 1 - g - g^2 + g^3
> \dfrac{g^4}{1-g} = \sum_{i=4}^\infty g^i$$
so the only way to ever return to the origin is to return every $4$ steps.
However, this argument won't work for the positive root (approximately $0.8483748957$) of $X^4 + X^3 + X^2 - X - 1$.  For this case, is it possible to return to the origin without returning after the first $5$ steps?


text:
Q: Loosing focus on the frame on click of ok button on joption pane I have created a panel which displays scaled images .On clicked on the scaled image, I shows the image with larger view in a frame.When I cropped the area on frame it shows cropped image in Joption pane and when I clicked ok , It returns the focus on to the main Panel and frame with enlarge view of image get minimized.
Here i dont want to loose the focus on the enlarge image frame view. Is any one can help me out with it.
enter code here
        imgPane = new CropImagePane(imagePath);
        frame= new MyFrame("Crop Area");
        frame.add(imgPane);
        frame.setSize(400,600);
        frame.setResizable(false);
        frame.toFront();
        frame.setVisible(true);


text:
Q: Angular Drop Down Not Showing Elements In my html component, I have the following:
        <select class="hideLabel form-control" [(ngModel)]="model.powerPlantType" name="powerPlantType" (change)="selectName();">
          <option selected="" value=""></option>
          <option [ngValue]="powerPlantType" *ngFor="let powerPlantType of powerPlantTypes">
            {{ powerPlantType }}
          </option>
        </select>

It displays fine as it can be seen from the screenshot below:

How do I add a message that says "--Select Type--" text when the page is loaded?
EDIT: Based on the suggestions from the post below, I could still not get it to work: So when the page loads the dropdown is still empty without the intended default test "--Select Type--"

But the test seem to appear when selcting the drop down!

I would rather like to have it like this when the page is loaded:

A: Change your html to following:
<select class="hideLabel form-control" [(ngModel)]="model.powerPlantType" name="powerPlantType" (change)="selectName();">
    <option selected="" value="">--Select Type--</option>
    <option [ngValue]="powerPlantType" *ngFor="let powerPlantType of powerPlantTypes">
        {{ powerPlantType }}
    </option>
</select>


text:
Q: daily 15 minutes downtime for half a year on GAE-python Happens every midnight PST.
Makes even the built-in 404 responses take minutes to complete (with DeadlineError, of course).
I reported it back in March, others must have done before.
Is there something to avoid in the code to somehow alleviate this?
Using python2.5 on M/S datastore.

A: As per here:
https://developers.google.com/appengine/docs/python/datastore/usingmasterslave
The master/slave datastore is deprecated; you should probably try to migrate to the high replication datastore. The HRD is much less susceptible to abnormal latency events in the backend, as it distributes requests to multiple datacenters.
You can migrate by following these directions:
https://developers.google.com/appengine/docs/adminconsole/migration
(Full disclosure: I work for Google as an SRE. While I do not work directly on AppEngine, I maintain services that run on the same backend technologies as AppEngine.)


text:
Q: How to rename media file before transfer from channel A to B (client.send_message)? I'm looking to a way to rename file before it's transfer to the other channel
so what I want is:

*

*telethon is reading texts and media(with caption) from channel "A"

*then rename media to specific name "abc.jpg" or "abc.mp3"

*telethon send texts and media(with caption) to channel "B"

i'm using this code
@client.on(events.NewMessage(chats=input_channels_entities))
async def handler(event):
    for output_channel in output_channel_entities:
        await client.send_message(output_channel, event.message)

is there specific to do? I looked over Telethon docs and searched every place but no luck

A: In your case you didn't find it on Telethon docs out because is not related to Telegram, but to the file itself.
Since you're willing to rename the file before sending it to the other channel, the simplest way is to download the file itself via its file ID stored in the Telegram servers thanks to the getFile method.
Once you download it locally, you can rename it directly and let your chatbot send it once through the methods offered by Telegram Chatbot API.
This last point is generic, because it depends by the file type you're willing to forward (audio, image, video, zip, document, etc.): additional information could be find out here: https://core.telegram.org/bots/api#available-methods


text:
Q: How does one show $S \sim \frac{N^2}{4}(2 \ln(N) - 1) $? So I used some non-rigorous means to show:
$$ S(N)=  \sum_{
\substack{
k,r =1 \\
k \leq r
}}^N \frac{r}{k} \sim \frac{N^2}{4}(2 \ln(N) - 1) $$
Is this correct? How would one go about proving this?

A: In my opinion is quite correct. If we study the series it's like to have
$$1\cdot(1 ) + 2\cdot(1  +\frac{1}{2} ) +\ldots + N\cdot(1  +\frac{1}{2}  +\frac{1}{3} + \ldots + \frac{1}{N})$$
Which behaves like $$\sum_{n} n H_n = \frac{1}{4} \left(2 N^2 H_{N+1}+2 N H_{N+1}-N^2-N\right)$$
Asymptotically, we have
$$\sim \frac{1}{4}(-N^2 + 2N^2H_{N+1})$$
Now
$$H_{N+1} \sim \ln(N+1) + \gamma$$
whence we can write
$$\sim \frac{1}{4}N^2(-1 + 2\ln(N+1))$$
Little improvements can be taken.


text:
Q: Load works once only with include and php I have a problem!
take a look at my code:
$( '#myModalEditaFunc' ).on( 'hide.bs.modal', function(e){
       $( ".class_exibir-funcionarios" ).load(
          location.href + ".class_exibir-funcionarios" );
})

The above code refresh the php page included on main page. Everyhtings works fine when I click the button , so the page is refreshed. But it works once only.
After that, when I click the button again, nothing happens and the page is not refreshed by .class_exibir-funcionarios.
my code
<?php

switch( $_GET[ 'page' ] ){
   case 'home':
   ?>

Por favor, selecione uma opção acima.

    <?php
       break;
       case 'exibir-funcionarios':
     ?>

<?php require_once( 'exibir-funcionarios.php' ); ?>

    <?php
      break;
     case 'cadastrar-novo-funcionario':
      require_once( 'cadastro-funcionario.php' );
       break;
     default:
   require_once( '404.php' );
       break;
  }
// END switch
?>

When I close my modal I call this:
$( '#myModalEditaFunc' ).on( 'hide.bs.modal', function(e){
       $( ".class_exibir-funcionarios" ).load( location.href + " .class_exibir-funcionarios" );
   });

So, the div .class_exibir-funcionarios is refreshed and its content as well.    But when I click the button to do the same operation the load does not works.
Help me please


text:
Q: Sequelize error: Unhandled rejection TypeError: Cannot read property '_pseudo of undefined I am cloned this app https://github.com/sequelize/express-example which appears to be the official sequelize express example but I get this error when I try to run it
Unhandled rejection TypeError: Cannot read property '_pseudo' of undefined
 at conformInclude (/Users/wasswasam/express-example-master/node_modules/sequelize/lib/model.js:277:14)
I am not sure what's going on.

A: I'm not sure myself but I do encounter this problem before. And I managed to solve this by removing the include param for findAll function
models.User.findAll({
    include: [ models.Task ]
  })

to
models.User.findAll()

The only think I can think is that you does not have the model it need.
Hope this help.

A: I get this error when the object in the include array is undefined. Usually caused by a dependency loop or a misspelled import.


text:
Q: Testing iterative code using mocks - does it make sense, how? I want to test an algorithm using mocks. The algorithm - in the current implementation - iterates over a container class in multiple passes and set()s and get()s values from it. The test's purpose is to verify the final result, stored in the container. The final value depends on values read and written in between the passes. e.g. the value of any element may change multiple times until the algorithm is finished and, most-likely, its value as result of iteration n will depend on its value after iteration n-1.
I like the idea of mocks and I would love to use them in the scenario described above since it would allow me to verify erroneous behavior of the algorithm once it occurs, not only when the computation is finished. However, I'm not sure whether this would actually be a good idea because I would then have to tie the expectations for the mock real close to the current implementation (e.g, "expect get(element n) and return x, then set(element n, value x+1), another get(n) and return x+1, then expect set(n, x+2) etc.").
Although allowing me to verify that intermediate values are as expected, I think such expectations would contradict the purpose of the test (verify that the algorithm computes the correct final value) and likely the test would fail if the implementation changes, regardless of the correctness of the final value.
Now my question: am I missing something? Is there nevertheless a good way to use mocks in this scenario? or does it simply make no sense to use them here? How do others deal with this problem?
Final remark: I'm talking about testing c++ code and using googlemock, if that makes any difference to your answer.
p.s.: I checked google and articles here (especially Mocking iterative behaviour - only tackles the problem of increasing a return value), however, I didn't find anything close to my problem.

A: Create your unit test for the final output of the algorithm. You want your automated testing to verify the expected result because that is what other parts of the program will utilize.
As far as testing the individual steps within the algorithm code, this is more a job for stepping through with a debugger -- not for automated tests. Going through the internal workings of the algorithm should be a one-time thing, and once you have it right there's no need to keep testing individual steps within it.

A: Unit tests would be more applicable on the smaller parts that compose the algorithm.
That being said, unit test tools are very helpful for developing algorithms that way.  They aren't bad at all to use, just don't hold on to them if they aren't valid anymore.  Usually you wouldn't test each iteration in an integration test, you'd just test the results.  If it is helpful to develop the algorithm that way though, go for it.
You are right about the mocks, you aren't really testing a lot.  They can be useful if you want to control some of the inputs though.  Many times I will permute my inputs in exhaustive ways when I have black boxes that I cannot control.  These sorts of tests run too long, though.  I will generally comment them out entirely or partially when they go into source control.

A: I would say that if the container is slow in some way or it has side-effects that mean you cannot read its values without disturbing it, then you should use a mock.
Otherwise, using a mock is a waste of time. Would you use a mocked version of std::vector? I wouldn't; it would be silly.
With your unit testing, if you cannot test all of the internal state of your algorithm through various public parameters, then those states don't actually matter. They can never come up in real use. So as long as you get the correct final answer from your algorithm for each set of input parameters, I would say things are working well.


text:
Q: Why does Pytest perform a nested loop over fixture parameters Using Pytest, I want to write a test function which takes in multiple fixtures as arguments. Each of the fixtures has several parameters.
For example, in test_demo.py is a function test_squared_is_less_than_10 that takes the fixtures, negative_integer and positive_integer as arguments, and then checks that the squared of the fixture parameters is less than 10.
import pytest

@pytest.fixture(params=[-1, -2, -3])
def negative_integer(request):
    return request.param

@pytest.fixture(params=[1, 2, 3])
def positive_integer(request):
    return request.param

def test_squared_is_less_than_10(negative_integer, positive_integer):
    assert negative_integer ** 2 < 10
    assert positive_integer ** 2 < 10

I expect that when I run the pytest command in the terminal, a total of 6 tests should be executed, i.e. [-1, -2, -3] for positive_integer and [1, 2, 3] for negative_integer.
However, pytest seems to executing a nested loop kind of iteration so that 9 tests are executed
i.e. [(-1, 1), (-1, 2), (-1, 3), (-2, 1), (-2, 2), (-2, 3), (-3, 1), (-3, 2), (-3, 3)].
Here is the output when I run pytest -v -k "test_squared_is_less":
test_squared_is_less_than_10[-1-1] PASSED
test_squared_is_less_than_10[-1-2] PASSED
test_squared_is_less_than_10[-1-3] PASSED
test_squared_is_less_than_10[-2-1] PASSED
test_squared_is_less_than_10[-2-2] PASSED
test_squared_is_less_than_10[-2-3] PASSED
test_squared_is_less_than_10[-3-1] PASSED
test_squared_is_less_than_10[-3-2] PASSED
test_squared_is_less_than_10[-3-3] PASSED

This is undesirable, as I only want to carry out 6 tests instead of 9. With a larger number of params (say 20), pytest will execute 400 tests instead of the desired 40 tests, which is a waste of computational time.
How can I deal with this problem.
P.S: I would like to avoid writing two separate tests, such as
test_negative_squared_is_less_than_10(negative_integer) and test_positive_squared_is_less_than_10(positive_integer)

A: You can apply non-cartesian parametrization via the @pytest.mark.parametrize marker. Your code, refactored:
import pytest

neg_params = [-1, -2, -3]

@pytest.fixture(params=neg_params)
def negative_integer(request):
    return request.param

pos_params = [1, 2, 3]

@pytest.fixture(params=pos_params)
def positive_integer(request):
    return request.param

@pytest.mark.parametrize(
    "negative_integer, positive_integer",
    zip(neg_params, pos_params),
    indirect=True
)
def test_squared_is_less_than_10(negative_integer, positive_integer):
    assert negative_integer ** 2 < 10
    assert positive_integer ** 2 < 10


text:
Q: Context Menu is not working in flash player 10.1 I write a flex application. I added some custom menu items in context menu. when I compiled this code using flashplayer 10.0, it works fine and my added context menu items are shown when I Right-Click. But when I compile same code for flashPlayer 10.1, menu items that I added in context menu are not shown when I Right-Click. What should I do to resolve this issue?
I am using sdk 3.5.
Any help or suggestion will be appreciated.
I am doing this;
    private var cm:ContextMenu = new ContextMenu();
    var versionMenu:ContextMenuItem = null;
    var dateMenu:ContextMenuItem = null;
    if(model.appVersion.length > 0)
    {
      versionMenu = new ContextMenuItem(model.appVersion);
    }
    if(model.releaseDate.length > 0)
    {
      dateMenu = new ContextMenuItem(model.releaseDate);
    }

     cm.hideBuiltInItems();
     var cmArray:Array = new Array();
     if(versionMenu != null)
       cmArray.push(versionMenu);
     if(dateMenu != null)
       cmArray.push(dateMenu);
     cm.customItems = cmArray;

Thanks.

A: there is no reason. It works fine for me in flashPlayer 10.1 . Also it is listed as supported in 10.1 here : http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/ui/ContextMenu.html
alert the isSupported property in code to double check (it will most definitely be true).

A: If you are trying to create a context menu for Application then here is the correct code:
<s:Application ... initialize="init();">

    private function init():void
    {
        var versionItem:ContextMenuItem = new ContextMenuItem("Version 1.5.443");
        contextMenu.hideBuiltInItems();
        contextMenu.customItems = [ versionItem ];
    }

</s:Application>


text:
Q: Can't get MS Office mass delpoyment working. Update Not Running? I am trying to mass deploy Office 2016 at work and I am testing it on one machine.
I am using the following scripts and instructions.
https://github.com/OfficeDev/Office-IT-Pro-Deployment-Scripts/blob/master/Office-ProPlus-Deployment/Deploy-OfficeClickToRun/1-ExampleDeployGeneric.ps1
I am able to run the script and I have all my configurations files in place and in the right directories. However after the UAC asks me if I want to run Office 2016 and I say yes, it errors out on my powershell screen as "Update Not Running"
Basically this is what happens after I run the script in powershell.
> Generate-ODTConfigurationCML -Languages AllInUseLanguages -TargetFilePath $targetFilePath | Set-ODTAdd - Version $NULL | Install-OfficeClickToRun

Installing Office Click-To-Run
Waiting for Update to Complete...
Update Not Running

It quits.
If anyone has any clue as to why, or if there are any Microsoft Experts out there that can help out, that would be great. I understand 2016 just came out, but it is debugging and trials like this that make it easier for others.


text:
Q: HTML drop down not dropping down .. Why First I am using Chrome ... If you look at this First jsfiddle the drop down will not drop down.

If I change the width from 400 to 900 then it will work fine see this Second jsfiddle.

I don't understand why CSS and HTML does this to me. So I am looking for a explanation of why.

A: The column-count you use makes the content of the div to be divided into 3 columns, and that division cause the "extra" content to be "displayed" outside your container (which is only 375px wide).
The reason for the 900px (of the container) to fix this is that it gives enough space for the <select> element to render (btw - 800px is enough).

A: You have this css rule in class .topColorTile
column-count: 3;
column-gap: 10px;

If you set width of #column1 by 400px, class .topColorTile will be inherited.
And you also set width of .topColorTile div.topColorCard by 375px, it's wrong here, you can not set with of child node larger than width of parent/column-count.
Sorry for my bad english :D

A: As others have answered, you have this CSS rule on .topColorTile
column-count: 3;
column-gap: 10px;

but also have this rule on div.topColorCard
 width: 375px;

When the parent container is only 400px the div gets broken down into 3 columns.  Since there are no other divs (or elements) inside, the card containing the select uses the entire width (375px as specified in the CSS) with the remaining two columns added next to them but with no content (i.e. invisible)
This makes the select statement to fully show but the overlapping (and invisible) 'columns' prevent the click event to trigger the dropdown action.
Changing the number of columns to 1 would solve the issue (or removing the CSS rule, in this case would be the same)
Setting the width of .topColorCard to a smaller amount (that would fit the parent's 400px) would also do it (i.e. 130px x 3 < 400px)
Making the parent's width to a higher number (like 900px) would also prevent this overlapping.

A:

That's why... float:right
Change it to float:left or adjust width of div's
You have a big mess in your code. Check FreeCodeCamp online tutorial to improve your skills.


text:
Q: How do I get a Chrome Extension PageAction icon to appear in the address bar? I'm trying to build a Chrome Extension that appears as an icon in the address bar which, when clicked, sets contenteditable=true on all elements on the page, and then when clicked again sets them back to contenteditable=false.
However, I'm falling at the first hurdle... The icon isn't even showing up in the address bar.
Here's my manifest file:
 {
  "name": "Caret",
  "version": "1.0",
  "description": "Allows you to edit the content on any webpage",
  "page_action": {
    "default_icon": "icon.png"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["jquery.js", "caret.js"]
    }
  ],
  "permissions" : [
    "tabs"
  ]
}

and here's the caret.js script:
    chrome.browserAction.onClicked.addListener(function(Tab) {

    $("*").attr("contenteditable",true);

});

This is my first attempt at an extension, so it's quite probably a newbie mistake, but I'd really appreciate any help or advice!

A: This is no longer possible as of last release.
Chrome extension page action appearing outside of address bar
https://groups.google.com/a/chromium.org/forum/#!searchin/chromium-extensions/upcoming/chromium-extensions/7As9MKhav5E/dNiZDoSCCQAJ

A: My answer to this other question gives the solution.  FYI, the second code issue noted in that answer is also relevant to your code: You want the icon to appear for all pages, so you should use browser_action, not page_action.  Either will work, but using a page action on every page goes against convention and makes for a less consistent end-user experience.

A: I had a similar problem, here are the steps I followed to solve it:
I altered my manifest.json to include the following:
{
  "background": {
    "scripts": ["background.js"],
    "persistent":false
  },
  "page_action": {
    "default_icon": "logo.png",
    "default_title": "onhover title",
    "default_popup": "popup.html"
  }
}

Then I inserted the following code into my background script:
// When the extension is installed or upgraded ...
    chrome.runtime.onInstalled.addListener(function() {
      // Replace all rules ...
      chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
        // With a new rule ...
        chrome.declarativeContent.onPageChanged.addRules([
          {
            // That fires when on website and has class
            conditions: [
              new chrome.declarativeContent.PageStateMatcher({
                pageUrl: { hostContains: 'myurl', schemes: ['https', 'http'] },
                css: [".cssClass"]
              })
            ],
            // And shows the extension's page action.
            actions: [ new chrome.declarativeContent.ShowPageAction() ]
          }
        ]);
      });
    });

The documentation for this can be found here... https://developer.chrome.com/extensions/declarativeContent

A: Ok, turns out I needed to use chrome.pageAction.show(tab.id);, which meant I needed to get the ID of the current tab, which is achieved with:
chrome.tabs.getSelected(null, function(tab) {

    chrome.pageAction.show(tab.id);

});

BUT it turns out you can't use chrome.tabs within a content script, so I had to switch to using a background page instead.

A: I did this:
chrome.tabs.onUpdated.addListener(function(id, info, tab){
  if (tab.url.toLowerCase().indexOf("contratado.me") > -1){
    chrome.pageAction.show(tab.id);
  }
});


text:
Q: When I do "uuidgen" in Unix how does it generate the ID? When I do "uuidgen" in Unix how does it generate the ID?

A: uuidgen comes from libuuid, which is part of e2fsprogs
The manual page for the e2fsprogs uuid_generate functtion states:

The  uuid  will be generated based on high-quality randomness
  from  /dev/urandom, if available. If it is not available, then
  uuid_generate will use an alternative algorithm which uses the
  current time, the local ethernet MAC address (if available), and random
  data generated using a pseudo-random generator.


text:
Q: dynamically added anchor click doesn't call function in jquery mobile My page fetches string data from local SQL and appends it to data-role='listview' as li using function below(simplified version)
function CreateListview{
   var temp ='
String Here
';
   $("#
-selector").append(temp).listview("refresh");
}

well, it works fine so I binded a click event for the anchor(class='.anchor')
$(document).on('vclick', '.anchor', function(e){
  e.preventDefault();
  alert("ANCHOR CLICKED");
});

OR
$(document).on('vclick', '#ul-selector > a', function(e){
  e.preventDefault();
  alert("ANCHOR CLICKED");
});

OR
$(document).on('vclick', '#ul-selector > li a', function(e){
  e.preventDefault();
  alert("ANCHOR CLICKED");
});

OR even
$(document).on('vclick', 'a', function(e){
  e.preventDefault();
  alert("ANCHOR CLICKED");
});

But nothing works
I double-checked if click event on other elements works by using the function below on dynamically added li and it sometimes works and sometime doesn't.
I don't know why it works randomly,
but I checked that click events are fired on some other dynamically added elements.
$(document).on('vclick', '#ul-selector > li', function(e){
  alert("
 CLICKED");
});

When it comes to binding click function to dynamically added anchors, the function won't be fired..
could it be a bug? or am I writing codes wrong?
Can you give me a working example binding click event to dynamically added anchor?

A: It seems works fine for me.

function CreateListView() {
   var temp ='
String Here
';
   $("#selector").append(temp).listview("refresh");
}

$(document).on('vclick', '.anchor', function(e){
  e.preventDefault();
  alert("ANCHOR CLICKED");
});

$("#createLi").on("vclick", function(){
    CreateListView();
    alert("test");
})

<input id="createLi" type="button" value="create li"/>

Am I missing something?

A: bind the event after you append the html like this
function CreateListview{
   var temp ='
String Here
';
   $("#
-selector").append(temp).listview("refresh");

$("#
-selector > li").on("click",function(){
 alert("
 CLICKED");
});

}

check this fiddle you can apply the same logic here

A: You're not listening to the click event but vclick(???).
$("yourUl").on('click', '.anchor', function(e){
  e.preventDefault();
  alert("ANCHOR CLICKED");
});

A: I found the solution.
Problem: with cordova, 'click' on anchor doesn't fire function even with e.preventDefault(); Rather, 'touchstart' works fine.
Solution: 'click' -> 'touchstart' to work on devices
$(document).on('touchstart', '#anchor-selector', function(){
   alert("touch");
});


text:
Q: Coin Tossing game with Array to hold values I am just learning basics of Javascript but know Java a good amount, I KNOW I AM DOING THIS WRONG, just looking for the correct way to do this.
I am trying to have a number entered into a text field and generate as many random numbers between 1-2 as the text field number specifies. Then store those numbers (A bunch of 1's and 2's) in an array and then cycle through the array with a for loop to count how many Heads or Tails there was, and print it.
Expected output: //Number inputted is 10.
Number of heads = 7 and number of tails = 3
<!DOCTYPE html>

    <title>Coin Tosser</title>

COINTOSSER

        <input type = "text" id ="num">

    <button id = "click" type="button">Start Tossing</button>

A: I've commented where I've made changes and why.
The key points are that since you are counting 2 values, you can just store the count of each value in an index of an array, rather than fill an array with a new value each time one of 2 options happen.
This lets you cut out the counting loop, making your program much more efficient, always try to count as you add rather than add then count at the end.
Also, you need to refresh the rng value each time the method is called, so I moved it into the top of the function.
Give it ago!

<!DOCTYPE html>

    <title>Coin Tosser</title>

COINTOSSER

        <input type = "text" id ="num">

    <button id = "click" type="button">Start Tossing</button>


text:
Q: Proper usage of .includes and .joins I have 3 models
Options:
class Option < ActiveRecord::Base
  attr_accessible :key, :name
  belongs_to :item_options
end

ItemOptions
class ItemOption < ActiveRecord::Base
  # attr_accessible :title, :body
  belongs_to :item
  belongs_to :option
end

and Item:
class Item < ActiveRecord::Base
  has_many :item_options
  has_many :options, :through => :item_options
end

And I need my controller to return all items with their options in JSON format so i'm trying to use .includes but with no luck:
items = Item
  .order('id')
  .where(manufacturer)
  .where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
  :include => :options
)

Result does not contain options but i see in console there are appropriate DB requests. However it does only works if i use :include inside to_json:
items = Item
  .order('id')
  .where(manufacturer)
  .where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
  :include => :options
)

So the first question is what am i doing wrong so that .include does not work?
But i aslo have problem with working code. I need options to be joined with item_options because options just store options name, options group id and so on, when item_options keeps value for defined option for defined item. And so i'm trying to extend my code as follows:
items = Item
  .order('id')
  .where(manufacturer)
  .where('is_active')
render :json => {:data => items.offset(offset), :total => items.count}.to_json(
  :include => {
    :options => {
      :joins => :item_options
    }
  }
)

But still, i receive options not beeing joined with item_options. Why?
Also if i use joins inside optoins do i need to define has_many through in items if they loaded without additional information in item_options?
========== UPDATE:
For now i just replaced an options relation to method in Items model:
item = Item
  .includes(:item_options)
  .find(params[:id])
render :json => item.to_json(:methods => :options)

and in Item model:
has_many :item_options
def options
  self.item_options.select('item_options.value, options.name, options.is_feature, options.root').joins('left join options on options.id = item_options.option_id')
end

Don't know, however, if this solution is optimal.

A: Your calling to_json on a hash and not on the model, and Hash knows nothing about includes or joins.
Try putting your json options on the model
data = items.offset(offset).as_json(include: :options)
render json: {data: data, total: items.count}

Also, I think your Option belongs_to :item_options should be Option has_many :item_options
Using :include within as_json is an instruction to the ActiveModel json serializer telling it to include data from associations in the output JSON.
ActiveModel::Serializers::JSON
(github)
The joins and includes methods are part of ActiveRecord and are used to add join conditions and perform eager loading.
ActiveRecord joins
ActiveRecord includes


text:
Q: Only allow values that are not in the range I'm making a list with emails for a newsletter, the emails are taken directly from the gmail inbox and pasted into the Sheet. However there are some emails i want to black-list from adding to the main column of mails.
I wanted to add the black-listed mails to another column and use requireValueInRange from the DatavalidationBuilder in some way to say "if the value appears in range B then dont be able to add it to range A"
I want to do the opposite of this:
var cell = SpreadsheetApp.getActive().getRange('A1');
var range = SpreadsheetApp.getActive().getRange('B1:B10');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(range).build();
cell.setDataValidation(rule);

A: You can use requireFormulaSatisfied to achieve your goal. Refer the below code.
   function setRule(){
      var rule = SpreadsheetApp.newDataValidation().requireFormulaSatisfied("=NOT(EQ(A1,B1:B10))").build();
       cell.setDataValidation(rule);
     }


text:
Q: Make "unmergeable" commits in a git branch I have already asked a question, but I think it is too complicated, and I have been able to simplify my question enough to warrant a re-write. Please refer to that link if you want to see a real-world example of my problem!
The question is whether it is possible for me to make a special type of git commit on my branch, which is never explicitly merged in future merges of the branch.
The use case is if I have a project that has multiple different makefile configurations (one for each platform) and I want to do development work on multiple of them. So the work will be spread out across the branches (branches being specific to a platform...) and I want to merge together the branches without the merge blowing away the configurations.

A: I guess unless there really is such a feature, I have to just give up on it because Git doesn't support this kind of workflow.
It seems like the "right" way so far is to basically set up cmake or other means of customizing and generating platform specific differences using the same initial seed code (which lives in the source code repository).
I feel like many projects can benefit from having this additional power in the branch, though. Many build systems for small projects can be made a lot more flexible by having a way to easily maintain basic build systems that are whipped up around whatever happens to be available on the given platform.
Meanwhile in my project, I am just going to use shell commands (uname etc) to perform the predication, so I'll no longer try to push this responsibility onto git and leave it on the Makefile.