text:
Q: Не подтягивается переменная с повторного fetch. Запутался в коде. React Беру из API курс валют за 30 дней. Сделал вьібор валют селекторами, куда подтянул данньіе из json, сделал два поля в которьіх подсчитьівается курс одной валютьі относительно другой. Если менять вьіходную валюту, то подтягивается новое отношение из єтого же файла json. Если менять входную, то делается новьій запрос, в котором будут новьіе отношения между валютами. У меня запрос делается, а отношения валют не стают новьіми при смене верхней валютьі.
Вот код App.js. Второй запрос делается на 60 строке, в нем и проблема:
import logo from './logo.svg';
import React, { useEffect, useState } from 'react';
import './App.css';
import CurrencyRow from './CurrencyRow'

var myHeaders = new Headers();
myHeaders.append("apikey", "seNJp91EYSFBx6e6XV00radMdjKULvrl")

var requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers: myHeaders
};

const BASE_URL = 'https://api.apilayer.com/exchangerates_data/timeseries?start_date=2022-09-01&end_date=2022-10-01' //& base=UAH

function App() {
    const [currencyOptions, setCurrencyOptions] = useState([])
    const [fromCurrency, setFromCurrency] = useState()
    const [toCurrency, setToCurrency] = useState()
    const [exchangeRate, setExchangeRate] = useState()
    const [amount, setAmount] = useState(1)
    const [amountInFromCurrency, setAmountInFromCurrency] = useState(true)

    const [rates, setRates] = useState({})
    const [dates, setDates] = useState([])
    const [rateRender, setRateRender] = useState([])

    let toAmount, fromAmount
    if (amountInFromCurrency) {
        fromAmount = amount
        toAmount = amount * exchangeRate
    } else {
        toAmount = amount
        fromAmount = amount / exchangeRate
    }

    useEffect(() => {
        fetch(BASE_URL, requestOptions)
            .then(res => res.json())
            .then(data => {
                const keys = Object.keys(data.rates)
                setDates([...keys])
                setRates(data.rates)
                let names = []
                let values = []
                rateRender.map(item => {
                    names.push(item.name)
                    values.push(item.value)
                })
                setCurrencyOptions([...Object(names)])
                setFromCurrency(data.base)
                setToCurrency(names[0])
                let n = names.indexOf(toCurrency)
                setExchangeRate(values[n])
                console.log(data)
            })
    }, [])

    useEffect(() => {
        //if (fromCurrency != null && toCurrency != null) {
            fetch(`${BASE_URL}&base=${fromCurrency}&sybmols=${toCurrency}`, requestOptions)
                .then(res => res.json())
                .then(data => {
                    const keys = Object.keys(data.rates)
                    setDates([...keys])
                    setRates(data.rates)

                    let names = []
                    let values = []
                    rateRender.map(item => {
                        names.push(item.name)
                        values.push(item.value)
                    })
                    let n = names.indexOf(toCurrency)
                    setExchangeRate(values[n])
                    console.log(data)
                    console.log(fromCurrency, " ", toCurrency, " ", exchangeRate)
                })
        //}
    }, [fromCurrency, toCurrency])

    useEffect(() => {
        if (dates.length && !rateRender.length) {
            getRates(dates[0])
        }
    }, [dates])

    const getRates = (date) => {
        const rateSelect = rates[date];
        const rate = [];
        for (let x in rateSelect) {
            rate.push({
                name: x,
                value: rateSelect[x]
            })
        }
        setRateRender(rate)
    }

    function handleFromAmountChange(e) {
        setAmount(e.target.value)
        setAmountInFromCurrency(true)
    }

    function handleToAmountChange(e) {
        setAmount(e.target.value)
        setAmountInFromCurrency(false)
    }

    return (
        <>

Currency

            <CurrencyRow
                currencyOptions={currencyOptions}
                selectedCurrency={fromCurrency}
                onChangeCurrency={e => setFromCurrency(e.target.value)}
                onChangeAmount={e => handleFromAmountChange(e)}
                amount={fromAmount}
            />

=

            <CurrencyRow
                currencyOptions={currencyOptions}
                selectedCurrency={toCurrency}
                onChangeCurrency={e => setToCurrency(e.target.value)}
                onChangeAmount={e => handleToAmountChange(e)}
                amount={toAmount}
            />
        </>
    );
}

export default App;

Для понятливости вот еще js в котором поля ввода и селекторьі:
import React from 'react'

export default function CurrencyRow(props) {
    const {
        currencyOptions,
        selectedCurrency,
        onChangeCurrency,
        onChangeAmount,
        amount
    } = props
    return (

            <input type="number" value={amount} onChange={onChangeAmount} />
            <select value={selectedCurrency} onChange={onChangeCurrency} >
                {currencyOptions.map(option => (
                    <option key={option} value={option}>{option}</option>
                ))}
            </select>

    )
}

Далее наглядньіе скриншотьі уже на сайте:
Евро к первой валюте из списка:

Евро к любой другой просто для примера работоспособности:

Доллар к первой валюте. Значение как и у евро:

Вот для проверки вьівел в консоль то, что отношение валют вообще не меняется, при том что поступает новьій запрос с другим base.

Вот как вьіглядит наполнение json из API:

Надеюсь хоть что-то понятно расписал. Я в реакте только осваиваюсь и, можно сказать, учился пока писал. Опьіт есть в других язьіках. Не могу просто понять в какой момент в коде и что я должен переприсвоить, чтобьі отношения валют после второго fetch`а стали новьіми.


text:
Q: Connection pooling with SQLServerXADataSource The documentation of the SQLServerXADataSource interface, says that it provides connection pooling and whenever a client is done with the connection, should call the close() method; in this case the connection won't be closed but returned to the pool. I'm trying this, but next time I'm trying to get a connection it says the connection is already closed. How can I implement the connection pooling using this interface?
The class that provides the connection is:
public class ConnectionPool {
   SQLServerXADataSource ds;
   Decoder dec = Base64.getDecoder();
   Connection connection = null;

   public ConnectionPool(InputStream inputStream) throws Exception {
    ds = new SQLServerXADataSource();
    boolean res = Config.load(inputStream);
    if (res) {
        ds.setServerName(Config.SQL_SERVER());
        ds.setDatabaseName(Config.SQL_DB_NAME());
        ds.setIntegratedSecurity(Config.SQL_INTEGRATED_SECURITY());
        ds.setPortNumber(Config.SQL_PORT());
        if (!Config.SQL_INTEGRATED_SECURITY()) {
            ds.setUser(Config.SQL_USERNAME());
            ds.setPassword(new String(dec.decode(Config.SQL_USER_PASSWORD())));
           }
       } else {
           throw new Exception("Failed to load parameters.");
       }
       connection = ds.getConnection();
   }

   public Connection getConnection() throws SQLServerException {
       return this.connection;
   }
}

After creating the object of ConnectionPool (when the user is logged in), I save it as a session attribute so that the servlets can get it when they need it.
Can you please provide an example of taking advantage of this interface to implement connection pooling in a web application? I know I'm not doing it right, but cannot figure out where the problem is.

A: You are creating a connection once, in your constructor. If you close this connection, then this connection is closed (even if the physical handle is returned to the connection pool). Instead your getConnection method should do something like:
public Connection getConnection() throws SQLServerException {
    return ds.getConnection();
}

Or better yet: just give access to the data source itself instead of introducing an unnecessary wrapper.
However as far as I know the SQLServerXADataSource is not a connection pool. It is a factory for XA connections (which you aren't using in your code example), and also extends SQLServerConnectionPoolDataSource (which is a factory for connections to be used by a connection pool, not a connection pool itself).
The Java EE way is to define a JNDI datasource (which could use the SQLServerXADataSource or SQLServerConnectionPoolDataSource as its factory), and then inject (or get) that data source from JNDI.

A: A database might close the connection, and this is not a correct implementation of connection pooling. If you want more information about connection pooling you might read commons-dbcp project, or c3p0. Here the example of datasource that implements connection pooling.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grayscale SVG in Highcharts Is there an option to convert colored charts to grayscale in Highcharts? Have a need to generate SVG that represents grayscaled image. A CSS based option wouldn't help as the SVG is not being used in a browser.

A: you can try to define your own colors http://api.highcharts.com/highcharts#colors


text:
Q: Capacitor, Nuxt, and VueJS - Push Notifications I am new to app building and I started using nuxt and capacitor to develop both an ios and android app. I was having trouble integrating push notifications with my app. I am using the @capacitor/push-notifications package. Is there any direction on how to integrate push notifications with nuxt and capacitor using this package. It would help if someone could walk through this step by step.
This is my nuxt.config.json file
import colors from 'vuetify/es5/util/colors'

export default {
  // Disable server-side rendering (https://go.nuxtjs.dev/ssr-mode)
  ssr: false,

  // Target (https://go.nuxtjs.dev/config-target)
  target: 'static',

  // Global page headers (https://go.nuxtjs.dev/config-head)
  head: {
    titleTemplate: '%s - title',
    title: 'title',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content:"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" },
      { hid: 'description', name: 'description', content: '' },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
  },

  // Global CSS (https://go.nuxtjs.dev/config-css)
  css: [],

  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
    '@/plugins/parse',
    '@/plugins/axios',
    { src: '~plugins/leaflet.js', src: '~plugins/vuesocial.js', ssr: false },
  ],

  // Auto import components (https://go.nuxtjs.dev/config-components)
  components: true,

  // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
  buildModules: [
    // https://go.nuxtjs.dev/eslint
    // '@nuxtjs/eslint-module',
    // https://go.nuxtjs.dev/vuetify
    '@nuxtjs/vuetify',
    '@nuxtjs/moment',
  ],

  // Modules (https://go.nuxtjs.dev/config-modules)
  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    // https://go.nuxtjs.dev/pwa
    '@nuxtjs/pwa',
    '@nuxtjs/toast',
    //nuxt-leaflet
    'nuxt-leaflet',
    ['nuxt-stripe-module', {publishableKey:'...',}],
  ],

  // Axios module configuration (https://go.nuxtjs.dev/config-axios)
  axios: {},

  toast: {
    position: 'bottom-left',
    duration: 3000,
  },

  // Vuetify module configuration (https://go.nuxtjs.dev/config-vuetify)
  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: false,
      themes: {
        dark: {
          primary: colors.blue.darken2,
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.deepOrange.accent4,
          success: colors.green.accent3,
        },
      },
    },
  },

  // Build Configuration (https://go.nuxtjs.dev/config-build)
  build: {
    transpile: ['parse', 'axios'],
  },
}

This is my capacitor.config.json
{
    "appId":"com.undefined.mobile",
    "appName":"undefined",
    "bundledWebRuntime":false,
    "npmClient": "yarn",
    "webDir":"dist",
    "plugins": {
        "SplashScreen": {
          "launchShowDuration": 0
        }
    },
      "cordova": {},
      "server": {
        "iosScheme": "nuxtmobile"
    }
}

This is my Podfile
platform :ios, '13.0'
use_frameworks!

# workaround to avoid Xcode caching of Pods that requires
# Product -> Clean Build Folder after new Cordova plugins installed
# Requires CocoaPods 1.6 or newer
install! 'cocoapods', :disable_input_output_paths => true

def capacitor_pods
  pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
  pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
  pod 'CapacitorClipboard', :path => '../../node_modules/@capacitor/clipboard'
  pod 'CapacitorGeolocation', :path => '../../node_modules/@capacitor/geolocation'
end

target 'App' do
  capacitor_pods
  # Add your Pods here
end


text:
Q: How can I save the value of a String that is ParseInt()ed into an array? Basically, I need to use the Integer.parseInt() function to convert 10 strings into integers which will then be averaged.
Also need to catch any Exceptions but I'm confused as to how to keep the program running so that when the user makes an error the array stays in the x value before the mistake was entered and keeps asking for a correct integer.
Running this right now gives an error since intNum can't be made into a variable, I'm sure it has to do with how i arranged my do and try methods?
public static void main(String[] args) {

    int p=1;
    Scanner scan = new Scanner(System.in);
    int tenNums[] = new int [10];

    for (int x=0; x<10; x++) {

        System.out.println("Enter number: ");
        String stringNum = scan.next();
        do {
            try {
                int intNum = Integer.parseInt(stringNum);
            }
            catch(NumberFormatException e) {
                System.out.println("Wrong Input");
            }
            p = 2;
        } while (p == 1);
        tenNums[x] = intNum;
    }
}

A: You do not need to use p == 1 as a condition for invalid output, you can just break of inner loop when an entered number is valid:
    for (int x=0; x<10; x++) {
        int intNum = -1;
        do {
            System.out.println("Enter number: ");
            String stringNum = scan.next();
            try {
                intNum = Integer.parseInt(stringNum);
                break;
            }
            catch(NumberFormatException e) {
                System.out.println("Wrong Input");
            }
        } while (true);
        tenNums[x] = intNum;
    }


text:
Q: Objective C Calculate Amount of Time Between Now and 3:00 I am making an app to use at school and I want to make a countdown timer to countdown the amount of time between now and the end of school, which for me is 3:00. For example, at 11:15, it will read 3:45.
So far, I have figured out how to make the countdown timer and I have the following code:    countdownTimer.text = [Formatter stringFromDate: [NSDate date]];
This code doesn't actually work yet, but I think it will work if I figure out how to subtract the current time from a set time and then use that value where date is, however I am open to other suggestions on how to approach the problem.

A: You can use NSCalendar method dateBySettingHour:minute:second: to get the NSDate object associated with 3pm today:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *schoolOut = [calendar dateBySettingHour:15 minute:0 second:0 ofDate:now options:0];

There are lots of different ways to get the NSDate object associated with 3pm today, but the above is just one example. You could also use components:fromDate of NSCalendar to extract the NSDateComponents of now, then adjust the hour, minute and second and then create a new NSDate object using dateFromComponents (also a NSCalendar method).
Anyway, once you have a NSDate object that represents your target date/time, you can then use NSDateComponentsFormatter to display the time interval between two dates in a nice format.
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;

NSString *string = [formatter stringFromDate:now toDate:schoolOut];

You can adjust the unitsStyle and zeroFormattingBehavior to adjust the format of the string.


text:
Q: Creating a shared_ptr from an allocator using typedefs? I have some code that I am retrofitting to use an allocator instead of operator new and operator delete directly.  One part of this code's public interface is to return not a bald pointer but a shared_ptr (being constructed from the bald pointer wandering out of new.)
I see in the public contract for an allocator several typedefs named pointer, const_reference, etc.  The idea is instead of referring to types T * directly, I might use pointer, allowing an allocator author to slip in something other than a C pointer.
But I am in turn wrapping the normal pointer in a smart pointer, which wants an honest C pointer (I think.)  If I attempt to change my code over to using the allocator's typedefs, will I run into trouble?  I haven't tried yet (as there is a bit of leg work to do just to try) so I'm asking first..
EDIT: Here's the some of code I want to alter (I didn't include the first time, as it isn't very friendly.)
template<typename Injector, typename Iface, typename Allocator, typename Impl, typename A1>
class New<Injector, Iface, Allocator, Impl, Impl(A1)>: public Binding<Injector> {
public:
  static Impl * provide(Injector const & injector) {
    SAUCE_SHARED_PTR<A1> a1(injector.template provide<A1>());

    return initializer(injector).template construct<Impl, SAUCE_SHARED_PTR<A1> >(a1);
  }

  static void dispose(Injector const & injector, Iface * iface) {
    Impl * impl = static_cast<Impl *>(iface);
    initializer(injector).destroy(impl);
  }
};

// Elsewhere

template<typename Iface>
SAUCE_SHARED_PTR<Iface> provide() const {
  Iface * provided = provideFromBinding<Iface>(
    Module::template bindings<Injector_> );

  SAUCE_SHARED_PTR<Iface> smartPointer;
  smartPointer.reset(provided, deleter);
  return smartPointer;
}

In particular, the construct and destroy template methods called on the result of the initializer(injector) expression currently embed direct uses of new and delete.  I'd like it to use the Allocator instead, and switch them to placement new / explicit destruction, to make something like
template<typename Injector, typename Iface, typename Allocator, typename Impl, typename A1>
class New<Injector, Iface, Allocator, Impl, Impl(A1)>: public Binding<Injector> {
public:
  static Impl * provide(Injector const & injector) {
    SAUCE_SHARED_PTR<A1> a1(injector.template provide<A1>());

    Allocator allocator;
    Impl * impl = allocator.allocate(sizeof(Impl));
    initializer(injector).template construct<Impl, SAUCE_SHARED_PTR<A1> >(impl, a1);
    return impl;
  }

  static void dispose(Injector const & injector, Iface * iface) {
    Allocator allocator;
    Impl * impl = static_cast<Impl *>(iface);
    initializer(injector).destroy(impl);
    allocator.deallocate(impl, sizeof(Impl));
  }
};

The question is, should I try to honor the allocator's typedefs?  It seems like I ought to be or else I'm not using the allocator correctly (never mind that pragmatically speaking nearly all of them will have the "boring" typedef values.)
I can certainly jigger it to return Allocator::pointer instead of Impl *, up until I attempt to shove it into a shared_ptr.  And maybe it just works there too?  That is my question.  Perhaps someone more familiar with the standard than me could say something like "So long as Allocator::pointer quacks like a operator* and you register a custom deleter, you'll be fine."
EDIT: @bdonlan raises the excellent point that a shared_ptr is templated on what would be Allocator::value_type, and not Allocator::pointer.  Instead, it presumably holds a Allocator::value_type * internally.  This seems to answer the question, except an allocator author might choose to implement operator Allocator::value_type * on their Allocator::pointer in such a way that, even when using the converted value, it "all works out" according to some concretely-stated semantic.
Does the standard require allocator authors to do this?
EDIT: See related.

A: shared_ptr (and the other TR1 smart pointers) are defined (ie, take template parameters) in terms of the element type, not the pointer type. As such, if you are using shared_ptr, you cannot substitute your own pointer representation; nor does it make sense to do so in most cases.


text:
Q: Variable value is different from what is programmed Pardon me if I create a fatal programming mistake here. I'm completely new to coding/programming. This is my first time doing OOP.
All comments and suggestions are welcomed
I wanted to create a java GUI where I can move a shape with keyboard arrows and show the coordinates of the shape inside a JTextField
So I created a package move, with 2 java class in it
move.java and second.java
below is move.java
package move;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class Move{

public static void main(String[] args) {

JFrame f = new JFrame();
second s = new second();
f.add(s);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);

    // TODO code application logic here
}

}

And this is Second.java
package move;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
import javax.swing.Timer;

public class second extends JPanel implements ActionListener, KeyListener, MouseListener {

private TextField tfX;
private TextField tfY;
private TextField tfMouseClickX;
private TextField tfMouseClickY;

Timer t = new Timer(10,this);
double x = 50, y = 50, velx = 0, vely = 0;

public second(){
    add(new Label("X Position"));
    tfX = new TextField(10);
    tfX.setEditable(false);
    add(tfX);

    add(new Label("Y Position"));
    tfY = new TextField(10);
    tfY.setEditable(false);
    add(tfY);

    add(new Label("X-Click: "));
    tfMouseClickX = new TextField(10);
    tfMouseClickX.setEditable(false);
    add(tfMouseClickX);
    add(new Label("Y-Click: "));
    tfMouseClickY = new TextField(10);
    tfMouseClickY.setEditable(false);
    add(tfMouseClickY);

    t.start();
    addMouseListener(this);
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.RED);
    g2.fill(new Ellipse2D.Double(x,y,50,50));
}

public void actionPerformed(ActionEvent e){
    repaint();
    x += velx;
    y += vely;
}

    public void keyPressed(KeyEvent e){

    int code = e.getKeyCode();
    if (code == KeyEvent.VK_UP){
        vely = -5;
        velx = 0;
        tfX.setText(Double.toString(x));
        tfY.setText(Double.toString(y));

    }
    else if (code == KeyEvent.VK_DOWN){
        vely = 5;
        velx = 0;
        tfX.setText(Double.toString(x));
        tfY.setText(Double.toString(y));
    }
    else if (code == KeyEvent.VK_LEFT){
        velx = -5;
        vely = 0;
        tfX.setText(Double.toString(x));
        tfY.setText(Double.toString(y));
    }
    else if (code == KeyEvent.VK_RIGHT){
        velx = 5;
        vely = 0;
        tfX.setText(Double.toString(x));
        tfY.setText(Double.toString(y));
    }

}
    public void keyTyped(KeyEvent e){}
    public void keyReleased(KeyEvent e){
    velx = 0;
    vely = 0;
    }

@Override
public void mouseClicked(MouseEvent e) {
    tfMouseClickX.setText(e.getX() + "");
    tfMouseClickY.setText(e.getY() + "");
}

@Override
public void mousePressed(MouseEvent e) {}

@Override
public void mouseReleased(MouseEvent e) {}

@Override
public void mouseEntered(MouseEvent e) {}

@Override
public void mouseExited(MouseEvent e) {}
}

I assigned a value of either 5 or -5 for the coordinates for each action. But on the TextField, it won't show what I programmed, the value keeps on changing too much.

A: You must to hold the tab key pressed then use keyboard arrows to move the shape.


text:
Q: Batch rename program I have a master directory called KARAOKI, in it are folders for artists, and in those folders are all their songs.  I need to insert the folder name in front of each song in that folder so I can load it into a Karaoke master file
For example, the below filename needs to look like:  Elvis Presley - Are You Lonesome Tonight:

*

*Folder Name: Elvis Presley  Title Name: Are You Lonesome Tonight

A: PowerShell:
$Root = 'C:\KARAOKI'
$Songs = Get-ChildItem $Root -File -Recurse
$Songs | Rename-Item -NewName {'{0} - {1}' -f $_.Directory.Name, $_.Name}

Get-CHildItem
Rename-Item
-f format operator

A: @echo off && setlocal enabledelayedexpansion

cd /d "%~dp0" && for /f tokens^=* %%i in ('dir /s /b /a:d')do for /f tokens^=* %%I in ('
dir /a:-d /b "%%~i"')do if not "%%~nxI" == "%~nx0" ren "%%~dpni\%%~nxI" "%%~ni - %%~nxI"

endlocal & goto :EOF
1) Try using delayed expansion for your variables:
setlocal enabledelayedexpansion
2) Go to folder where bat (I suppose) will run/work == Master Drive:\Master-Folder:
cd /d "%~dp0"
3) Use a for loop to running in all sub folder recursively only, folder == %%~i:
for /f tokens^=* %%i in ('dir /s /b /a:d')do...
4) Use a 2nd for in current folder (%%~i) for get/list any file (%%~I) in current folder:
for /f tokens^=* %%i in ('dir /s /b /a:d')do for /f tokens^=* %%I in ('
dir /a:-d /b "%%~i"')do...
5) Use expanded variable %%~nxi,  %%~ni, %~nx0,  %%~dpni\%%~nxI and %%~xi, according to the layout name needs:
%~nx0   ==    Name + Extension file.bat %0         ==    Q1537358.cmd

%%~ni   ==    Name Folder in loop %%i              ==    Are You Lonesome Tonight.ext

%%~nxI  ==    Name + Extension file in loop %%I    ==    Elvis Presley

%%~dpni ==    Drive + Path Name file in loop %%i   ==    D:\KARAOKI

%%~nxI  ==    Name Folder in loop %%I              ==    KARAOKI
6) Use if to compare the current name\extension file is not the same to your current bat/cmd file before try to rename any file:
if not "%%~nxI" == "%~nx0"
7) Use if to compare the current name\extension file is not the same to your current bat/cmd file before try to rename any file:
8) Rename your file with this layout name in loop variable expanded:
ren "%%~dpni\%%~nxI" "%%~ni - %%~nxI"
ren "D:\KARAOKI\Elvis Presley\Are You Lonesome Tonight.ext" "Elvis Presley - Are You Lonesome Tonight.ext"

Obs.: This presuming that you will to save this bat file and run them in the same Drive:\Folder where your master directory \KARAOKI is/are...
C:\KARAOKI or D:\KARAOKI or E:\KARAOKI...
For command line help, you can use /?:
Ren /?, For /?,CD /?, Setlocal /?, Endlocal /?, Goto /?, Setlocal /?, Endlocal /?, if /?
On the internet, you can get more help on:

*

*Cd

*Dir

*Ren

*For /f

*Setlocal

*Endlocal

*Goto :EOF

*EnableDelayedExpansion

*If, Else If, Else, If Defined, Errorlevel ...
So sorry my limited English

A: For simple renaming (if it only depends on the name of the file, and maybe some number/letters sequence) I use a simple old but nice freeware software called "Lupas Rename 2000". Since this needs to navigate also to the parent folder to get the name I am not sure It will work in your case. Anyways, you can find it here: http://rename.lupasfreeware.org/download.php
For your problem, I guess you need more elaborated tools. The one from Keith Miller seems quite clean and effective if you have access to PowerShell.


text:
Q: how to create your own custom ngram filter in solr I want to create a custom filter with which i will be able to create ngrams of a query string according to my needs..
How can we create a custom ngram filter for solr-4.10 ???

A: Depending on your need you can either develop a new filter from scratch, or you can start from the existing NGramFilter and modify it to suit your needs. The existing NGram and Shingle filters should however be able to do most of what is considered NGrams.


text:
Q: Member was not declared in base class template The codes comprises 1 header file and 1 source file. I have cut the irrelevent codes and still maintain the compilation error.
Huffman.h
#ifndef HUFFMAN
#define HUFFMAN
template<int size>
class Huffman{
protected:
    int code_len[size];
    int code[size];
    void genCode(){
    }
};
template<int size>
class HuffmanEncode :public Huffman<size>{
public:
    void f(){
        for (int i = 0; i < size; i++){
            code_len[i] = 0;
        }
    }
};
#endif

main.cpp
#include"Huffman.h"
int main()
{
    HuffmanEncode<256> h;
}

The member variable code_len is defined in the base class. I don't know why it said code_len is undefined.

A: This is a special case for templates. The problem is that the nondependent name code_len won't be looked up in the scope of dependent base class Huffman (which depends on template parameter size).
You could make the name code_len dependent, then it will be looked up only at the time of instantiation; at that time the template argument has been known and the base class has been instantiated, then the name code_len could be found at the scope of base class (like non-template base class). e.g.
this->code_len[i] = 0;

or
Huffman<size>::code_len[i] = 0;


text:
Q: How do I apply an ordering in place? I have an array, e.g. a = [a, b, c, d]. I also have an ordering indicating the indexes of this array, e.g. [2, 0, 3, 1]. Applying the ordering would result in [c, a, d, b]
Explanation:
a            [a, b, c, d]
current_idx: [0, 1, 2, 3]
target_idx:  [2, 0, 3, 1]
result:      [c, a, d, b]

How do you apply the order of target_idx to a in place (without creating a new a)?
Is there a name for such a sorting algorithm? I did not find anything when searching for "applying order to array"


text:
Q: Connecting to Aurora MySQL Serverless with Node I'm trying to connect to my Aurora Serverless MySQL DB cluster using the mysql module, but my connection always times out.
const mysql = require('mysql');

//create connection
const db = mysql.createConnection({

    host     : 'database endpoint',
    user     : 'root',
    password : 'pass',
    database : 'testdb'

});

//connect
db.connect((err) => {
    if(err){
        throw err;
        console.log('connection failed');
    }
    console.log('mysql connected...');
})
db.end();

My cluster doesn't have a public IP address so I'm trying to use the endpoint.  I've successfully connected to the db using Cloud9, but I can't connect using node.  I must be missing something.

A: Aurora Serverless uses an internal AWS networking setup that currently only supports connections from inside a VPC, and it must be the same VPC where the serverless cluster is deployed.

Q: How do I connect to an Aurora Serverless DB cluster?
You access an Aurora Serverless DB cluster from within a client application runing in the same Amazon Virtual Private Cloud (VPC). You can't give an Aurora Serverless DB cluster a public IP address.
https://aws.amazon.com/rds/aurora/faqs/#serverless

This same limitation applies to Amazon EFS, for architecturally similar reasons.  You can work around the limitation in EFS, and the same workaround could be used for Aurora Serverless, but you'd need to disable the health checks entirely since those health checking connections would keep the instance alive all the time.  Exposing a database to the Internet is a practice best avoided.
You could also use some VPN solutions.   They would need to be instance-based and would probably need to use NAT to masquerade the client address behind the VPN instance's internal address -- that's effectively what the proxy workaround mentioned above does, but at a different OSI layer.


text:
Q: Windows Phone 8 - List Picker two level selection I am building a Video Application where each video has many resolutions
The video list is bound to ListPicker, but when the user selects a video I have to make him select the resolution options. (240, 360, 480)
Example:
Consider we have: Celebrity Video, National Video, Sport Video. They are listed like:

Now when the user selects a video I have to make him choose on which resolution he wants to play the video. Like a ListPicker inside the main ListPicker
I don't know how to approach that.
Any help is much appreciated

A: if you have only one list picker in the screen,you can use another list picker below your first list picker and use the selected event of the first list picker to bind the visibility to the second list picker( which contains the resolutions.)
on page loads it only contains first list picker and once the item is selected in the first list picker, the second list picker kicks in( visibility is made to visible ) where the user is allowed to select the resolutions. hope this helps.


text:
Q: Json get graph api permissions Not working code:
$izincikcik = file_get_contents('https://graph.facebook.com/me/permissions?access_token=YOURTOKENCODE');
$json = json_decode($izincikcik, true);
$izinvarmi = $json["data"]["publish_stream"];
echo "$izinvarmi";


text:
Q: Haskell: do notation and return in Monads Suppose I have following code
do {x <- (Just 3); y <- (Just 5); return (x:y:[])}

Which outputs Just [3,5]
How does haskell know that output value should be in Maybe monad? I mean return could output [[3, 5]].

A: do {x <- (Just 3); y <- (Just 5); return (x:y:[])}

desugars to
Just 3 >>= \x -> Just 5 >>= \y -> return $ x:y:[]

Since the type of >>= is Monad m => m a -> (a -> m b) -> m b and per argument Just 3 (alternatively Just 5) we have m ~ Maybe, the return type of the expression must be some Maybe type.

There is a possibility to make this return [[3, 5]] using something called natural transformations from category theory. Because there exists a natural transformation from Maybe a to [a], namely
alpha :: Maybe a -> [a]
alpha Nothing  = []
alpha (Just a) = [a]

we have that your desired function is simply the natural transformation applied to the result:
alpha (Just 3 >>= \x -> Just 5 >>= \y -> return $ x:y:[])
-- returns [[3, 5]]

Since this is a natural transformation, you can also apply alpha first and your function second:
alpha (Just 3) >>= \x -> alpha (Just 5) >>= \y -> return $ x:y:[]
-- returns [[3, 5]]

As @duplode pointed out, you can find alpha in the package Data.Maybe as maybeToList.


text:
Q: Can someone explain how to calculate the third order partial derivative of $f.$ $f(x,y)=\sin(xy).$ I calculated that $ \dfrac{\partial^2f}{\partial x\,\partial y}=\dfrac{\partial^2f}{\partial y\,\partial x}=\cos(xy)-xy\sin(xy)$.
I also calculated $$ \frac{\partial^3f}{\partial x^2\partial y}= -2y\sin(xy)-xy^2\cos(xy)$$ and  $$\frac{\partial^3f}{\partial y^2\partial x}=-2x\sin(xy)-x^2y\cos(xy).$$
However I am not sure whether this is the correct method to calculate the third order partial derivative because $$ \frac{\partial^3f}{\partial x^2\partial y} \neq \frac{\partial^3f}{\partial y^2\partial x}.$$
Can someone explain how to calculate the third order partial derivative of $f.$

A: Define $g(x,y) = \dfrac{\partial^2 f}{\partial x \,\partial y}$.
Generally $\dfrac{\partial g}{\partial x} \neq \dfrac{\partial g}{\partial y}$.
By the way if you exchange the roles of $x$ and $y$, you get exactly the same as is to be expected from the form of $f$.

A: It will usually be the case that $\dfrac{\partial^3f}{\partial x^2 \, \partial y} \neq \dfrac{\partial^3f}{\partial y^2 \, \partial x}$.  For this particular function, $f(x,y)=\sin(xy)$, the variables $x$ and $y$ play symmetrical roles.  A consequence is that $\dfrac{\partial^3f}{\partial x^2 \, \partial y}$ will differ from $\dfrac{\partial^3f}{\partial y^2 \, \partial x}$ only in that $x$ and $y$ get interchanged.


text:
Q: Using a non-default attribute in path helpers, instead of :id What I have
I now have a route like
get 'book/:id' => 'books#show', as: :book

The code to create that URL is:
book_path @book

In the controller:
@book = Book.find(params[:id])

So far so good. Now, this id is obviously the internal ActiveRecord or database primary key.
What I want
Instead, I would (in this ficticious example) use the ISBN instead. I could do this like so:
get 'book/:isbn' => 'books#show', as: :book
book_path(isbn: @book.isbn)
@book = Book.find_by(isbn: params[:isbn])

This is a bit verbose; I want the convention "isbn" for this model in the whole application, and nobody should need to care about it, ever. So, I want my 3 lines to look like this:
get 'book/:isbn' => 'books#show', as: :book
book_path @book    # (!)
@book = Book.find(params[:isbn])    # (!)

Is it possible to configure the route so that my wish comes true? Obviously, this should automatically work everywhere, at the very least for GET requests where the user sees the ISBN in the URL.
In case it matters, the #isbn attribute is not a primary key in the usual sense, but it is guaranteed that there is only ever one record with a particular ISBN in the table. So at least this part of the Primary Key contract is fulfilled.

A: To override the Rails default :id parameter, you can use to_param method:
class Book < ActiveRecord::Base
  def to_param  # overridden
    isbn
  end
end

And in controller:
book = Book.find_by(isbn: '123456')

If you don't have any problem with using any gem for it, then I suggest you should give a look to friendly_id Gem. This does a good job in such case.

A: In your routes.rb, use match to match /book/:isbn to book#show
match '/book/:isbn' => 'book#show', via: :get, as: :show_book

In your book.rb, you can override the find method in order find based on isbn instead of id. Something along the lines of:
def self.find(*args)
    c = Book.select("id").find_by(name: args[0])
    args[0] = c.id
    super(args)
end

This will first find by isbn and then using the id, it will call the original find method. (I have not test this, you will have to modify it to make it work with multiple isbns)
But I am not sure if this is recommended and what caveats it will present.
Instead, why don't you use find_by_isbn[params[:isbn]]? It is more readable than find_by(:isbn, params[:isbn]).


text:
Q: Custom API responses I am currently trying to create an API handler that will ensure that all my requests follow the same template using express in Node JS. So I have defined the structure of the response and registered it as middleware in my express application. I am however unable to get the responses to work.
I have tried importing express into the external class for it to use the res parameter for the middleware. I have also tried it without. I have tried expressing it with middleware parameters such as (req, res, next) which didn't work either. So I am unsure what to try next.
The external handler is as follows:
exports.success = (message, results, statusCode) => {
    return {
        message,
        error: false,
        code: statusCode,
        results
    };
};

I however tried the following as well which didn't work:
exports.success = (message, results, statusCode) => {
    return res.json({
       message,
       error: false,
       code: statusCode,
       results
   });
};

I tried this as well which didn't work:
exports.success = (message, results, statusCode) => {
    return (req, res, next) => {
        res.json({
            message,
            error: false,
            code: statusCode,
            results
        });
        next();
    }
};

I have implemented it in the middleware as follows:
this.app.use((req, res, next) => {
    res.success = responseHandler.success;
    next();
});

Is it not possible to implement what I am trying (which I doubt)? I have a feeling I am just returning the wrong thing but I am not sure what it is.

A: I think you should be able to get this working, I've tested a simple version of what you're trying to achieve.
I've used a bind() call to ensure the context is correct for the success() call, also we'll use the function declaration rather than an arrow function in the response-handler module for the same reason.
index.js
const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')
const responseHandler = require('./response-handler.js')

app.use(bodyParser.json());

app.use((req, res, next) => {
    res.success = responseHandler.success.bind(res);
    next();
});

app.get('/success', function(req,res,error) {
    res.success("Success - yay!!", { foo: 'bar' }, 418);
})

app.listen(port);
console.log(`Serving at http://localhost:${port}`);

response-handler.js
exports.success = function(message, results, statusCode) {
    this.json({
        message,
        error: false,
        code: statusCode,
        results
    });
};


text:
Q: Access CSS fonts from Android 'Assets' folder I'm trying to change the font of web pages loaded in to a Browser app developed for Android. Currently my custom font is hosted in a URL & I access the font from there by injecting a JavaScript to the page to change the style sheet (CSS) font face.
Here is the current code:
var css = '@font-face {font-family: "dhanika"; src: url(http://www.sample.lk/DhanikaWeb.ttf);} si {font-family: "dhanika"}';
var style = document.getElementsByTagName("style")[0];
style.appendChild(document.createTextNode(css));

This code works perfectly. But it takes some time to load the font from the URL. And also it is not good to load the font each time since it may incur data charges.
Therefore I wanna know weather there is a method to access my custom font from the JavaScript, if I place my font in my app's 'Assets' folder. Glad if anyone can provide the code.
Any help is appreciated!

A: From what I know about Android and @font-face, Android currently chokes on the local() declaration. The best method for using @font-face with all browsers is to use double declarations. Example
@font-face { font-family:'fontName'; src:url('fontName.eot'); font-weight:normal; font-style:normal; }
@font-face { font-family:'fontName'; src:url(//:) format('no404'), url('fontName.woff') format('woff'), url('fontName.ttf') format('truetype'), url('fontName.svg') format('svg'); font-weight:normal; font-style:normal; }

The Easiest way to do this is to use FontSquirrel's @font-face generator


text:
Q: Как отправить сообщение всем слушателям RabbitMQ, Spring boot Отправка:
@Service
public class ProducerImp implements Producer {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Value("${jsa.rabbitmq.exchange}")
    private String exchange;

    @Value("${jsa.rabbitmq.routingkey}")
    private String routingKey;

    @Override
    public void produceMsg(MessageDTO msg) {
        amqpTemplate.convertAndSend(exchange, routingKey, msg);
        System.out.println("Send msg = " + msg);
    }
}

слушатель (Остальные такие же):
@Component
public class SubscribeServiceImpl {
    @RabbitListener(queues="jsa.queue")
    public void recievedMessage(MessageDTO msg) {
        System.out.println("Recieved Message: " + msg.getMessage());
    }

}

Проблема в том что сообщение приходит только одному из слушателей. Как сделать так чтоб приходила всем?

A: Если все слушатели подписаны на одну и ту же очередь, то сообщение обработает только один слушатель, который первым получил сообщение.
Вы можете создать несколько очередей (для каждого из слушателей) и посылать сообщение во все очереди сразу привязав их к одному Exchange и RoutingKey.
Подробней тут


text:
Q: How to create such custom button? How can I create a Button with a custom touch area?
I want to create curved Buttons like the ones below:

But only the area under the curve should be clickable, so simple ImageButtons won't work since the hitbox is rectangular.
1pic. how it works with ImageButtons
2pic. one of the versions as have to be

A: Views are rectangular, by nature.
So, simply put a background image in the container Layout and lay your (transparent) ImageViews or TextViews (without any image or text inside) over it.
And react to their click listener/s.
This is the basic idea:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rise_call_bg"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        >
        <TextView
            android:id="@+id/txtLeft"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
        <TextView
            android:id="@+id/txtMidLeft"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
        <TextView
            android:id="@+id/txtMidRite"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
        <TextView
            android:id="@+id/txtRite"
            android:layout_height="100dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:clickable="true"
        />
    </LinearLayout>
</RelativeLayout>

Which results in something like this:

Each TextView is clickable.
So, just add the click listener/s (a centralized one or individual ones - you choose), and it's done.

The user will think the Buttons are what s/he sees: the drawn text underneath the TextViews.

Note: I selected all the TextViews, only to make them visible at design time.
They'll be completely transparent at runtime.
You may want to rise the height a bit, say up to 120dp.

A: Try to use this solution.
The core idea is to detect whether touch in bitmap or not.
https://stackoverflow.com/a/22325218/1979882

A: Ok, I've solved that porblem by one ImageView and onTouchListener. I've calculated the formula for each button-zone and cross-checked the coordinates of touching view.
Here the code for Check and Fold buttons:
 public boolean onTouch(View v, MotionEvent event) {
    x = event.getX();
    y = event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: // нажатие
            if (y > 0.98 * x +75) {
                Log.d("TEST", x+" __FOLD__ "+y);
                img.setBackgroundResource(R.drawable.fold_all);
            } else
            if(y > -0.98 * (x-1200)){
                Log.d("TEST", x+" __CHECK__ "+y);
                img.setBackgroundResource(R.drawable.check_all);
            } else {
                Log.d("TEST", x+" __NOTHING__ "+y);
            }
            break;
        case MotionEvent.ACTION_MOVE: // движение
            break;
        case MotionEvent.ACTION_UP: // отпускание
        case MotionEvent.ACTION_CANCEL:
            img.setBackgroundResource(R.drawable.all);
            break;
    }
  return true;
}

Sorry for my english.


text:
Q: How to dynamically render  or  in Vue depending on whether the link is exrternal or internal? <template>
  <component
    :is="type === 'internal' ? 'router-link' : 'a'"
    :to="type === 'internal' ? link : null"
    :href="type !== 'internal' ? link : null"
  >
    <slot />
  </component>
</template>

Above is a Vue component where it will render a link. I have stripped out anything not relevant to the problem (I.e. rel, target, class, etc.).
Understanding - My understanding of Vue Router is that <router-link to="/about">About</router-link> and About will both render asAbout in the DOM, with a difference being the <router-link> version will give the link the SPA functionality (I.e. doesn't load a new page, it dynamically renders a component).
Expected - When type="internal", it will render the <router-link> version. When type="external", it will render the  version.
<site-link type="external" link="https://stackoverflow.com">Stack Overflow</site-link>

Will render

Stack Overflow

<site-link type="internal" link="/about">About</site-link>

Will render

<router-link to="/about">About</router-link>

Which is then handle by VueRouter to render

About

Actual - When type="internal", a  with no href rendered in the DOM. When type="external", it renders as expected.
<site-link type="external" link="https://stackoverflow.com">Stack Overflow</site-link>

Will render

Stack Overflow

<site-link type="internal" link="/about">About</site-link>

Will render

<router-link to="/about">About</router-link>

Which is then handle by VueRouter to render

About

Any ideas how I can achieve what I want?

A: The better and cleaner approach:
  <router-link v-if="type === 'internal' :to="link">
    <slot />
  </router-link>
   <slot />

You can use v-if in root element so it solves you the case
Or may be you just missed path part?
  <component
    :is="type === 'internal' ? 'router-link' : 'a'"
    :to="type === 'internal' ? { path: link } : null"
    :href="type !== 'internal' ? link : null"
  >
    <slot />
  </component>

A:
...with a difference being the <router-link> version will give the link the SPA functionality (I.e. doesn't load a new page, it dynamically renders a component).

By not loading a new page, I suppose you mean it does not reload the page. And yes, it doesn't because the onclick handler actually gets assigned to a function that does a preventDefault (preventing page redirection) while pushing a new entry into the history stack.
If you take a look at the API reference, the most noticeable thing <router-link> does for you is it toggles between the active-classes depending on the active/current route.
So, that being said, you could do your dynamic nchor rendering inside the default slot via the v-slot; because at this point, the href slot prop would have been a resolved URL which you can then safely bind to the DOM href attribute.

Edit
Added an example (untested).
<router-link
  :to="link"
  v-slot="{ href, route, navigate, isActive, isExactActive }">

    <slot></slot>

</router-link>

Where the customNavigate handler could be something like:
{
  methods: {
    customNavigate(navigate) {
      if (this.type === 'internal') {
        navigate();
        return false;
      }
    }
  }
}

You can basically add any attributes on the in-component anchor tag based on the slot props, like navigating in certain ways, adding special classes, depending on your use case.

A: The official documentation includes an example of how to do this now.

*

*Extending RouterLink
Their approach is to create a custom template that handles external links.


text:
Q: Tracking problem with EF Core 3 and Automapper I've an problem when using .AttachRange() with a list of entities mapped from DTO's. This code worked with the previous version of EF Core. There is an issue about this on GitHub - Entity already tracked exception for entity with multiple references to same navigation property #20116
.AttachRange() throws an error:
The instance of entity type 'School' cannot be tracked because another instance with the same key value for {'SchoolId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

I know how to fix this example case but if you have a lot of FK properties and for example a list of entities and those also have a lot of FK properties then it will be difficult.
Has anyone figured out how to do this properly?
public class School
{
    public int SchoolId { get; set; }

    public string Name { get; set; }
}

public class Student
{
    public int StudentId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public School School { get; set; }
}

var studentsDtos = new List<StudentDTO>
                {
                    new StudentDTO
                    {
                        FirstName = "FirstName 1",
                        LastName = "LastName 1",
                        School = new SchoolDTO
                        {
                            SchoolId = 1
                        }
                    },
                    new StudentDTO
                    {
                        FirstName = "FirstName 2",
                        LastName = "LastName 2",
                        School = new SchoolDTO
                        {
                            SchoolId = 1
                        }
                    }
                };

                var students = mapper.Map<List<Student>>(studentsDtos);

                db.Students.AttachRange(students);

                db.SaveChanges();


text:
Q: Android VOIP Encryption I have thesis to do this year. I want to create an android VOIP application. But I need it to be secure. I intent to use the SIP. Maybe I wasn't searching good enough but I have to find some information fast. Do you know some way to encrypt the voice using SIP? A few times I found some information about ZRTP but the information wasn't really useful. Any help would be useful. I have three months to finish the project (but I can't work all the time because I go to school).

A: Signalling and Media are to be managed differently to build a secure voip application.

*

*Signaling - SIP is a signaling protocol and carried over UDP [usually]. Adding a layer of protection to this can be done by using TLS as the transport to make the message exchange secure. The SIP packets are all encrypted and makes it secure over the transmission.

*RTP - Usually the media is carried as RTP. But the secure flavor is the SRTP and in that ZRTP is a particular mechanism to handle encryption of the packets.
Coming to building the VoIP Application, i would recommend with going with a stack like PJSIP or numerous other options and this should help you have the prototype faster and understand the concepts better. Good luck.


text:
Q: How can I find EPSG when it's not obvious from the .PRJ file? Using Geoserver, I'm trying to get the correct projection for a map layer that is provided by the State of Idaho. I've tried looking up the EPSG code from http://prj2epsg.org/search. However, the search results throws an error.
Here is the location of the data - https://fishandgame.idaho.gov/ifwis/portal/opendata/controlled-hunt-areas-2015-elk
Here are the results of the .prj file
PROJCS["NAD_1983_Transverse_Mercator",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",2500000.0],PARAMETER["False_Northing",1200000.0],PARAMETER["Central_Meridian",-114.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",42.0],UNIT["Meter",1.0]]

I found this page that should help, but I don't know what it all means.
https://www.idwr.idaho.gov/GIS/IDTM/

A: You can not find an EPSG code, because the data provider does not use any of the CRS registered at EPSG for Idaho.
Alternatively, you can run gdalsrsinfo on the .prj file to get the proj.4 string:
+proj=tmerc +lat_0=42 +lon_0=-114 +k=0.9996 +x_0=2500000 +y_0=1200000 +ellps=GRS80 +units=m +no_defs

You would have to create a custom CRS from that, or use ogr2ogr to reproject the data to a CRS listed by the EPSG.

UPDATE
The projection is now available in GDAL 2.3.1 as EPSG:102605 (although it is really an ESRI projection code). You can get it from gisinternals or the OSGEO4W gdal-dev package, but not yet with OSGEO4W QGIS builds (which is still at GDAL 2.2.4) or Ubuntugis. Debian testing and Ubuntu cosmic have it, older versions not.
The projection is now also included in the EPSG registry as EPSG:8826 NAD83 / Idaho Transverse Mercator. It will take some time until it finds its way in the GDAL release.

A: If you google the whole content of the prj file, you usually end up on the description page for that projection on http://www.spatialreference.org
In your case, it comes to this, showing that there is no EPSG code for that particular projection: http://www.spatialreference.org/ref/sr-org/idaho-tranverse-mercator/


text:
Q: Image not displaying in JTable (Java Swing) Hi I have created the following code.  The problem is the image is not displaying in the JTable column.
I extend the DefaultTableModel and override the method getColumnClass.  It was suggested this was one way to do it.  Any clues? the code is below.
//package javaapplication12;

import javax.swing.*;

public class NewJFrame2 extends javax.swing.JFrame {

    /** Creates new form NewJFrame */
    public NewJFrame2() {
        initComponents();
    }

    public class imageTableModel extends javax.swing.table.DefaultTableModel

   {
       imageTableModel(Object[][] data, Object[] columnNames)
       {
           super(data,columnNames);
       }

@Override
        public Class getColumnClass(int column)
         {

            if (column == 0)
         {

                return ImageIcon.class;
        }
            return Object.class;
    // other code; default to Object.class
       }
    }

    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new imageTableModel(
            new Object [][] {
                {new ImageIcon("simply.jpg"), "pp"},

            },
            new String [] {
                "image", "name"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration

}

A: This is the correct way to do it, but your jpg isn't being found correctly.  Change your code to look it up as a resource URL and it should find it correctly.  The following change worked perfectly on my machine:
    jTable1.setModel(new imageTableModel(
        new Object [][] {
            {new ImageIcon(getClass().getClassLoader().getResource("simply.jpg")), "pp"},

        },
        new String [] {
            "image", "name"
        }
    ));


text:
Q: mojjara JSF 2.0 vs myfaces behaving differently I am working on web application upgrade which involves below two upgrades
JSF 1.0 -> 2.x ,
Webspehere 7.0 -> 8.5
After upgrade if I switch to  myfaces libs provided in WAS8.5 plugins, certain elements in UI tend to break. If I keep the implementaion to mojjara JSF2.0 libs, it seems to work fine.
One of the errors I am getting when I use myFaces 2.0 is
java.lang.IllegalArgumentException: Component javax.faces.component.UIInput is no javax.faces.component.html.HtmlInputText

This happened because <inputText> which is of type javax.faces.component.html.HtmlInputText tag had a binding to a model which returned new UIInput(); in getter method of model. (I know this is a bad code. But it's existing and was written to initialize text field with default values)
I can understand why this should not work. Because HtmlInputText is a subClass of UIInput. And when we try to bind object of Parent class where Child class is expected, this error is thrown. This is similar to when we try to cast a Parent Object to Child reference
Now if this is the case, then my question is how same code works with Mojjara JSF implementation. If I switch to Mojjara, I don't face this issue, which is surprising. Because I expected this issue with this also, since code violates general Parent Child Class rules.

A: Check this page - JavaServer Faces migration - it describes some migration details. In particular, if you use JWL:

You must update widget library to version 3.1.6 or higher to enable
  compatibility with the changes in the JSF 2.0 implementation. Obtain a
  compatible version of JWL by upgrading IBM® Rational® Application
  Developer for WebSphere to 7.5.5.2 or later or installing IBM Rational
  Application Developer for WebSphere V8.0 and later.


text:
Q: Django url and request GET in template I am using "url" tag in my template and everything works fine, except I cant capture anything thats behind it. Since I have multiple filters on that page, that are kept via GET request in the url, I need to be able to apend them to it. What happens is, that when I select one filter url will change to some/url/?f=1, then when I select another filter previous filter will get overriden, since the url is just some/url without request.
Here is a piece from urls.py:
url('^products/$', products_list, name = 'products_list'),

Is there anyway to modify it so the url tag will capture the GET request? Or do I need to create a filter which will add it there?
Any help is appreciated
Regards

A: There is no way to generate a query string using the url tag. If you need to add a query string to the output then do it manually, e.g. {% url foo bar %}?var={{ val|urlencode }}.


text:
Q: c program.data validation. convert char to integer I'm writing a program which allows user to enter alphanumeric strings and validate their input based on the options available.when I run my code below, it always print option is invalid even though I have entered an option within the range.Can anyone help me with this?Any help will be aprreciated.
#include<stdio.h>
#include<ctype.h>
#include<string.h>

int main (void){

char option;

do{
printf("\n\n----------------------------------------------------\n");
printf("Main Menu\n");
printf("----------------------------------------------------\n");
printf("1. Add Record\n");
printf("2. Delete record\n");
printf("3. List Record\n");
printf("4. Exit\n");
printf("----------------------------------------------------\n");

printf("Enter your option:");
scanf("%c",&option);

if(isdigit(option)){
switch(option){

    case 1:
    add();
    break;

    case 2:
    del();
    break;

    case 3:
    listrec();
    break;

    case 4:
    return 0;

    default:
    printf("The number that you have entered is invalid.Please enter a new option\n");
    break;

}

    else{
    printf("The option that you have entered is invalid.Please enter a new option\n");
    }

}while(option!=4);
return 0;
}

A: Besides using 1 instead of '1' (you need to compare the character with the character, not with a number), there is another problem - you don't get the carriage return from the input, and this makes the input fail on the second pass. See below for a possible solution:
#include<stdio.h>
#include<ctype.h>
#include<string.h>

int main (void){

char option;

do {
  printf("\n\n----------------------------------------------------\n");
  printf("Main Menu\n");
  printf("----------------------------------------------------\n");
  printf("1. Add Record\n");
  printf("2. Delete record\n");
  printf("3. List Record\n");
  printf("4. Exit\n");
  printf("----------------------------------------------------\n");

  printf("Enter your option:");

  if(scanf("%c",&option)==1) {

    if(isdigit(option)){
      printf("you entered %c\n", option);
      switch(option){

      case '1':
        printf("adding\n");
        break;

      case '2':
        printf("deleting\n");
        break;

      case '3':
        printf("listing\n");
        break;

      case '4':
        return 0;

      default:
        printf("The number that you have entered is invalid.\nPlease enter a new option:\n");
        break;

      }

    }
    else {
      printf("you entered not a digit: %c\n", option);
      printf("The number that you have entered is invalid.\nPlease enter a new option:\n");
    }

    // empty the input buffer:
    while(getchar()!='\n');

  }

  }

} while(option!=4);
return 0;
}

A few things to note:

*

*There was a } missing in your code sample given - between the end of the switch and the else

*I check that scanf returns a value of 1 (valid conversion) - per Nisse's comment

*I empty the input buffer after the if by reading until I get an EOL (which stays in the buffer after the scanf). This ensures that the next character read is the next character after the carriage return, and not the carriage return itself.

*Miscellaneous clean-up...

A: The integer value of a character object that contains a digit is equal to the internal representation of the corresponding character that denotes the digit. For example if the ASCII coding is used then for example '1' has internal representation equal to 49. So you had to write
case 49:

instead of
case 1:

Change case labels the following way that they would not depend on the internal representation of character digits.
    case '1':
    add();
    break;

    case '2':
    del();
    break;

    case '3':
    listrec();
    break;

    case '4':
    return 0;

    default:
    printf("The number that you have entered is invalid.Please enter a new option\n");
    break;

}

    else{
    printf("The option that you have entered is invalid.Please enter a new option\n");
    }

}while(option!='4');


text:
Q: Confused about Release/Debug folders in Visual Studio 2010 I am working on ASP.Net MVC 3. When I build it in debug mode, all files go to the bin folder. But I have seen people with "Debug" & "Release" folders inside the bin folder. Why don't I have that in my bin folder?
How do I have Debug & Release folders in my bin folder? Or should I really have them?
Then I saw that there are Debug & Release folders inside \obj\ folder created when using "Deployment Wizard". What is the different between these folders and the ones under "bin" folder? Are these both same?
Please help.

A: Here is a good thread for what the /obj folder is for and how it's different from the /bin folder
As for why you don't have Debug/Release folders in your /bin folder:
-Under your project properties go to the Build tab
-From the Configuration on top choose Debug or Release
-For each configuration you can set the Output Path at the bottom of the window. For Debug use bin\Debug and do the same for Release.
I'm not sure why VS doesn't do this automatically -- it did it for my other projects in the same solution.

A:
Release Mode
When an assembly is built in release mode, the compiler performs all
  available optimisations to ensure that the outputted executables and
  libraries execute as efficiently as possible. This mode should be used
  for completed and tested software that is to be released to end-users.
  The drawback of release mode is that whilst the generated code is
  usually faster and smaller, it is not accessible to debugging tools.
Debug Mode
Debug mode is used whilst developing software. When an assembly is
  compiled in debug mode, additional symbolic information is embedded
  and the code is not optimised. This means that the output of the
  compiler is generally larger, slower and less efficient. However, a
  debugger can be attached to the running program to allow the code to
  be stepped through whilst monitoring the values of internal variables.

Some excellent SO threads about this is here and here

A: Try to do the following steps:
Step I.

*

*Right click on a web project name in a solution explorer and choose "Publish"

*Inside a "Pick a publish target" select "Folder"

*Make sure you have "bin\Release\" in a "Folder or File Share" right pan

*Click on "Create Profile" button in a bottom right corner of the popup

*In opened window click on "Rename Profile" blue link

*Set "Release" in a "New Profile Name" input box

Step II.

*

*Once again right click on a web project name in a solution explorer and choose "Publish"

*Click on "Create new profile" blue link

*Inside a "Pick a publish target" select "Folder"

*Make sure you have "bin\Debug\" in a "Folder or File Share" right pan

*Click on "Create Profile" button in a bottom right corner of the popup

*In opened window click on "Settings" blue link

*In an opened "Publish" popup inside a left menu choose "Settings"

*Set "Debug" in a "Configuration" drop down list

*Click on "Save" button

*Click on "Rename Profile" blue link

*Set "Debug" in a "New Profile Name" input box

*Click on "Save" button

As a result you will have 2 profiles for publishing that you can specify in a drop down list before publishing.
You can also create as many profiles as you need.
Final Step.
Try to play with it consistently changing profiles, then clicking on a "Publish" button and checking your specified output folders:

*

*bin/Debug/

*bin/Release/

If you make everything correctly you will have specific Web.config files inside each folder.

A: I think When you make a desktop application then your Debug and Release folder create in Bin folder,And in web applications debug and release folder is not in bin folder.
The difference between the debug and release folder is,
Debug mode :  Help you in debugging like line no etc.No optimized while
Release mode : It is optimized and efficient because all debug information is removed.


text:
Q: C# ADO.NET IBM DB2 named parameters with same name throws Not enough parameters specified Exception I have a fairly agnostic ADO.NET application that connects to a number of databases and is able to extract the necessary information to run.  I have hit a snag with DB2 and how it handles named parameters, particularly when I reuse a named parameter in the same query.  I know of a couple of ways to get around this by simply adding more parameters, but in theory it should work as it does on other databases that I connect to as the parameter name is the same.
What I'm doing is a bit more complicated and involves subqueries etc, but to demonstrate, take the following query:
select value from test.table where cola=@key1 and colb=@key1;
The named parameter @key1 is used twice.
My code is as follows:
       try
        {
            DbProviderFactory dbfFactory = DbProviderFactories.GetFactory("IBM.Data.DB2.iSeries");
            using (DbConnection dbConnection = dbfFactory.CreateConnection())
            {
                dbConnection.ConnectionString = "DataSource=xxx.xxx.xxx.xxx;UserID=xxxxxxxx;password=xxxxxxxxx";

                using (DbCommand dbCommand = dbConnection.CreateCommand())
                {
                    IDbDataParameter iddpParameter1 = dbCommand.CreateParameter();
                    iddpParameter1.ParameterName = "@key1";
                    iddpParameter1.DbType = DbType.String;
                    iddpParameter1.Value = "1";

                    dbCommand.Parameters.Add(iddpParameter1);
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.CommandText = "select value from test.table where cola=@key1 and colb=@key1";
                    dbConnection.Open();

                    using (IDataReader idrReader = dbCommand.ExecuteReader())
                    {
                        while (idrReader.Read())
                        {
                                   ...
                        }
                    }
                }

            } // end dbConnection
        } // end try

        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }

When I run this I get an exception that tells me:
System.InvalidOperationException: Not enough parameters specified.  The command requires 2 parameter(s), but only 1 parameter(s) exist in the parameter collection.

I get what it is telling me, but I'm looking for help in figuring out how I can have the provider use the named parameter for both parameters as they are the same.  It seems that it is doing a blind count of named parameters and not realizing that they are the same named parameters.  SQL Server seems to allow me to do this with the same code above.   I'm guessing it's just one of those differences in the providers, but hoping someone has run into this and has a solution for DB2 that doesn't get into specific DB2 code.
Thanks, appreciate the assistance.

A: well I did a little more digging, and I wonder if it might be the connector that you are using. So I'm doing the following (which is very similar to what you are doing)
in my app config file I have
<connectionStrings>
    <add name="AWOLNATION" providerName="Ibm.Data.DB2" connectionString="Server=sail:50000;Database=Remix;" />
</connectionStrings>

in my Databasemanager class I would initialize it like so
    public static DatabaseManager Instance(string connectionStringName)
    {
        var connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
        if (connectionStringSettings == null) throw new MissingMemberException("[app.config]", string.Format("ConnectionStrings[{0}]", connectionStringName));
        return new DatabaseManager(connectionStringSettings);
    }

    private DatabaseManager(ConnectionStringSettings connectionInformation)
    {
        _connectionInformation = connectionInformation;
        _parameters = new Dictionary<string, object>();
    }
    private void Initialize()
    {
        _connection = DbProviderFactories.GetFactory(_connectionInformation.ProviderName).CreateConnection();
        _connection.ConnectionString = _connectionInformation.ConnectionString;

        _command = _connection.CreateCommand();
    }

I add parameters a little different though. I have a Dictionary<string,object> that I add too when setting up my query. To use your example I would have had this
    public IEnumerable<object> GetSomething(string key)
    {
        var sql = "select value from test.table where cola = @key1 and colb = @key1";
        _manager.AddParameter("@key1", key);

        return _manager.ExecuteReader<object>(sql, ToSomethignUseful);
    }

    private object ToSomethignUseful(DatabaseManager arg)
    {
        return new { Value = arg.GetArgument<object>("value") };
    }

then reading is where the OP and I have similar code
    public IEnumerable<T> ExecuteReader<T>(string sql, Func<DatabaseManager, T> conversionBlock)
    {
        Initialize();
        using (_connection)
        {
            _connection.Open();
            _command.CommandText = sql;
            _command.CommandType = CommandType.Text;

            if (_parameters.Count > 0)
                AddParameters(_command, _parameters);

            _parameters.Clear();

            using (_reader = _command.ExecuteReader())
            {
                while (_reader.Read())
                {
                    yield return conversionBlock(this);
                }
            }
        }
    }
    private static void AddParameters(DbCommand command, Dictionary<string, object> parameters)
    {
        foreach (var param in parameters)
        {
            command.Parameters.Add(CreateParameter(command, param.Key, param.Value));
        }
    }

    private static DbParameter CreateParameter(DbCommand command, string key, object value)
    {
        var parameter = command.CreateParameter();
        parameter.ParameterName = key;
        parameter.Value = value;

        return parameter;
    }

running said code is working for me, so I wonder if the difference is in the provider that we are using. I'm using named parameters in production and have been for atleast a year now, possibly closer to 2 years.
I will say that I did get the same error when essentially running the same code twice, as shown in this code
    public static void IndendedPrintForEach<T>(this IEnumerable<T> array, string header, Func<T, string> consoleStringConverterMethod)
    {
        var list = array.ToList();
        var color = Console.ForegroundColor;
        Console.ForegroundColor = ConsoleColor.Magenta;
        Console.WriteLine($"<<<{header}>>>");
        Console.ForegroundColor = color;

        if (!list.Any())
        {
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("    ************NoItemsFound************");
            Console.ForegroundColor = color;
        }
        else
        {
            foreach (var item in list)
                Console.WriteLine($"    {consoleStringConverterMethod(item)}");
        }
    }

on line 3 var list = array.ToList() was the fix to the problem that you were seeing for me. before I had if (!array.Any()) which would run the query and use the parameters (which I clear out before I execture the query) then when I go to enumerate through and print each item in the array I was then getting the error. For me the problem was that it was re-running the query which I had no more parameters. The fix was to enumerate the query with the ToList() and then do my checking and printing on the list.

A: You answered you own question: "Unfortunately, I have not found a solution. I had to create another named parameter and just assign it the same value"
Oracle/DB2/Sybase especially are difficult with SQL queries and parameters.

*

*Parameters in the SQL query should be in the same order they are added to the C# parameters are added to the C# SQL command (Oracle, Sybase)

*Put parenthesis around the SQL query where clause parts using parameters (all)

*Make sure the SQL data types are matching the C# parameter data types (all)

*Check for overflow/underflow of parameter data so that the SQL query does not error

*Pass in null/empty string in the appropriate format for the database.  Ideally, create C# SQLParameter create methods to create the parameter in the correct format for the database

Oracle is particularly finicky about this.  Take the time to build a C# wrapper library to construct a C# query object correctly, construct C# parameters correctly and add the C# SQL parameters to the query.
Put in notes that the query parameter add order should match the order of "@" parameters in the SQL query.
This wrapper library is you documentation for you and the next developer to avoid the problems you've encountered.


text:
Q: why does GPG store different things in a bash var compared to a file I am trying to decrypt a file to a bash variable and then pipe that to zcat and then pipe that mysql.  Sending the output to file is not an option as it is a specified requirement.
so what I have is:
temp=$(gpg --batch --quiet --yes --passphrase=XXXXXX --decrypt file.sql.gz.gpg)
{ zcat preprocess.sql.gz; echo $temp | zcat; } | mysql -u$DB_USER -p$DB_PWD --host=$DB_HOST $DB_ID

The response is a correctly unzipped preprocess file followed by:
zcat: stdin is encrypted -- not supported

However when I do:
gpg --batch --quiet --yes --passphrase=XXXXXX --decrypt file.sql.gz.gpg > tempfile.sql.gz
zcat preprocess.sql.gz tempfile.sql.gz | mysql -u$DB_USER -p$DB_PWD --host=$DB_HOST $DB_ID

It works as expected.  However as I said we do not want any decrypted files hanging around on the server for any length of time (some of the mysl imports take hours) so writing the file and then deleting it is not a starter.
So the question is why does gpg store something different in the $temp variable as compared to the file? and what can I do about it

A:
However as I said we do not want any decrypted files hanging around on
  the server for any length of time ...

Instead of saying:
temp=$(gpg --batch --quiet --yes --passphrase=XXXXXX --decrypt file.sql.gz.gpg)
{ zcat preprocess.sql.gz; echo $temp | zcat; } | mysql -u$DB_USER -p$DB_PWD --host=$DB_HOST $DB_ID

say:
{ zcat preprocess.sql.gz; gpg --batch --quiet --yes --passphrase=XXXXXX --decrypt file.sql.gz.gpg | zcat; } | mysql -u$DB_USER -p$DB_PWD --host=$DB_HOST $DB_ID

And you'd even avoid a variable holding decrypted data!


text:
Q: Selenium Hover elements with IE I have an HTML div tag and inside the div there is an element which appears in when mouse enters its boundaries. Now I want to click on the element which becomes visible on mouse entering or hovering.
Issue: the element starts blinking.
Browser: IE8
I am using the code below
   IWebElement we = addToBasket.FindElement(By.Id("MyBox"));
   action.MoveToElement(we).MoveToElement(driver.FindElement(By.Id("plus-icon"))).Click().Build().Perform();

Any suggestion why its blinking?

A: The element is blinking because of a feature of the IE driver called "persistent hovers." This feature is of dubious value, but is required because of the brain-dead way IE (the browser, not the driver) responds to WM_MOUSEMOVE messages when using the SendMessage API.
You have a few options. You can turn persistent hovers off by using code like the following:
InternetExplorerOptions options = new InternetExplorerOptions();
options.EnablePersistentHover = false;
IWebDriver driver = new InternetExplorerDriver(options);

Be aware, though that this will subject you to the whims of where the physical mouse cursor is on the screen when you attempt to hover. If that's not acceptable, you have a couple of other approaches you could take. First, you could turn off so-called "native events," which would cause the driver to rely solely on synthesized JavaScript events. This approach has its own pitfalls, due to relying only on JavaScript to synthesize the mouse events.
InternetExplorerOptions options = new InternetExplorerOptions();
options.EnableNativeEvents = false;
IWebDriver driver = new InternetExplorerDriver(options);

Finally, you could migrate from using the default SendMessage Windows API to code that uses the more correct SendInput API. This is done with the RequireWindowFocus property. Its drawback is that the mouse input is injected at a very low level in the system, which requires the IE window to be the foreground window on the system.
InternetExplorerOptions options = new InternetExplorerOptions();
options.RequireWindowFocus = true;
IWebDriver driver = new InternetExplorerDriver(options);

As a final note, do not attempt to set all of these properties at once; pick an approach and stick with it. Several of them are mutually exclusive, and the interaction between them is undefined.

A: This worked for me.
WebElement element = driver.findElement(By.xpath("element xpath"));
Locatable hoverItem = (Locatable) element;
Mouse mouse = ((HasInputDevice) driver).getMouse();
mouse.mouseMove(hoverItem.getCoordinates());


text:
Q: jQuery Unable to process cloned input fields I have some code to clone the input field directly preceding the clone 'button' renaming the id and name of the field as it goes (shown below): -
$(".clone").live('click', function () {
var doppleganger = $(this).prev(); // Neater referencing.
    $(doppleganger).clone().insertAfter(doppleganger);

$(this).prev().attr("id", "input" + increment).attr("name", "input" + increment);

    increment++;

return false;

});

.
The form (#adv_magic) data is loaded on the fly with the jquery ajax event and submitted thusly: -
$("#adv_magic").live('submit', function() {

$("#editor_button, #date_select, #search").hide();
$(".loader").show();

$.ajax({
    type: "POST",
    url: "./scripts/aquire_template.php",
    data: $("#adv_magic").serialize(),
    success: function(html){
        $("#right_container").empty();
        $(".loader").fadeOut(350);
            $("#right_container").html(html);
    }
});
return false;

});

However my cloned input fields are not being processed when the form is posted to my script.  I've seen a few tutorials about creating the input fields as an array but i'd rather not mess around with that at this stage if there is anything else I can do.
I'm wondering also if it's to with the way I am serializing the form? I can't post the full code or a link on this occasion unfortunately as the application is not available from the web. Any thoughts on this would be really appreciated! I'm stumped!
Update Sat 10th 20:31 GMT >
I got the following report from the console > post tab in firebug: -
input1  meeting
input2  select date
input3  enter text
input5  NUMBER MISSING
input6  enter text
input7  test
switch  1

Source
input1=meeting&input2=select+date&input3=enter+text&input6=enter+text&input7=test&input5=NUMBER+MISSING&switch=1

Inputs 5/6/7 are cloned elements so presumably they are being passed to the script?
Update Sat 10th 21:06 GMT >
Echoing the string variable before it is being processed by the script shows non of the cloned input fields.

A: This one worked for me.
<form id="myForm">
    <fieldset>
        <input type="text" id="input1" name="input1"/><input type="button" value="clone" class="clone"/>
    </fieldset>
    <input type="submit" value="submit" id="sbmt"/>
</form>

$(".clone").live("click", function(e) {
    var count = $("#myForm fieldset").length + 1;
    $(this).parent().clone().insertBefore("#sbmt").find("input[type=text]").attr({
        "id": "input" + count,
        "name": "input" + count
    }).val("");
});

$("#myForm").submit(

function(e) {
    e = e || window.event;
    e.preventDefault();

    $.ajax({
        type: "GET",
        url: "/",
        data: $("#myForm").serialize(),
        success:function(data){
        }
    });
    return false;

});

demo: http://jsfiddle.net/wFzx5/2/


text:
Q: Is my JUnit test for delete operation correct? I want to write JUnit test for delete operation that call delete method ORMLite library (it is not important). I'm mocking behaviour of ORMLite API in my tests. But I'm not sure that I created the correct test and that I'm really testing delete operation.
So, I have defined some datasource class with operations create(List<Object> o), read(Object o), delete (Object o). Here is simplified code.
class ObjectDataSource {

    public void create (List<Object> o) {
        ormapi.create(o);
    }

    public List<Object> read (Object o ) {
        return ormapi.queryForMatching(o);
    }

    public void delete (Object o) {
        ormapi.delete(o);
    }

}

Now,I here is created JUnit test. It's testing that Object was really removed.
@Test
public void readTest() {
    // ormlite api init
    RuntimeExceptionDao<Object, Integer> dao = mock(RuntimeExceptionDao.class);
    ObjectDbHelper dbHelper = new ObjectDbHelper(context, dao);
    ObjectDataSource dataSource = new ObjectDataSource(context, dbHelper);

    // data init
    Object object = new Object() {{ setId(47); }};
    Object completeObject = new Object {{ setId(47); setObjectName("test object"); }}
    List<Object> list = ArrayList<Object>();
    list.add(completeObject);

    // api mocking
    when(dao.queryForMatching(object)).thenReturn(new ArrayList<Object>());

    // testing
    dataSource.create(list);
    dataSource.delete(object);
    List<Object> readList = dataSource.read(object);
    Assert.assertEquals(new ArrayList<Object>(), readList);
}

A: You ought to be checking that delete() has been called. You probably need something like:
@Test
public void readTest() {
    // ormlite api init
    RuntimeExceptionDao<Object, Integer> dao = mock(RuntimeExceptionDao.class);
    ObjectDbHelper dbHelper = new ObjectDbHelper(context, dao);
    ObjectDataSource dataSource = new ObjectDataSource(context, dbHelper);

    // data init
    Object object = new Object() {{ setId(47); }};
    Object completeObject = new Object {{ setId(47); setObjectName("test object"); }}
    List<Object> list = ArrayList<Object>();
    list.add(completeObject);

    // testing
    dataSource.create(list);
    dataSource.delete(object);

    // verify that ObjectDataSource class correctly invokes delete
    // method on DAO:
    verify(dao).delete(object);
}

I see no benefit in calling dataSource.read() and testing the result, since you've faked that result with your mocked DAO object. It doesn't really tell you anything. It's like setting int x = 5; and then checking x is 5.
Also, your test is very misleadingly named if your intention is to check deletion works... Something like deleteTest might be a better name :-)


text:
Q: Connection to MongoDB with Express.js is working but I am not sure if is the correct way I am trying to create a backend for a learning project, because of learning purposes I would like to complete this project without using Mongoose. Currently I initiated MongoDB in a db.js file under config folder. Within server.js I can succesfully call the function and wait for a promise before listening on the defined port with Express.
Now within the Controller for the specific collection I have to call the same function (connectToDb) again to succesfully create, find, update etc.
I was wondering if this is the actual way it should be done, isn't there like a functionality to just do CRUD actions on the collection within the controllers without using the connectToDb functionality again. What it looks like to me is that within server.js you already start the connection and for every action I have to create another connection and something does not feel right this way.
For example purposes I have only included createHabitCard, also I know that this is not the way a controller is used and that a lot of functionality belongs in a service file but this is because I am still learning and slowly expanding "my creation".
I hope someone can give me some advice on this, thanks in advance :)
Server.js
require("dotenv").config({ path: "./config.env" });
const express = require("express");
const connectToDb = require("./configs/db.config");
const cors = require("cors");
const path = require("path");
const habitcardRouter = require("./routes/habitcardRoutes");
const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(cors());
app.use(express.json());
app.use("/", express.static(path.join(__dirname, "/public")));

//First routes
app.use("/api/habitcards", habitcardRouter);

let db;

connectToDb()
  .then((res) => {
    app.listen(PORT, () => {
      console.log(`Server is running on port: ${PORT}`);
    });
  })
  .catch((err) => {
    console.log(err);
  });

module.exports = { db };

db.config.js
const { MongoClient } = require("mongodb");

const uri = process.env.ATLAS_URI;

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const connectToDb = async () => {
  try {
    const database = client.db("howwasmyday");
    return database;
  } finally {
    await client.close();
  }
};

module.exports = connectToDb;

habitcardController.js
const connectToDb = require("../configs/db.config");

//Create habitcard

const createHabitCard = async (req, res) => {
  const habitcard = req.body;
  try {
    let db = await connectToDb();
    const collection = db.collection("habitcards");
    collection.insertOne(habitcard, (err, result) => {
      res.json("It all worked");
    });
  } catch (err) {
    console.log(err);
  }
};
module.exports = {
  createHabitCard,
};

A: Right, you don't need to create a new connection for every controller and request. Change your db.config.js file in the following way:
const {MongoClient} = require("mongodb");
const uri = process.env.ATLAS_URI;
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
let database;
const connectToDb = async () => {
  if (database) {
    return database;
  }
  try {
    database = client.db("howwasmyday");
    return database;
  } finally {
    await client.close();
  }
};
module.exports = connectToDb;

This pattern is called Singleton. Every time you call connectToDb, it will return already cached instance of database connection and avoid connecting to it again.
This works in node.js, b/c every time you require db.config.js from different files, it will cache the module, so you'll have db connection persisting in memory.
You can read more about this here.

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.


text:
Q: python multiprocessing, make instance per process and reuse it I'm using pytesseract to do some ocr with a multiprocessing approach.
The approach looks the following:
tess_api = PyTessBaseAPI()
Parallel(n_jobs=4)(delayed(execute)(image) for image in images)

having the function:
def execute(image):
    tess_api.SetImage(image)
    text = tess_api.GetUTF8Text()

this will lead into a concurrency problem as Worker 1 could override the image before Worker 2 is executing gettext()
The idea is now to have per worker one instance of PyTessBaseAPI.
The main idea would be to do something like:
tess_apis = [PyTessBaseAPI(), PyTessBaseAPI(), PyTessBaseAPI(), PyTessBaseAPI()]

and then hand over tess_api[0] to the worker 0 but I don't know how I could do the connection between the worker and the instance.
Any suggestions, or what would be a better approach?
As I have thousands of images I don't wan't to create instances inside the execute function.

A: Use Pool(initializer=...) to initialize the Tesseract object once per worker process before they start reading their job queue.
tess_api = None

def initialize_worker():
    global tess_api
    tess_api = PyTessBaseAPI()  # initialize a copy for this instance

def execute(image):
    tess_api.SetImage(image)
    text = tess_api.GetUTF8Text()

def main():
    with multiprocessing.Pool(initializer=initialize_worker) as p:
        for result in p.imap_unordered(images, chunksize=10):
            # ...

This will only work if you're using actual processes; if you're using threads instead (which might work, considering Tesseract is C and would release the GIL), you could use contextvars/threading.local.

A: Pool(initializer=...) can work as mentioned. However, if you want to do anything more complex, I'd suggest using Ray.
Then it an be expressed as follows.
import ray

ray.init()

@ray.remote
class Worker(object):
    def __init__(self):
        self.tess_api = PyTessBaseAPI()

    def execute(self, image):
        self.tess_api.SetImage(image)
        return self.tess_api.GetUTF8Text()

# Create several Worker actors.
workers = [Worker.remote() for _ in range(4)]

# Execute tasks on them in parallel.
result_ids = [worker.execute.remote(image) for worker in workers]

# Get the results
results = ray.get(result_ids)

You can read more about Ray in the documentation. Note that I help develop Ray.


text:
Q: how to apply box-shadow on hexagon i want to give box shadow on the hexagon
here is my jsfiddle
jsfiddle
and this is my hexagon css property
    .hex1 {
    background-color: rgba(52,152,219,.5);
    text-align: center;
    line-height: 70px;
    height: 80px;
    width: 140px;
    margin: 60px 10px;
    position: relative;
    z-index: 1;
box-shadow:2px 2px 2px 2px grey;
}
.hex1:before {
    border-top: 40px solid transparent;
    border-bottom: 40px solid rgba(52,152,219,.5);
    top: -80px;
}
.hex1:after, .hex1:before {
    border-left: 70px solid transparent;
    border-right: 70px solid transparent;
    content: "";
    position: absolute;
    left: 0;
    z-index: -1;
}
.hex1:after {
    bottom: -80px;
    border-top: 40px solid rgba(52,152,219,.5);
    border-bottom: 40px solid transparent;
}

this is not affecting on my hexagon .. is there any way to five border and box shadow to hexagon.
please help

A: You Can Use these code....

 #hexagon{
   background: red;
   width: 100px; height: 60px;
   position: relative;
   -moz-box-shadow: 0 0 10px rgba(0,0,0,0.7);
  -webkit-box-shadow: 0 0 10px rgba(0,0,0,0.7);
   box-shadow: 0 0 10px rgba(0,0,0,0.7);
 }

http://jsfiddle.net/jelmerdemaat/5UMxW/3/


text:
Q: Finding the lim sup and lim inf of a sequence? Let $a_n=1$ if $n=2^k$ for some positive integer $k$, and $a_n=\frac{1}{n!}$ otherwise.
Find $\limsup_n a_n$ and $\liminf_n a_n$.
Find $\limsup_n \frac{|a_{n+1}|}{|a_n|}$.
Find $\limsup_n |a_n|^{1/n}$.
Attempt at a solution: For the first part, since all $n,k>0$, $a_n<0$ whenever $n\not=2^k$, so the $\limsup = 1$. For the lim inf, would if be 0, since the $\frac{1}{n!}$ portion decreases as $n\to \infty$?
For the second part, I was thinking that this might occur when $a_{n+1}=1$, which would make $a_n$=$1/(2^k -1)!$, so would this be $(2^k-1)!$  ?
For the last portion, $\limsup_n |a_n|^{1/n}$, would this occur when $a_n=1$ so $1^{1/2^k}=1$?
Thank you in advance!

A: Recall that $\lim \sup_n a_n$ is an abbreviation for $\lim_{n\to \infty} \sup \{a_j :j>n\}$. So in each case consider $\sup \{a_j :j>n\}$ for any  $n$ and it should be easy.

A: It seems to me that in the second part, the lim sup is infinity, since as you mention we have the value $(2k-1)!$, but $k$ can be arbitrarily high.