text:
Q: How to fix Video tearing with KDE and ati drivers? I have Ubuntu 12.04.02 x64 and KDE 4.10.00.
I'm having a little video tearing while playing ANY video (HD mkv, avi, etc.).

*

*it happens with vlc latest version and with default Ubuntu video player and also with other players like kmplayer.

*I have some effects enabled and I use: OpenGL, Raster, Shaders: OpenGL 2 and vertical sync.

*I have ATI MSI R6870 hawk with latest fglrx video card driver AMD Catalyst™ 13.1 Proprietary Linux Display Driver

*My pc hardware are:
CPU: Intel(R) Core(TM) i5-2500 Sandy Bridge
Motherboard: Asus P8P67 PRO
Display: full hd display (DVI)

*glxinfo says direct rendering: yes

*No problem with Windows 7.

How to solve it?

A: The AMD Catalyst software has an option to reduce tearing.
Open a terminal and type kdesudo amdcccle, then find the section for reducing tearing and check the option.
Additionally, I should mention that I had some tearing issues with VLC and Totem a while ago (before the 13.1 driver was released), but using smplayer instead of VLC dramatically improved my video playback. If the Catalyst option doesn't work for you, give smplayer a try and see if that helps.


text:
Q: If hibernat.hbm2ddl.auto is having value create with MYSQL then hibernate not able to create schema I am trying to generate mysql schema automatically when I run a hibernate program with spring but it giving below exception
It is working properly with DERBY DB but it is giving problem with MYSQL
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'hdb'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
    at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
    at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
    at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
    at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
    ... 41 more

For which I have done below configuration
app.properties file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hdb
jdbc.username=root
jdbc.password=java
jdbc.initialSize=1
jdbc.maxActive=2

spring.xml file
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${jdbc.initialSize}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
    </bean>

   <bean id="namedParameterDaoImpl" class="org.net.dao.NamedParameterDaoImpl">
        <property name="dataSource" ref="dataSource"/>
   </bean>

   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>app.properties</value>
        </property>
   </bean>

   <bean id="mysessionFactory"  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>org.net.model</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

So I am not able to understand why it is not working.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set the caret position in a contenteditable div in Firefox and old IE versions I am trying to set the caret position in a contenteditable div. Here is code that works in modern IE, Chrome and Safari, but does not work in Firefox 36.0.4 or old IE versions (9 or less). For this answer it is safe to assume that the contenteditable div contains only text (i.e no child elements other than a single text node).
Please tell me how to fix this, especially for Firefox.
Thank you.
HTML:

12345

JavaScript:
function moveCaret(d, position) {
    d.focus(); // This is included because in my application the div is already focused by the time the caret must be moved.
    if (window.getSelection && document.createRange) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        var range = document.createRange();
        range.setStart(d.childNodes[0], position);
        range.setEnd(d.childNodes[0], position);
        sel.addRange(range);
        d.focus();
     } else if (document.selection && document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(d);
        textRange.select();
        d.focus();
    }
}

try {
    var position = 0;
    var d = document.getElementById("d");
    moveCaret(d, 3);
}catch(e) {
    document.getElementById("log").innerHTML += e.toString();
}

http://jsfiddle.net/bk7ade2r/

A: The issue seems to be that firefox can not focus() on a contenteditable div.


text:
Q: Generating a histogram and density plot from binned data I've binned some data and currently have a dataframe that consists of two columns, one that specifies a bin range and another that specifies the frequency like this:-
> head(data)
      binRange Frequency
1    (0,0.025]        88
2 (0.025,0.05]        72
3 (0.05,0.075]        92
4  (0.075,0.1]        38
5  (0.1,0.125]        20
6 (0.125,0.15]        16

I want to plot a histogram and density plot using this but I can't seem to find a way of doing so without having to generate new bins etc. Using this solution here I tried to do the following:-
p <- ggplot(data, aes(x= binRange, y=Frequency)) + geom_histogram(stat="identity")

but it crashes. Anyone know of how to deal with this?
Thank you

A: the problem is that ggplot doesnt understand the data the way you input it, you need to reshape it like so (I am not a regex-master, so surely there are better ways to do is):
df <- read.table(header = TRUE, text = "
                 binRange Frequency
1    (0,0.025]        88
2 (0.025,0.05]        72
3 (0.05,0.075]        92
4  (0.075,0.1]        38
5  (0.1,0.125]        20
6 (0.125,0.15]        16")

library(stringr)
library(splitstackshape)
library(ggplot2)
# extract the numbers out,
df$binRange <- str_extract(df$binRange, "[0-9].*[0-9]+")

# split the data using the , into to columns:
# one for the start-point and one for the end-point
df <- cSplit(df, "binRange")

# plot it, you actually dont need the second column
ggplot(df, aes(x = binRange_1, y = Frequency, width = 0.025)) +
    geom_bar(stat = "identity", breaks=seq(0,0.125, by=0.025))

or if you don't want the data to be interpreted numerically, you can just simply do the following:
df <- read.table(header = TRUE, text = "
                 binRange Frequency
1    (0,0.025]        88
2 (0.025,0.05]        72
3 (0.05,0.075]        92
4  (0.075,0.1]        38
5  (0.1,0.125]        20
6 (0.125,0.15]        16")

library(ggplot2)
ggplot(df, aes(x = binRange, y = Frequency)) + geom_bar(stat = "identity")

you won't be able to plot a density-plot with your data, given its not continous but rather categorical, thats why I actually prefer the second way of showing it,

A: You can try
library(ggplot2)
ggplot(df, aes(x = binRange, y = Frequency)) + geom_col()


text:
Q: How to place tabs of TabBar in middle and upon clicking next tab, it starts shifting to left? Mock I am trying to implement:

Then when starting clicking the next tab i.e 2 it shows 3rd tab (named 3) and 1st tab moves to left. Till eventually to far left slide of the screen.
Mock:

Finally, when clicked further it shows three dots to left also. FYI clicking on dots does nothing its a representation of showing that more that is there.
Now following is my code.
class TabbedAppBarSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: choices.length,
        child: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.white, // status bar color
            brightness: Brightness.light,
            title: TimerPage(),
            bottom: TabBar(
              // isScrollable: true,
              indicatorColor:Colors.red,
              unselectedLabelColor:Colors.grey,
              labelColor: Colors.red,
              tabs: choices.map((Choice choice) {
                return Tab(
                  text: choice.title,

                  // icon: Icon(choice.icon),
                );
              }).toList(),
            ),
          ),
          body: TabBarView(
            children: choices.map((Choice choice) {
              return Padding(
                padding: const EdgeInsets.all(6.0),
                child: ChoiceCard(choice: choice),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

const List<Choice> choices = const <Choice>[
  const Choice(title: '1'),
  const Choice(title: '2'),
  const Choice(title: '...'),

]; // above is a mock array which eventually will be coming from API call

Thanks and bear my coding I am new to flutter.

A: Use TabController to animate to next tab and use PreferredSize to control positon of tabbar
code snippet
appBar: AppBar(
        title: Text(widget.title),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(20.0),
          child: Padding(
            padding: const EdgeInsets.only(left: 200.0),
            child: TabBar(
              controller: _tabController,
              tabs: [
                Tab(text: 'Tab 1'),
                Tab(text: 'Tab 2'),
                Tab(text: 'Tab 3'),
              ],
            ),
          ),
        ),
      ),

@override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 3);
  }

  void _toggleTab() {
    _tabIndex = _tabController.index + 1;
    _tabController.animateTo(_tabIndex);
  }

working demo

full code
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Tabs Demo';
    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MyHomePageState();
  }
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  int _tabIndex = 0;

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 3);
  }

  void _toggleTab() {
    _tabIndex = _tabController.index + 1;
    _tabController.animateTo(_tabIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: BottomAppBar(
        notchMargin: 20,
        child: new Row(
          // mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            InkWell(
              onTap: () {
                _toggleTab();
              },
              child: Text(
                'Next >',
                style: TextStyle(fontSize: 20, color: Colors.red),
              ),
            )
          ],
        ),
      ),
      appBar: AppBar(
        title: Text(widget.title),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(20.0),
          child: Padding(
            padding: const EdgeInsets.only(left: 200.0),
            child: TabBar(
              controller: _tabController,
              tabs: [
                Tab(text: 'Tab 1'),
                Tab(text: 'Tab 2'),
                Tab(text: 'Tab 3'),
              ],
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          Card(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ListTile(
                  leading: Icon(Icons.album),
                  title: Text('Hello 1'),
                  subtitle: Text('Click on Next Button to go to Tab 2.'),
                ),
              ],
            ),
          ),
          Card(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ListTile(
                  leading: Icon(Icons.album),
                  title: Text('Hello 2'),
                  subtitle: Text('Click on Next Button to go to Tab 3'),
                ),
              ],
            ),
          ),
          Card(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ListTile(
                  leading: Icon(Icons.album),
                  title: Text('Hello 3'),
                  subtitle: Text('The End'),
                ),
              ],
            ),
          ),
        ],
      ),
    ));
  }
}


text:
Q: Why must this density function be greater than zero almost everywhere? In Klenke's Probability book, in Example 8.31, he states

Why is it that $f(x)>0$ a.a.? There are several densities for which we have $f(x)=0$ outside a compact set... For example, we can see the densities of the Beta distribution as zero outside the $[0,1]$ interval.

A: The term 'almost everywhere' requires a reference measure. You are taking the reference measure as Lebesgue measure. But the author is taking $P_X$ as the reference measure . Since $P_X (\{x: f (x)=0\})=\int_{\{x: f (x)=0\}} f(x)dx=0$ it follows that $f>0$ almost everywhere w.r.t. $P_X$.


text:
Q: Python - matplotlib - How to plot a space even when .bar() takes a zero value import pylab as p
from matplotlib.ticker import MaxNLocator

fig = p.figure(figsize=(20,8))
plot = fig.add_subplot(111)

ind = range(10)

bar1 = plot.bar(ind,l,facecolor='#777777')

# x-axis
plot.xaxis.set_major_locator(MaxNLocator(10))
plot.set_xticklabels(headings)

p.show()

value of l on first run:
l=[29, 28, 35, 32, 31, 27, 36, 40, 59, 60]

value of l on second run:
l=[13,1,18,0,0,0,0,0,0]

See photo for results:
http://s1362.photobucket.com/user/superempl/media/figure_1a_zpsf281ca7b.png.html?sort=3&o=0
Problem:  A bar is not created when the value being passed in from list l is 0, even though the bar doesn't exist I would still like a space to be created as if it were.
The issue I face is that when list l's first and last value != 0 then 10 bar charts are produced (which is what I want), but when either the first or last value/s = 0 then less than 10 bars get created and thus the width of the bars changes (as you can see in the photo).
How would one solve this problem please?

A: Put this just before p.show():
plot.set_xlim([0,len(l)])


text:
Q: Element Tree, Parsing XML didnt appear in QLineEdit i make plugin in QGIS to open and parse xml from local disk or removable disk, this is code i use to open xml file :
from PyQt4 import QtCore, QtGui
from ui_testparse import Ui_testparse
import xml.etree.ElementTree as ETree
# create the dialog for zoom to point

class testparseDialog(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_testparse()
        self.ui.setupUi(self)

        opendata = self.ui.btnCari
        QtCore.QObject.connect(opendata, QtCore.SIGNAL('clicked()'),self.openxml)

    def openxml(self, event=None):

        #open dialog
        openfile = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '*.xml')

        self.ui.lineLokasi.setText(openfile)

        #call XML data
        self.isiData(openfile)

    def isiData(self, nmsatu):
        #open teks with read mode
        openteks = open(nmsatu, 'r').read()

        self.ui.textXml.setText(openteks)

and to parse xml after that i try use Element Tree, this code i use to parse xml from code above :
#Parse XML from Above
        self.parsenow(openteks)

    def parsenow(self, parse):
        element = ETree.fromstring(parse)
        xml_obj = ETree.ElementTree(element)
        for title_obj in xml_obj.findall('./{gmd#}dateStamp/{gco#}Date'):
            print element
            self.ui.lineSkala.setText(element)

and xml i want to parse have format like this :
<gmd:datestamp>
<gco:Date> XML Date </gco:Date>

i try to show XML Date in LineSkala(lineEdit) in QT but when i run it, it can open and read xml but failed to show XML Date in lineSkala, it just blank and didn't give me any error message
What i miss?
Thanks for your help in advance

A: The XPath syntax supported by etree is quite limited. Also, you must either supply a prefix dictionary when using find/findall (although this is not properly documented in python2), or use the full namespace uri.
So try something like:
ns = {
    'gmd': 'http://www.isotc211.org/2005/gmd',
    'gco': 'http://www.isotc211.org/2005/gco',
    }

tree.findall('.//gmd:dateStamp/gco:Date', ns)

or:
tree.findall('.//{http://www.isotc211.org/2005/gmd}dateStamp/'
             '{http://www.isotc211.org/2005/gco}Date')

PS:
If you need to use more sophisticated XPath syntax, try lxml, which has a very similar API to ElementTree, but many more features.


text:
Q: ANDROID - Measuring the level of sound a user made and displaying it I am currently writing an app that shows how loud the user is. I currently have it recording the sound when they press record using MediaRecorder and then allowing them to listen to that recording again by pressing play, this uses MediaPlayer.
I now want to some how output how loud the noise was that they recorded. Due to using the MediaRecorder I am trying to retrieve the loudness through.getMaxAplitude(). Using this I am then trying to display it in a textview so the user can see their results.
Therefore in doing this I have the current code in the begin recording function is
 recorder = new MediaRecorder();
 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
 recorder.setOutputFile(OUTPUT_FILE);
 recorder.prepare();
 recorder.start();

 int test = recorder.getMaxAmplitude();
 txtView.setText(test);

As you would have already guessed this doesn't work, the recording the audio does work but acquiring or showing the amplitude to the user isn't
Any ideas?

A: Probably you can take a view on the stackoverflow post here.
Also a similar kind of project is available in code.google.com


text:
Q: How to reinstate a missing wireless adaptor in Windows 10 I have no Wireless adapter showing under Control Panel → Network and Internet → Network Connections. I just see Bluetooth and Ethernet.
How do I reinstate the Wireless adapter in Windows so I can make a connection to a wireless network?
I am also missing the option to "manually connect to a wireless network", as shown here:

It is a desktop Windows 10 machine with a Linksys AC1200 USB wireless adapter plugged in and I am trying to connect to a 4G hub.
Linksys AC1200 is present and enabled in Device Manager (reporting as Linksys WUSB6300). The drivers are the latest from the Linksys website.

A: This is a known issue with Win 10 if you have older VPN software installed like Cisco or in my case Junos. What worked for me was to uninstall the VPN and reboot. However the articles out there suggest registry editing:
Windows 10 looses wifi after upgrade
Start CMD as an admin

reg delete HKCR\CLSID{988248f3-a1ad-49bf-9170-676cbbc36ba3} /va /f

next in the same CMD:

netcfg -v -u dni_dne

reboot and wifi should be back.
However I got the "registry key not found so I unstalled the VPN, reboot and wifi is back. Next I installed a new version from Win 10 store and everything works great!

A: I had similar situation where the network drivers and the hardware were fine (Device Manager listed all network adapters and Linux used the network just fine, but there was no network in Windows 10 and no Network Connections in network settings). My guess is that I had Cisco AnyConnect VPN installed in Windows 8.1 and then upgraded to Windows 10 where it all got messed up.
Many users experienced that and there were many suggestions and none of them worked.
Eventually I had to run the following command to reset the absent network connections:
netcfg -d

The first time it failed and gave many errors. Then I tried netcfg -d command again and then it was successful (bizarrely).
Then I rebooted and suddenly Windows 10 started picking up networks.
Now it can associate with WiFi AP securely but it still fails to get an IP address... well, at least something.

A: Go into Device Manager and see if the driver is installed under the Network Adapters category. In device manager you can also check if the driver is disabled or not. You can open Device manager by following these steps, or you can search for devmgmt.msc in the search bar from the Start Menu.
If the driver is not installed, go to the manufactures website and download it.

A: I just had the same issue. Drove me nuts. No connection options listed except Broadband and dial-up (what year is this??), with an Ethernet connection.
I saw that a Windows Update had been installed this morning, about the time that the wifi crapped out. Did a system restore back to the update installation and voila---my wifi adapter was back.
I knew it was something with the laptop because my tablets and phone wifi were both fine.

A: *

*Open Device Manager, open the drop-down Network adpaters

*Right-click Network adapters

*Select Scan for hardware changes

*If you can't see your Wireless adapter, go to step 11

*If you can see it, right-click on the adapter

*Select Uninstall ( this should only uninstall you driver software, not delete it)

*Now right-click Network adapters again

*Select Scan for hardware changes. This should re-detect your wireless adapter)

*Once detected, restart you machine

*Make sure your Wireless adapter in Network And Sharing Center is Enabled. Now try what you have to.

*If you cant find you your Wireless adapter device, you may need to properly install a wireless adapter driver. You'll have to do it perfectly, or have a service person do it for your machine

PS: If you want to create a wifi hotspot (when your wireless adapter is working properly), try the following command in Command Prompt
netsh wlan connect ssid=YOURSSID name=PROFILENAME

Replace YOURSSID with your ssid, and PROFILENAME with a name for you connection

A: I have had same issues but got it resolved. Always turn off the wifi of PC/Laptop before shutdown. Whenever PC/Laptop is again started wifi adaptor will be available under network adaptor tab. Switch on Wifi and search for required wifi network.
Hope this works for all.


text:
Q: Ошибка в POST методе, передача null Пишу на MVC, есть страница для создания клиента. Есть 2 модели: Client и City.
 public class Client
{
    [Key]
    public int Id { get; set; }
    public string Surname { get; set; }
    public string Name { get; set; }
    public string Patronymic { get; set; }
    public string Telephone { get; set; }
    public City City { get; set; }
    public string Adress { get; set; }
    [DisplayName ("Passport")]
    public string SeriaNumberPassport { get; set; }
    [DisplayName("Identifical Code")]
    public string IdentificalCode { get; set; }

}

public class City
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

У меня есть так же DropDownList который при создании клиента выводит список доступных городов.

            @Html.DropDownList("Cities", (IEnumerable<SelectListItem>)ViewBag.Cities, "Select City", new { @class = "form-select" })

Но при нажатии кнопки создания вылетает ошибка, клиента невозможно создать, в дебаге City = null. не знаю как исправить. Ниже get и post методы Create
// GET: Clients/Create
    public IActionResult Create()
    {
        if (_context.City != null) _cities = _context.City.ToList();
        ViewBag.Cities = new SelectList(_cities, "Id", "Name");

        return View();
    }

    // POST: Clients/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Surname,Name,Patronymic,Telephone,City,Adress,SeriaNumberPassport,IdentificalCode")]
        Client client)
    {
        if (ModelState.IsValid)
        {
            _context.Add(client);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(client);
    }


text:
Q: Spread values across rows Excel I have two tables (one for purchase order and the other for the invoice) and I want to distribute the quantity from the invoice table to the purchase order invoice quantity column but I want to match the exact quantity from the purchase order quantity.
Here is how the table looks now

And this is how I want it to look:

How do I manage to do that? Thanks!
Here is the excel attachment file:
Book1.xlsx
Update:
Is it possible to do that for multiple codes?

A: With Invoice Quantity in the E2 cell and and Qty in the M2 cell, put this formula into E3,
=MAX(MIN(M$3-SUM(E$2:E2), D3), 0)

Fill down as necessary.

A: You can use the Consolidate function to do so.

*

*Click a cell where you want to locate the result in your current worksheet.

*Go to click Data > Consolidate

*In the Consolidate dialog box:
(1.) Select Sum from Function drop down list;
(2.) Click  button to select the range that you want to consolidate, and then click Add button to add the reference to All references list box;
(3.) Check Top row and Left column from Use labels in option.

*After finishing the settings, click OK, and the duplicates are combined and summed.

Note: If the range do not have the header row, you need uncheck Top row from the Use labels in option.
Reference: http://www.extendoffice.com/documents/excel/1268-excel-combine-duplicate-rows-and-sum.html


text:
Q: How to open camera using voice search? I am new to Android development. I am trying to build a voice assistant and I want it to open the camera when I say a specific words. I know how to turn speech to text but I am stuck at opening the camera.
if (Text.getText().toString().equals("Launch camera")){
  saySomething("Launching camera");
  // How do I make it launch the camera?
}

Edit :
So far, my app turns speech to text and then it looks for if it is equal to a command and respond it that way. I have 2 questions about this.

*

*Can I use "contains" for a text ?

*How can I make it respond it first and turning into text later?
Code
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case RESULT_SPEECH: {
            if (resultCode == RESULT_OK && null != data) {
                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                Text.setText(text.get(0));
            }
            if (Text.getText().toString().equals("Hello")){
                saySomething("Hello");
            }
        }

    }
}

A: You need to implement Speech to Text RecognizerIntent in android , RecognizerIntent will give the text version of what user said and later you can use the result text result.contains("Launch camera") to verify that result text contains your desired action , it will basically give you a list of possible results and you can go through all to match your input
@Override
public void onResults(Bundle results) {
    List<String> list=results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
    for(String s: list)
    {
        if(s.contains("Launch camera"))
        {
         dispatchTakePictureIntent()
         // call the function to take picture
         break;
        }
    }
}

add the below code into your class
// constant variable for request code
static final int REQUEST_IMAGE_CAPTURE = 1;

// function to open the camera app using explicit intent
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

And later you will receive the response in onActivityResult from where you can fetch your image from data intent
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     // verify the successful completion of picture taken
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

        // get the bundle
        Bundle extras = data.getExtras();

        // imageBitmap will hold the image you are looking for
        Bitmap imageBitmap = (Bitmap) extras.get("data");

        // optionally you can display this pic in some ImageView or can delete this line
        mImageView.setImageBitmap(imageBitmap);
    }
}

Code implementation
Android Speech to Text Example
Taking Photos Simply

Can I use "contains" for a text ?

Yes you can use contains to match and verify result that you found , a required text input from user. You should use contains because equals will only work when you found an exact word to word match and there can be some noise which can effect the response text so safer option is to use contains

How can I make it respond it first and turning into text later?

Basically using  RecognizerIntent , the input has been already converted into text and you also need the text input to display it later into your TextView so simply you can launch camera intent first and display the text after the picture is taken so store the match content into some String variable and later use that variable to display it into your TextView
String inputcommand="";

@Override
public void onResults(Bundle results) {
    List<String> list=results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
    for(String s: list)
    {
        if(s.contains("Launch camera"))
        {
            // store your match in global variable to use it later
            inputcommand = s;

            dispatchTakePictureIntent()
            // respond it first
         break;
        }
    }
}

After the picture has been successfully capture then you can display the text
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        ...            // same above mentioned code

        // display your input in TextView
        Text.setText(inputcommand );
    }
}


text:
Q: Cross Browser navigation CSS I am trying to build a simple CSS only navigation bar for my site. This is it working fine in modern browsers:

And this is my CSS:
#nav{
    width:496px;
    height:45px;
    float:right;
    background-color:#bee199;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
    border-radius:3px;
    margin-top:5px;
    border:1px solid #a09f9f;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    box-sizing:border-box;
}
    #nav ul{
        list-style:none;
        text-align:center;
    }
    #nav ul .last{
        padding-right:0px;
        border-right:none;
    }
    #nav ul li.navsep{
        width:1px;
        height:44px;
        background-color:#a09f9f;
        padding:0;
        margin-right:10px;
    }
        #nav ul li{
            width:auto;
            height:44px;
            display: -moz-inline-stack;
            display:inline-block;
            padding-right:10px;
            margin-bottom:-16px;
        }
            #nav ul li a{
                font-family:Helvetica, Arial, sans-serif;
                font-size:20px;
                font-weight:400;
                text-decoration:none;
                color:#434342;
            }

HTML:

Principles

Our services

Recent work

Contact

One of my problems is using negative margins, I really don't want to be using them. But every time I try to use conventional methods the text will not center vertically and it looks like this:
This also happens on older browsers.
Thanks for your time! If you need more information just ask! :)

A: *

*Omit the
 and use borders instead.

*use lineheight on the li elements.

A: Instead of using negative margin use line-height, in your case #nav ul li {height: 44px; line-height: 44px;} this will vertical center your text


text:
Q: Интеграция с Zoho CRM и вывод данных не из кастомных таблиц Есть ли у кого-нибудь опыт интеграции с Zoho CRM? Итак, все по порядку:
I. Создал ACCESS_TOKEN через API Mode в данной CRM
II. Пытаюсь получить хоть какие-нибудь данные посредством кода, выложенного у них в качестве примера:
    header("Content-type: application/xml");
    $token = "my_token";
    $url = "https://crm.zoho.com/crm/private/xml/Clients/getRecords";
    $param= "newFormat=1&authtoken=".$token."&scope=crmapi";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    $result = curl_exec($ch);
    curl_close($ch);
    echo $result;

В ответ возвращается XML с 4600 ошибкой - Unable to process your request. Please verify whether you have entered proper method name,parameter and parameter values.
III. Поставил библиотеку zoho-crm-client-php, которая также на любые мои запросы возвращает пустые массивы в качестве результата, хотя при обращении к полям, возвращает список кастомных полей в кастомных модулях:
$client = new ZohoCRMClient('Leads', 'my_token');

$records = $client->getFields()->request();

IV. Собственно вопрос: что я делаю не так, учитывая, что мне нужно получить данные не из кастомных модулей, а с клиентского (список вакансий)? Я так понял, для этого нужно использовать метод getSearchRecordsByPDC. Правильно ли это?
V. Второй вопрос - при обращении к нестандартному модулю нужно указывать CustomModule1(2,3,4-N), но в ответ получаю сообщение о том, что данных модулей не существует, а при попытке обратиться по на названию $client = new ZohoCRMClient('MyModule', 'my_token'); получаю снова 4600 ошибку.
VI. Если я такой рукожоп, что не могу сделать простую интеграцию из примеров, то что говорить уже о нестандартном модуле.


text:
Q: Cannot install nvidia graphics driver 390 on Ubuntu 18.04 After facing issues with nvidia 396, I wanted to move back to nvidia 390 on Ubuntu 18.04.
I purged nvidia from the system, moving back to the default xorg driver.
I then added the repository ($ sudo add-apt-repository ppa:graphics-drivers/ppa ), and tried to install 390 by

$ sudo apt install nvidia-driver-390

However, this is also installing nvidia 396 on my machine.
How can I install 390?
Thanks.

A: Solved.
What was happening was that another ppa was interfering and the download was taking place from that repo.
It was the System76 Pop repository. I removed it from Software and Updates.
After that, running

$ sudo apt install nvidia-driver-390

installs the 390 driver as expected.

A: Ok, as of now many of the bugs related to this issue (NVIDIA Graphics) have been fixed and the installation procedure is fairly easy.

1.Entering Grub Boot Parameters - This can be done by going to the grub menu at boot (press Esc or Shit at boot) here press e.  2. Enabling Text Mode Booting - Here add a 3 after quiet splash and press F10 to reboot using the new parameters. 3. Purge NVIDIA- Now login to the text only mode, and purge all the NVIDIA drivers completely using the sudo apt-get remove --purge nvidia*, and reboot. While rebooting follow step 1, here edit the parameters and add the command nomodeset before qiet splash, and press F10
   to reboot the using the new parameters.  4. Installing Nvidia Drivers- once in the system run commands in the terminal sudo apt-get update and sudo apt-get upgrade now.

*

*Add the drivers repository to Ubuntu, run the commands sudo add-apt-repository ppa:graphics-drivers/ppa and sudo apt update.  Now, do not update graphic drivers via the terminal, instead search for Software & Updates in the Ubuntu GUI. here go to the additional drivers tab. Here you will find the set of NVIDIA drivers for your system. select the nvidia-drivers-390 or use nvidia-driver-415 i think that one is the latest. (Make sure that you do not select or keep selection in Using X.Org X server - selection)

*The installation will take a while once the installation is complete, reboot the system.

*Now it isn't necessary to add nomodeset to boot parameters, the Ubuntu Os should boot properly and without any error.

*If you have added nomodeset parameters to Grub, remove it in this step and keep the quiet splash parameter alone.(or else nvidia driver wont load)

*Once you have completed the login, enter the Ubuntu desktop, search for the NVIDIA Xserver application, to monitior the nvidia GPU.


text:
Q: TypeError: list indices must be integers or slices, not str JSON Scrapy I was scraping a JSON response but getting the following error
values = resp['acf']
TypeError: list indices must be integers or slices, not str

I am not sure where did I do wrong.
Your response is highly appreciated.
# -*- coding: utf-8 -*-
import scrapy
import json

class MainSpider(scrapy.Spider):
    name = 'main'
    start_urls = 'https://chamber.vinylagency.com/wp-json/wp/v2/directory?industry-type=547&per_page=100'

    def parse(self, response):
        resp = json.loads(response.body)
        values = resp['acf']

        for value in values:
            name = value['OrgName']

            yield {
                "Name": name,
            }

A: The exception is raised because the response is a list of objects and you are trying to access it as a dict directly.
Here is a sample of the response:
[
    {
        "id": 33286,
        "date": "2020-05-09T02:38:47",
        "date_gmt": "2020-05-09T02:38:47",
        "guid":
        ...
    },
    {
        "id": 32954,
        "date": "2020-05-09T02:38:22",
        "date_gmt": "2020-05-09T02:38:22",
        "guid":
        ...
    }
]

You probably want to parse like this:
def parse(self, response):
    resp = json.loads(response.body)

    for value in values:
        name = value['acf']['OrgName']

        yield {
            "Name": name,
        }


text:
Q: swiperjs - how to keep prev and next slider in sight but not centered current one
I'm using swiperjs, and what to stay part of the prev slider in the window, but not center the current one
I've triedspaceBetween, centeredSlides and slidesOffsetBefore, but none of these satisfied.
here is a  demo
, can anyone help ?

A: Your swiping library adds a swiper-slide-prev to the previous slide.
Adding
.swiper-slide-prev {
  margin-left: 55px;
}

looks similar to what you want.
Updated fiddle https://jsfiddle.net/z33jqt4s/2/


text:
Q: Doctrine query: best approach to creating a select query joining three tables? I have three tables that I need to join to extract a result set, and I am not sure if I should use createQueryBuilder, createNativeQuery, or some other approach.
My three tables are

*

*Email (joined to member via field: member)

*Member (joined to company via field: current_company)

*Company

The Entities are properly annotated in the code. For example
In the Email Entity:
   /**
     * @ORM\ManyToOne(targetEntity="Member")
     * @ORM\JoinColumn(name="member", referencedColumnName="id", nullable=true)
     */
    protected $member;

In the Member Entity:
/**
 * @ORM\ManyToOne(targetEntity="Company")
 * @ORM\JoinColumn(name="current_company", referencedColumnName="id", nullable=true)
 */
protected $current_company;

And in the Company Entity:
/**
 * @ORM\ManyToMany(targetEntity="Member", mappedBy="companies")
 */
protected $members;

What I need to do is extract a set of records from Email where the Members are all associated with one Company.
The following SQL in MySQL returns what I need, but I am new to Doctrine and do not know how best to translate this query into something Doctrine can use to extract the same results:
select e.* from email e
join member m on m.id = e.member
join company c on c.id = m.current_company
where m.current_company = '95f1b5a4-03c9-11e9-85b1-989096db2d5f';

Can anyone help, and which approach should be employed createQueryBuilder, createNativeQuery, etc?

A: Update, I was able to get it working using plain old SQL, but I am not sure if this is an acceptable workaround in the Doctrine world. Thoughts and suggestions from those with more experience would be greatly welcome!
$conn = $this->em->getConnection();
$sql = "select e.* from fitchek.email e join fitchek.member m on m.id = e.member join fitchek.company c on c.id = m.current_company where m.current_company = ?";

$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $company_uuid);
$stmt->execute();


text:
Q: JSF Rendered property Issue So, i have this piece of code, which basically performs CRUD on a database and displays the results in a <h:dataTable>. The problem is, my code is able to generate an edit action, when I provide a fixed ArrayList. But, if i populate the ArrayList from a database, the rendered property does not provide an editable option from the form. I am able to perform delete functionality, so it's not a matter of the object not being read properly in the action method's parameter. In short, the rendered attribute doesn't work when my data source is a table from a database.
Here's the page:
index.xhtml
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
</h:head>
<h:body>

JSF 2 dataTable example

    <h:form>
        <h:dataTable value="#{order.orderList}" var="o"
        styleClass="order-table"
        headerClass="order-table-header"
        rowClasses="order-table-odd-row,order-table-even-row"
       >

         <h:column>

            <f:facet name="header">Order No</f:facet>

            <h:inputText value="#{o.orderNo}" size="10" rendered="#
  {o.editable}" />

        <h:outputText value="#{o.orderNo}" rendered="#{not o.editable}" />

         </h:column>

         <h:column>

        <f:facet name="header">Product Name</f:facet>

        <h:inputText value="#{o.productName}" size="20" rendered="#
 {o.editable}" />

        <h:outputText value="#{o.productName}" rendered="#{not o.editable}"
 />

         </h:column>

         <h:column>

        <f:facet name="header">Price</f:facet>

        <h:inputText value="#{o.price}" size="10" rendered="#{o.editable}"
 />

        <h:outputText value="#{o.price}" rendered="#{not o.editable}" />

         </h:column>

         <h:column>

        <f:facet name="header">Quantity</f:facet>

            <h:inputText value="#{o.qty}" size="5" rendered="#{o.editable}"
 />

            <h:outputText value="#{o.qty}" rendered="#{not o.editable}" />

         </h:column>

         <h:column>

        <f:facet name="header">Action</f:facet>

            <h:commandButton value="Edit" action ="#{order.editAction(o)}">
                <f:setPropertyActionListener
                    target = "#{Orders}" value = "#{o}" />
            </h:commandButton>

         </h:column>
            <h:column>
                <f:facet name ="header">Action</f:facet>
                <h:commandButton value ="Delete" action="#
 {order.delete(o)}"/>
            </h:column>

      </h:dataTable>

  </h:form>
</h:body>

The orderBean.java:
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name="order")
@RequestScoped
public class orderBean implements Serializable{

private static final long serialVersionUID = 1L;

private static ArrayList<Orders> orderList;

public ArrayList<Orders> getOrderList() {
            try{
                    orderBean.orderList = new ArrayList();
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/orders","root","");
                    PreparedStatement ps = conn.prepareStatement("Select *
  from Orders");
                    ResultSet rs = ps.executeQuery();
                    while(rs.next())
                    {
                        Orders orders = new
 Orders(rs.getString("orderNo"),rs.getString("productName"),
 rs.getBigDecimal("price"),rs.getInt("qty"));

                        orderList.add(orders);
                    }
                }
                catch(Exception e)
                {

                }
                return orderList;
}
    public void delete(Orders order)
    {
          try{
                    orderBean.orderList = new ArrayList();
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/orders","root","");
                    PreparedStatement ps = conn.prepareStatement("Delete
from orders where orderNo=?");
                    ps.setString(1,order.orderNo);
                    int rs = ps.executeUpdate();

                }
                catch(Exception e)
                {

                }
    }

public void editAction(Orders order) {
            order.setEditable(true);
            }

public static class Orders{

    String orderNo;
    String productName;
    BigDecimal price;
    int qty;
    boolean editable;

    public Orders(String orderNo, String productName, BigDecimal price, int
  qty) {
        this.orderNo = orderNo;
        this.productName = productName;
        this.price = price;
        this.qty = qty;
    }
                 public void setOrderNo(String orderNo)
            {
                this.orderNo = orderNo;
            }
            public void setProductName(String productName)
            {
                this.productName = productName;
            }
            public void setPrice(BigDecimal price)
            {
                this.price = price;
            }
            public void setQty(int qty){
                this.qty = qty;
            }
            public String getOrderNo()
            {
                return this.orderNo;
            }
            public String getProductName()
            {
                return this.productName;
            }
            public BigDecimal getPrice()
            {
                return this.price;
            }
            public int getQty()
            {
                return this.qty;
            }
            public boolean isEditable() {
                return this.editable;
            }
            public void setEditable(Boolean editable) {
                this.editable = editable;
            }
    //getter and setter methods
 }
 }


text:
Q: CSS Flexbox - Bg-color and text don't align Please see codepen link. ccs was compiled in    scss Please scroll down more than halfway on css page to    avoid reset code.    Issue: Both button's on right    of nav backgrounds and text are out of sync, compared to the left    side.
Can anyone spot the issue, please?
Open to suggestions on my B__E__M styling

A: The issue is : li in left side navigation has display: list-item; but li in right navigation has display: flex;
Increase the width of .nav__ul--rt to 25% and give the correct property to li on right side to align it correct. This observation is based on your layout.

A: Why not just put the background colour on the parent?

/* Box sizing rules */
*,
*::before,
*::after {
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}

/* Remove default padding */
ul[class],
ol[class] {
  padding: 0;
}

/* Remove default margin */
body,
h1,
h2,
h3,
h4,
p,
ul[class],
ol[class],
li,
figure,
figcaption,
blockquote,
dl,
dd {
  margin: 0;
}

/* Set core body defaults */
body {
  min-height: 100vh;
  scroll-behavior: smooth;
  text-rendering: optimizeSpeed;
  line-height: 1.5;
  font-family: Arial, Helvetica, sans-serif;
}

/* Remove list styles on ul, ol elements with a class attribute */
ul[class],
ol[class] {
  list-style: none;
}

/* A elements that don't have a class get default styles */
a:not([class]) {
  text-decoration-skip-ink: auto;
}

/* Make images easier to work with */
img {
  max-width: 100%;
  display: block;
}

/* Natural flow and rhythm in articles by default */
article > * + * {
  margin-top: 1em;
}

/* Inherit fonts for inputs and buttons */
input,
button,
textarea,
select {
  font: inherit;
}

/* Remove all animations and transitions for people that prefer not to see them */
@media (prefers-reduced-motion: reduce) {
  * {
    -webkit-animation-duration: 0.01ms !important;
            animation-duration: 0.01ms !important;
    -webkit-animation-iteration-count: 1 !important;
            animation-iteration-count: 1 !important;
    -webkit-transition-duration: 0.01ms !important;
            transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}

/*````````````````the actual code below`````````````*/

.nav {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: nowrap;
      flex-wrap: nowrap;
  height: 100px;
  background-color: #ecdfc8;
}

.nav__img {
  -webkit-box-flex: 1;
      -ms-flex: 1 1 10%;
          flex: 1 1 10%;
}

.nav img {
  height: 100px;
  margin: auto;
}

.nav__section {
  -webkit-box-flex: 8;
      -ms-flex: 8 1 90%;
          flex: 8 1 90%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
      -ms-flex-pack: justify;
          justify-content: space-between;
}

.nav__ul {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-pack: distribute;
      justify-content: space-around;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.nav__ul--lf {
  width: 50%;
}

.nav__ul--rt {
  width: 15%;
}

.nav__item {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  background-color: #df7861;
  border-radius: 5px;
  -webkit-transition: background-color 1s;
  transition: background-color 1s;
  padding: 10px 15px;

}

.nav a {
  color: #111;
  text-decoration: none;
  font-weight: 300;

}

.nav__item:hover {
  background-color: #df7861;
  background-color: #ecdfc8;
}
/*# sourceMappingURL=style.css.map */

          Home

          Product

           Learn

            Contact

            Sign in

A: Remove display: flex from class .nav__item
.nav__item {
   display: -webkit-box;
   display: -ms-flexbox;
}


text:
Q: Forcing a vector's allocator to point to a specific location I have a simple c-style buffer allocated with custom alignment requirements - 64 byte size alignment and 4096 bytes address alignment. I wish to use a std::vector and allocate it such that it's data pointer points to the above mentioned buffer's location?
Is it possible? And if it is, then what are possible cons? I will not be resizing the vector ever during its lifetime. I am forced to work with vectors and have no choice over it.

A: Using a vector for this is probably wrong (bad practice) - even though vector might only allocate once and even if you wrote the custom allocator - since you want the buffer to be static and shouldn't be moved. Additionally the vector is supposed to own the memory and clean up(release) after itself (where as you state that the memory for the elements have been pre-allocated), so vector does not seem like a good fit for a container to begin with.
Cast to aligned pointer type and use a span c++20
When/if you have have c++20 you could use a span as your "array view" basicly.
Until that, just use an aligned type and cast to that.
#include <iostream>
#include <type_traits>
#include <utility>
#include <span>

struct alignas(0x1000) Mine {
  unsigned char a[64];
};

typename std::aligned_storage<sizeof(unsigned char[64]), 0x1000>::type mem_seg[10]; //<-- or your own allocated storage

int main() {

   std::cout << "size: " << sizeof(Mine) << std::endl;
   std::cout << "alignment: " << alignof(Mine) << std::endl;

   Mine* begin_ = reinterpret_cast<Mine*>(&mem_seg);
   Mine* end_ = reinterpret_cast<Mine*>(&mem_seg) + 10;

   //pre-c++20 you done, work with the pointers 'normally'

   //c++20 gives you span: (an array view of sorts)
   //that works a lot like a normal container (except it's fixed size)
   std::span<Mine> mine_view(begin_, end_);

   for(auto& e : mine_view) {
       std::cout << "address check: " << &e << std::endl;
   }

   return 0;
}

https://godbolt.org/z/H3BDof
The above prints the following (example):
size: 4096

alignment: 4096

address check: 0x604000

address check: 0x605000

address check: 0x606000

address check: 0x607000

address check: 0x608000

address check: 0x609000

address check: 0x60a000

address check: 0x60b000

address check: 0x60c000

address check: 0x60d000


text:
Q: How to get good (Windows-like) font rendering on Linux Mint KDE I'm using Linux Mint 13 KDE.  I installed a TrueType font that I have and like (Arrus BT).  I've noticed that the font rendering is noticeably worse on Linux.  If I set hinting to none or slight, the letters appear slightly fuzzy and there is poor contrast.  If I set hinting to full, the letters appear slightly chunky in shape, but the lines are unappealingly thin.  In both cases the letters seem too "light", alhtough in the first case it's because they seem to be blurred too much with the background, and in the second case it's because the lines are too thin.
I have seen various other postings like this and a few like this that advocate fiddling with .fonts.conf in a way that seems to be outdated (I can set those settings in the System Settings panel).  I've also tried the "autohint" option described for instance here.  None of these produce what I want.
For an illustration, here is the font rendering on Linux with no hinting:

Here it is with full hinting:

And here it is on Windows:

I've used this color scheme because the problem is most pronounced with this sort of situation, where the text is a brighter color on a dark background.  I've tried intermediate hinting options, all of which suffer from basically the same problem (too blurry or too thin).  I've also tried the various subpixel smoothing options (RGB, BGR, etc.), which don't seem to have an appreciable effect on resolving the problem.
I see from previous posts on this issue that there are differences of opinion on what "looks best" in terms of font hinting and smoothing.  Putting all that aside, my question is simple: is there or is there not a way to get Linux to display the font so it looks like it does in Windows, and if so, how?

A: Subpixel smoothing can improve rendering slightly, but not 100% windows-like. Maybe you should try infinality patches?

A: Try the solution below for blurry or broken fonts: http://lampjs.wordpress.com/2014/09/12/arch-linux-kde-blurry-broken-fonts/
excerpt

*

*go to system settings ->application preference

*in fine tuning select "High display resolution and High CPU"

*click on fonts in left side bar

*check the "Force fonts DPI"


text:
Q: Unable to uninstall a package (gns3-gui) I have installed the GNS3 server and client separately on Ubuntu 20.0.4. when I check the packages list, GNS3 (GUI) is available:
test@gns3vm:/$ dpkg -l gns3*
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version       Architecture Description
+++-==============-=============-============-=================================
un  gns3           <none>        <none>       (no description available)
ii  gns3-iou       0.0.3~focal1  amd64        GNS3 support for IOU
hi  gns3-server    2.2.29~focal1 amd64        GNS3 server

The first line is the GNS3 GUI. But, when I want to uninstall it there is no GNS3 (GUI).
dpkg -r gns3-
gns3-iou     gns3-server

Do you have any idea about this problem? Is it possible to be the dpkg problem? How can I uninstall gns3 (GUI) only?

A: Unfortunately, you did not include any information on the steps you took to install this app.
This on-line guide explains how to install GNS3-GUI
The basic 5 steps are:

*

*Run the following commands step-wise:

sudo add-apt-repository ppa:gns3/ppa
sudo apt update
sudo apt install gns3-server gns3-gui

*

*Allow non-root users to use wire-shark and capture packets as well.

*Install IOU Support (Optional)

*Docker Support (Optional)

*Launch GNS3 on Ubuntu 20.04
Complete GNS3 setup on Ubuntu 20.04 Linux.
You can find the same instructions for all the steps within the link provided.

A: There is no problem. The dpkg output you quote shows shows packagage gns3 with status n, ie. "not installed". You cannot uninstall it because it is not installed in the first place.
Note that according to man dpkg-query, dpkg -l <pattern> lists not just installed packages, but packages listed in the dpkg database, which may include uninstalled and half-installed packages. You need to consult the Status column to know its actual status.


text:
Q: WARN: Could not register destruction callback
15:11:14,676  WARN FacesRequestAttributes:121 - Could not register destruction callback [org.springframework.beans.factory.support.DisposableBeanAdapter@1059fd6] for attribute 'purchaseController' because FacesRequestAttributes does not support such callbacks

This warn message appears in my log a lot. For every managed bean whenever it expires. It expires after a given time, because I'm using MyFaces Orchestra.
I have defined the org.springframework.web.context.request.RequestContextListener in my web.xml, and I don't have the spring jar only ones on my classpath (i.e. not a class-loading problem)
The docs of FacesRequestAttribute says:

NOTE: In contrast to ServletRequestAttributes, this variant does not support destruction callbacks for scoped attributes, neither for the request scope nor for the session scope. If you rely on such implicit destruction callbacks, consider defining a Spring RequestContextListener in your web.xml.

The purchaseController is actually a simple managed bean (not extending anything an implementing only Serializable), annotated with @Controller.
Update1:
The beans in @Scope("request") and @Scope("session") seem to be affected.
So I wanted to know whether this warn poses any danger to the proper flow. I.e. if something really needs those callbacks. If not, I will just skip the warning with the lo4j config.
Update 2:
I digged a little further, and it seems that this happens only sometimes. IF the listener is used, then RequestContextHolder.currentRequestAttributes() returns the ServletRequestAttributes, rather than FacesRequestAttributes. So it appears that sometimes the listener doesn't work and doesn't set the current attributes in the RequestContextHolder.
Update 3:
I turned debug on for RequestContextListener, and here's the result:
07:21:31,518 DEBUG RequestContextListener:69 - Bound request context to thread: org.apache.catalina.connector.RequestFacade@1190ae9
07:21:31,518 DEBUG RequestContextListener:89 - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@1190ae9
07:21:31,538  WARN FacesRequestAttributes:121 - Could not register destruction callback [org.springframework.beans.factory.support.DisposableBeanAdapter@11aa152] for attribute 'org.apache.myfaces.orchestra.conversation.AccessScopeManager' because FacesRequestAttributes does not support such callbacks
07:21:31,541  WARN FacesRequestAttributes:121 - Could not register destruction callback [org.springframework.beans.factory.support.DisposableBeanAdapter@1552393] for attribute 'localeController' because FacesRequestAttributes does not support such callbacks
....and so on, other request and session beans

It appears that the request gets destroyed before access to the beans is attempted. Which is very odd. Could this be due to a problem in the servlet container implementation of the listener handling?

A: I tried adding
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

as suggested by erhan14 on this forum post.
And that warning disappeared for me. Hope it helps.

A: In the javadoc of FacesRequestAttributes, we can read:

Note: In contrast to ServletRequestAttributes, this variant does not support destruction callbacks for scoped attributes, neither for the request scope nor for the session scope. If you rely on such implicit destruction callbacks, consider defining a Spring RequestContextListener in your web.xml.

And, indeed, the registerDestructionCallback() method of FacesRequestAttributes doesn't do much things:
public void registerDestructionCallback(String name, Runnable callback, int scope) {
    if (logger.isWarnEnabled()) {
        logger.warn("Could not register destruction callback [" + callback + "] for attribute '" + name +
                        "' because FacesRequestAttributes does not support such callbacks");
    }
}

But my understanding is that the RequestContextListener (that you have declared) will take care of this job. Its requestDestroyed(ServletRequestEvent requestEvent)  method is shown below:
public void requestDestroyed(ServletRequestEvent requestEvent) {
   ServletRequestAttributes attributes =
           (ServletRequestAttributes) requestEvent.getServletRequest().getAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE);
   ServletRequestAttributes threadAttributes =
           (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
   if (threadAttributes != null) {
       // We're assumably within the original request thread...
       if (attributes == null) {
           attributes = threadAttributes;
       }
       RequestContextHolder.resetRequestAttributes();
       LocaleContextHolder.resetLocaleContext();
   }
   if (attributes != null) {
       attributes.requestCompleted();
       if (logger.isDebugEnabled()) {
           logger.debug("Cleared thread-bound request context: " + requestEvent.getServletRequest());
       }
   }
}

And if you look at the javadoc of ServletRequestAttributes#requestCompleted():

Executes all request destruction callbacks and updates the session attributes that have been accessed during request processing.

So, I think that you can safely skip the WARN with log4j configuration (maybe confirm this with a little debugging session though).


text:
Q: How to creat a dataframe of columns each with 'n' empty values I am trying to create a dataframe of empty values. My code is
df['Voc_inIV'] = np.nan
df['Isc_inIV'] = np.nan
df['Voc_error'] = np.nan
df['Isc_error'] = np.nan
df['Pmpp_inIV'] = np.nan
df['ff'] = np.nan
df['v_at_Isc'] = np.nan
df['i_at_voc'] = np.nan

My above approach works. But this does not look good.
Is there a better approach than this? I mean, I did not like repeating np.nan all the times. Moreover, my dataframe should have n rows.

A: To create an empty dataframe, just don't pass any data to the data argument, but pass your column names  to columns:
cols = ['Voc_inIV','Isc_inIV','Voc_error','Isc_error','Pmpp_inIV','ff','v_at_Isc','i_at_voc']

df = pd.DataFrame(columns=cols)

Giving you:
>>> df
Empty DataFrame
Columns: [Voc_inIV, Isc_inIV, Voc_error, Isc_error, Pmpp_inIV, ff, v_at_Isc, i_at_voc]
Index: []

Edit: If you need it to have n rows, pass an index of range(n):
n = 5

df = pd.DataFrame(columns=cols, index=range(n))

>>> df
  Voc_inIV Isc_inIV Voc_error Isc_error Pmpp_inIV   ff v_at_Isc i_at_voc
0      NaN      NaN       NaN       NaN       NaN  NaN      NaN      NaN
1      NaN      NaN       NaN       NaN       NaN  NaN      NaN      NaN
2      NaN      NaN       NaN       NaN       NaN  NaN      NaN      NaN
3      NaN      NaN       NaN       NaN       NaN  NaN      NaN      NaN
4      NaN      NaN       NaN       NaN       NaN  NaN      NaN      NaN

A: Here is another approach, helping you specifically with not repeating np.nan:
df = pd.DataFrame()
cols = ['Voc_inIV', 'Isc_inIV', 'Voc_error', 'Isc_error', 'Pmpp_inIV', 'ff', 'v_at_Isc', 'i_at_voc']
for col in range(len(cols)):
    df[cols[col]] = np.nan


text:
Q: Using Arial Unicode MS BOLD in JavaFX I want to use the font Arial Unicode MS in my JavaFX project which works fine. But i want e.g. the headlines to be bold. But I don't get the bold font working. What's the probleme here?
I tried it with css and within the code directly
.bold-font {
    -fx-font-family: Arial Unicode MS;
    -fx-font-weight: bold;
}

and
label.setFont( Font.font("Arial Unicode MS", FontWeight.BOLD,24));

Nothing worked and when i check the font after setting with "getFont()" it is still regular.

A: i checked few possibilities with Arial Unicode MS and look

check this
incLab.setStyle("-fx-font-weight: bold; -fx-font-family: Arial Unicode MS; -fx-font-size: 24");


text:
Q: Magento updating CMS page XML to add block - block not loading I added a new CMS page, and editted the Layout XML to show this:
<reference name="head">
<block type="cms/block" name="myblock" template="myfolder/mytemplate.phtml"></block>
</reference>

So I put the file "mytemplate.phtml" in this folder:
/app/design/frontend/base/default/template/myfolder

And I put this test script in the file:
<?php
echo '<script>alert("hello");</script>';
?>

However, when I load the CMS page nothing happens, so it means the 'mytemplate.phtml' file is not loading.
How can I make this work?

A: If you're going to use template (phtml), your block should extend from Mage_Core_Block_Template.
So your block type should be core/template, not cms/block.

A: If you want to just display your template file, you should use block type core/template for that. Try this xml:
<reference name="head">
    <block type="core/template" template="myfolder/mytemplate.phtml"/>
</reference>


text:
Q: Search a inside a specific doc after getting its docId Iam trying to implement a 2-stage search which first searches for a document title (stored as StringField) and after getting the docId of the matching document i want to search for a string inside that document's content(stored as TextField) and then highlight it using the usual Highlighter
EDIT
Rephrasing the question
this is not the actual question.  Iam simply trying (my best) to avoid wrong/unhelpful answers
Given the docId and the Query object search for the query specified in the Query object inside the document given by the docId

A: Use Apache Tika in Solr to extract and index text of document. Document can be text file, PDF, PPT, XLS, DOC etc.

A: If you are using Java to query your index try this one. source here
public static void searchIndex(String searchString) throws IOException, ParseException {
        System.out.println("Searching for '" + searchString + "'");
        Directory directory = FSDirectory.getDirectory(INDEX_DIRECTORY);
        IndexReader indexReader = IndexReader.open(directory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        Analyzer analyzer = new StandardAnalyzer();
        QueryParser queryParser = new QueryParser(FIELD_CONTENTS, analyzer);
        Query query = queryParser.parse(searchString);
        Hits hits = indexSearcher.search(query);
        System.out.println("Number of hits: " + hits.length());

        Iterator<Hit> it = hits.iterator();
        while (it.hasNext()) {
            Hit hit = it.next();
            Document document = hit.getDocument();
            String path = document.get(FIELD_PATH);
            System.out.println("Hit: " + path);
        }

    }


text:
Q: Passing a service object from one activity to another I am using the Google Analytics API for an android app. To make data requests we need to create a service object:
Analytics analytics = Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY)
.setApplicationName("Hello-Analytics-API-Sample")
.setHttpRequestInitializer(credential)
.build();

What is the best way to pass this object to different activities, so I can data request for different activities? I checked the parcelable method, however, from what I understand, you need to implement that in the class whereas here I am importing the class from their API library.
Here is the article for more info: https://developers.google.com/analytics/solutions/articles/hello-analytics-api
To clarify I am using the GA API to pull data, not the SDK to collect data for my app.
Thanks

A: I did find this from google: http://developer.android.com/guide/faq/framework.html#3 . Creating a singleton class might be the way to go here. In case anyone else finds it useful


text:
Q: get execution time only from the command gtime I need to execute a command and get the execution time of it. I am using gtime but the output is a bit different from what I want.
gtime returns the result of the execution and then the execution time. I need to store the output of the command(which I need it to be the time only) in a variable and use it afterward.
Is there a way to change the command to get the execution time only?
So if I write the command below:
executiontime=$(gtime -f "%U" /Users/Desktop/SemanticLocality/optimathsat-1.6.2-macos-64-bit/bin/optimathsat < file.smt2)
echo "$executiontime"

then this is an example of the output I get:
sat

(objectives
 (misses_80 1)
)
9.94

A: To get executable time only from the output you can modify your command on such way:
executiontime=$(gtime -f "%U" /Users/ouafaelachhab/Desktop/SemanticLocality/optimathsat-1.6.2-macos-64-bit/bin/optimathsat < file.smt2|tail -1)


text:
Q: Data structure which needs to be filled in VBA I need to load some data from an 2D array to an type array structure.
My type structure looks like the following:
Public Type LocationType
  LocationID As String
  Description As String
  ZoneID As String
  IsEmpty As Boolean
  LastPalletArrivedTime As Date
  PalletID As String
  Sequence As Long
End Type

I declared the following:
Dim LocationArray() As LocationType

which needs to be filled with data from a 2D array.
The code I use to fill LocationArray is as follows:
For x = 1 To UBound(TextFileLine())
    LocationArray(x).Description = SplitTextLines(x, 0)
    LocationArray(x).LocationID = SplitTextLines(x, 1)
    LocationArray(x).Sequence = SplitTextLines(x, 2)
    LocationArray(x).ZoneID = SplitTextLines(x, 3)
    LocationArray(x).PalletID = SplitTextLines(x, 4)
    LocationArray(x).LastPalletArrivedTime = SplitTextLines(x, 5)
    LocationArray(x).IsEmpty = SplitTextLines(x, 6)
Next x

I was wondering if there is any method or code I could use to make the code which I use to fill "LocationArray" easier?
*Note all my variables are declared and code is working. I am just asking for better or easier method to the one I am currently using.
Help will be much appreciated.

A: After some thinking
create a Class module and name it Location
this is the code to use in the class module
Option Explicit

Public LocationID As String
Public Description As String
Public ZoneID As String
Public IsntEmpty As Boolean
Public LastPalletArrivedTime As Date
Public PalletID As String
Public Sequence As Long

Public Property Let Item(index As Long, value As Variant)
    Select Case index
        Case 1
             LocationID = value
        Case 2
             Description = value
        Case 3
             ZoneID = value
        Case 4
             IsntEmpty = value
        Case 5
             LastPalletArrivedTime = value
        Case 6
             PalletID = value
        Case 7
             Sequence = value
    End Select
End Property

Public Property Get Item(index As Long) As Variant
    Select Case index
        Case 1
             Item = LocationID
        Case 2
             Item = Description
        Case 3
             Item = ZoneID
        Case 4
             Item = IsntEmpty
        Case 5
             Item = LastPalletArrivedTime
        Case 6
             Item = PalletID
        Case 7
             Item = Sequence
    End Select
End Property

this is a standard Module1 for testing (note the commented section)
Option Explicit

Sub Main()

    Dim myLoc As Location
    Set myLoc = New Location

    Dim i As Long

    '////////////////
    ' SAMPLE filling

    For i = 1 To 7

        ' covering BOOLEAN
        If i = 4 Then
            myLoc.Item(i) = False

        ' covering DATE
        ElseIf i = 5 Then
            myLoc.Item(i) = Now

        ' covering LONG
        ElseIf i = 7 Then
            myLoc.Item(i) = i

        ' convering STRING
        Else
            myLoc.Item(i) = CStr("property " & i)

        End If
    Next i

   '///////////
   ' PRINTING

    For i = 1 To 7
        Debug.Print "property:" & i, myLoc.Item(i)
    Next i

    '/////////////////
    ' pay attention
    ' this is what you could do

    ' this section is commented as Im unable to test it
    ' but this should work for you

'    create a collection

'    Dim c As Collection
'    Set c = New Collection
'
'    Dim x As Long
'    For x = 1 To UBound(TextFileLine())
'        Dim loc As Location
'        Set loc = New Location
'
'        For i = 1 To 7
'            loc.Item(i) = SplitTextLines(x, i - 1)
'        Next i
'
'        c.Add loc
'    Next x
'
'    ' now if you wanted to retrieve the data
'    ' you iterate over the collection
'
'    For i = 1 To c.Count
'        For j = 1 To 7
'            Debug.Print c.Item(i).Item(j)
'        Next j
'    Next c

End Sub


text:
Q: "Grouping" differential equations and the appropriate methods for solving them I have an exam coming up and a pretty large part is going to be on first-order ordinary differential equations. This has been my weakest subject during the semester so I am trying to get down the basics. In particular, I am trying to classify the different types of ordinary DE's and the methods for solving them. Below, I am going to write down the different types of equations and how I would solve them. I would really appreciate if you guys could point out if I am using a wrong approach or if I have completely misunderstood something. (I hope this is a valid question for stackexchange, if not, I kindly ask one of the moderators to remove it).
ps: I apologize for the length of this question. It turned out longer than I expected.

First-order homogenous linear differential equation

Diff. equations in the form of:
$$y'(x)+g(x)y(x)=0$$
Method for solving: Separation of variables

First-order inhomogeneous linear differential equation

Diff. equations in the form of:
$$y'(x)+g(x)y(x)=r(x), \space \space \space r(x)\not=0$$
Method for solving:

*

*Solve the homogenous system: $y'(x)+g(x)y(x)=0$ and find the homogenous solution $y_h(x)$

*Use "variation of parameters" to find a particular solution $y_p(x)$

*The general solution is $y(x)=y_h(x)+y_p(x)$

First-order nonlinear differential equation

Diff. equations in the form of:
$$y'(x)=f(x,y)$$
The "method for solving" depends on whether or not the equation is separable.
In case the equation is separable then I can just use "separation of variables" and write the equation in the form: $y'(x)=f(x,y)=g_1(x)\cdot g_2(y)\iff \frac{dy}{dx}=g_1(x)\cdot g_2(y) \iff \frac{dy}{g_2(y)}=g_1(x)dx$.
The only nonlinear non-separable diff. equations I need to know are Bernoulli differential equations and equations in the form of $y'=F(\frac{y}{x})$

Bernoulli differential equation

Diff. equation in the form of:
$$y'(x)+p(x)y(x)=q(x)(y(x))^n$$
As far as I understand, for $n=0,1$ this becomes a linear differential equation and I can solve it like I solved the previous diff. equations.
Method for solving for $n \ge 2$:

*

*Divide both sides by $y^n \implies \frac{y'}{y^n}+p(x)y^{1-n}=q(x)$

*Substitute $v=y^{1-n}$ to convert into a diff. equation in terms of "$v$".

*To determine what $y'$ is, differentiate $v$. $\implies v'=(1-n)y^{-n}y' \iff \frac{y'}{y^n}=\frac{v'}{(1-n)}$

*The differential equation becomes: $\frac{v'}{1-n}+p(x)v=q(x)$

*Solve by using "separation of variables" and "variation of parameters".

*Resubstitute

Differential equation: $y'=F(\frac{y}{x})$

Method for solving:

*

*Substitute $v(x)=\frac{y}{x} \iff y=xv; \space y'=v+xv'$

*The equation becomes $v+xv'=F(v) \iff xv'=F(v)-v$

*This equation is now separable and can be solved by the methods I mentioned above.


text:
Q: Difference between "Browser Mode" and "Document Mode" in Internet Explorer I´m really glad that I must no more use IETester since IE6 support was dropped in our company and IE9 has some quite cool developer tools. I can set "Browser Mode" and "Document Mode" but I can´t tell the difference. Does anyone know it? This post also didn´t help me out: IE8 browser mode vs document mode
Thanks

A: Document Mode is what the browser uses to render the page: IE9, IE8, IE7 or Quirks.
Browser Mode sets how the browser identifies itself to the web server and to JavaScript.
From a testing standpoint, it seems unnecessarily confusing that these are two separate options and you usually want to change both, for example, set the Browser mode to IE8 and the Document Mode to IE8 to get IE9 to pretend to be IE8.
There's also the Internet Exploer 9 Compatibility View option for Browser Mode.  This seems to be the same as IE7 mode except the user-agent string also says "Trident/5.0" (Trident is the IE layout engine).

A: In no way this will replace @mhenry1384's answer, but there is also a very good explanation of the differences on the MSDN blogs, more specifically this section:

and here a little more useful info:


text:
Q: Upload of JSON file using ForgeSDK, ObjectsAPI to Forge bucket failing I'm trying to take a set of file stored in one bucket and copy them to another (one is transient and one is temporary - the files are to be stored for a longer period of time). I'm using the NodeJS ForgeSDK, using getObject to download the file, then uploadObject to put it in the second bucket. This seems to work fine for most of the files I'm moving, but fails when I try to use it on a JSON file.
I've tried converting the JSON both to a buffer and to a string before the uploadObject call, both fail giving a gateway timeout error.
Any suggestions on how to make this work? Thanks!
static copyObjectToBucket(oAuth2TwoLegged, bucketName, copyToBucketName, objectName, access, callback) {
    console.log(bucketName, copyToBucketName, objectName);
    ObjectsApi.getObject(bucketName, objectName, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials())
    .then((resp) => {
            var headers = resp.headers;
            var contentLength = headers['content-length'];
            var body = resp.body;
            if (objectName.includes('json')){
                body = JSON.stringify(body[0]);
            }

            ObjectsApi.uploadObject(copyToBucketName, objectName, contentLength, body, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials())
            .then(
                (res) =>{
                    console.log(res);
                    callback;
                }
            )
            .catch((err) =>{
                console.log(err);
                }
            );
        })
}

A: There are certain restrictions when it comes to uploading files to the Forge Data Management service, however JSON files should not be an issue. Please try uploading your JSON file some other way, for example:

*

*using an HTTP client such as curl or postman

*using another Node.js SDK: https://github.com/petrbroz/forge-server-utils (disclaimer: it's my unofficial version of the Forge SDKs)

*using the VSCode Forge extension (disclaimer: this one's mine, too, using the library mentioned above :))

If you can upload the JSON using one of these tools, it might be an issue in the SDK. In that case please report a bug in https://github.com/Autodesk-Forge/forge-api-nodejs-client.
Btw. I have just tried uploading a JSON file using the VSCode extension and found no issues.


text:
Q: how to switch another tab when click table row There is two tab in my java swing interface. One tab has customer details table. I want to switch to the next other tab when I click a row of the table. Please help me. I tried this code.
        private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {
            int i = jtp.getSelectedIndex();
        jtp.setSelectedIndex(i == jtp.getTabCount() - 1 ? 0 : i + 1);

}

And I'm having exception.

  Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Tab count: 0

A:
"I want to switch to the next other tab when I click a row of the table."

What you want to do is add a ListSelectionListener to the table's selection model. When a row is selected, it will fire a ListSelectionEvent. You can just change the tab to whatever index you want it changed to from there.
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
     @Override
     public void valueChanged(ListSelectionEvent e) {
          if (e.getValueIsAdjusting()) {
               tabs.setSelectedIndex(tabs.indexOfTab("Other Panel"));
          }
     }
});

See How to Use Tables and How to Write ListSelectionListeners to learn more.
Full example
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class TableSelection {

    public TableSelection() {
        JTabbedPane tabPane = createTabPane();

        JFrame frame = new JFrame("Frame");
        frame.setContentPane(tabPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    private JTabbedPane createTabPane() {
        JTabbedPane pane = new JTabbedPane();
        JTable table = createTable(pane);
        pane.add(new JScrollPane(table), "Table Tab");
        JPanel panel1 = new JPanel();
        panel1.setBackground(Color.BLUE);
        pane.add(panel1, "Other Panel");
        return pane;
    }

    private JTable createTable(final JTabbedPane tabs) {
        String[][] data = {{"HELLO", "WORLD"}, {"HELLO", "WORLD"}};
        String[] cols = {"Hello", "World"};
        JTable table = new JTable(data, cols);
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    tabs.setSelectedIndex(tabs.indexOfTab("Other Panel"));
                }
            }
        });

        return table;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TableSelection();
            }
        });
    }
}


text:
Q: Order of Convergence when working with errors I am looking at the numerical solutions of a problem when using the boundary element method, the exact solution is 0.25
I have 3 errors corresponding to using 20,40 and 80 boundary elements.
I have seen online the order of convergence for discretisation methods uses formula:
$$ q = \frac{log(E_1/E_0)}{log(h_1/h_0)} $$
where $q$ is the order of convergence, $E_1 , E_0$ are the errors and $h_1,h_0$ are step sizes. I do not understand what the step sizes would be in this case.
I thought I would look at getting two values for q using error 1 and error 2 (using $h_1 =40, h_0 =20$) but I end up with a negative $q$ which doesn't make sense.


text:
Q: Does class and specialization affect starting locations? It seems to be understood that choosing a race impacts the probability of starting locations/climate, but does the same thing happen with your class and specialization? My friend plays an Air Master Sorcerer, and out of six attempts he always ended up in Arctic terrain. It could be a coincidence of course, but just wondering if anyone knows for sure, or based on a large number of games.

A: No, the climate has nothing to do with what race you pick, Its completely random.


text:
Q: Prove f'(a) is undefined when f(a) is undefined I've been asking myself how to prove that if $f(a)$ is undefined for a function, then $f'(a)$ is also undefined. I can't seem to find a proof that is generalised for any $f$. Here is what I got:
What I got
Let $f$ be any function undefined at  $a$, then
$f(a)\  \nexists$
Now, $f'(a) = \lim_{h\to 0} \frac{f(a+h) + f(a)}h$
Where I'm confused

*

*Do I only need to know that $f(a)$ is undefined to complete the proof?

*Is there a better way to write it?

I'm sorry I know it's kind of a simple question but it's been bugging me for a while and I couldn't find the answer anywhere and I'm really trying to work on being more rigorous in my understanding of maths.
Thank you!

A: By definition, to prove that a function is differentiable at $x=a $, you need compute the limit
$$\lim_{h\to 0}\frac {f (a+h)-f (a)}{h} $$
For this, you should know the value of $f (a) $.

A: Here's my rendition of the standard definition of the derivative, fully written out:

Suppose that $f$ is a function whose values are real numbers, and which is defined at a real number $a$, and on a neighborhood of $a$. The derivative of $f$ at $a$, $f'(a)$, is the limit
$$\lim_{h \to 0} \frac{f(a + h) + f(a)}{h},$$
if this limit exists.

If we have a function $f$ which is not defined at a real number $a$ (in other words, $f(a)$ is not defined), then the conditions for the definition of $f'(a)$ are not satisfied, and so the definition of $f'(a)$ does not apply (in other words, $f'(a)$ is not defined).

A: It's probably easier to think about this using contraposition. Your statement is equivalent to : If $f$ is differentiable at $a$, then $f$ is defined at $a$
To prove the equivalent statement, note that differentiability implies continuity, which implies $f$ being well-defined at point of differentiability.


text:
Q: manipulations with Taylor expansions for log and sinh How could we derive the equality
$$ \frac14 \sum_{m=1}^\infty \frac1m \frac{1}{\sinh^2 \frac{m\alpha}2} = - \sum_{n=1}^\infty n\log (1-q^n)$$
where $q=e^{-\alpha}$ ?

A: $$ \begin{align} \sum_{m=1}^{\infty} \frac{1}{m} \frac{1}{\sinh^{2} \frac{m \alpha}{2}} &=  \sum_{m=1}^{\infty} \frac{1}{m} \frac{4}{(e^{m \alpha /2}-e^{- m \alpha /2})^{2}} \\ &= 4 \sum_{m=1}^{\infty} \frac{1}{m} \frac{e^{-m \alpha }}{(1-e^{-m \alpha})^{2}} \\ &=4 \sum_{m=1}^{\infty} \frac{1}{m}\sum_{n=1}^{\infty} n(e^{-m \alpha})^{n} \tag{1} \\ &=4 \sum_{n=1}^{\infty} n \sum_{m=1}^{\infty} \frac{(e^{-\alpha n })^{m}}{m} \\ &= -4 \sum_{n=1}^{\infty} n \log(1-e^{- \alpha n}) \end{align}$$
$(1)$ If $|z| <1$, $ \displaystyle \sum_{n=1}^{\infty} nz^{n} = \frac{z}{(1-z)^{2}}$.


text:
Q: jQuery, onBeforeUnload and ASP.Net form I have the following solution for stopping the users from accidentally leaving my registration page:
var warning = true;

function CheckExit() {
    if (warning) {
        return "Changes done. Remember to save, blah blah.";
    }
}
window.onbeforeunload = CheckExit;

addToPostBack = function (func) {
    var old__doPostBack = __doPostBack;
    if (typeof __doPostBack != 'function') {
        __doPostBack = func;
    } else {
        __doPostBack = function (t, a) {
            if (func(t, a)) old__doPostBack(t, a);
        }
    }
};

$(document).ready(function () {

    $('#aspnetForm').submit(function () {
        warning = false;
        return true;
    });

    addToPostBack(function (t, a) {
        warning = false;
        return true;
    });

});

Most of this code is from different questions here on StackOverflow, and works just fine on my local debugging page; all ASP.Net controls (linkbuttons, buttons) can be clicked without a warning, but as soon as the user tries to close the window or navigate away, the warning is displayed.
However, when deployed to my server, the warning pops up when I click ASP.Net controls too (and I really do not want to warn the user that his changes isn't saved when he clicks the "Save" button). Now, there is a difference between my local debugging page and the server: the server uses a different MasterPage with some ads in it, but after debugging with Firebug (see next paragraph), I can't see how that should make a difference.
I have tried running different parts of the Javascript code by using Firebug to confirm that everything is loaded correctly (my first guess was that the section containing $('#aspnetForm') wasn't being loaded, since this seems to be the difference), but there is no improvement at all. The warning still pops up on every click of a link or a button.
My main problem is, I think, that I do not fully understand what the addToPostBack function does, and as such, I cannot properly debug it.
Is there anybody here who has any idea what might be wrong?

A: It's a guess, but you don't have the conventional anti-conflict device which goes
    (function ($) { code here })(jQuery);
so something might be conflicting with jQuery's definition of '$' which would stop the execution of the exception your code makes when someone is posting back.

A: I agree with James. Most of the time such type of conflict occurs. I will suggest with noConflict().
Happy Coding.


text:
Q: Is generating and concatenating 3 Math.random() values more random than 1 Math.random() value? I need to generate unique id's for multiple sentences in a longer narrative (where multiple users can be performing the same action, at the same time, on different machines).
I considered doing new Date().getTime() (and perhaps concatenating a username) but as the id's were generated in a loop whilst iterating over the sentences, I found duplicates were created (as generation could occur at the same millisecond).
So I am currently playing around with:
var random1 = Math.floor((Math.random() * 10000) + 1).toString(36);
var random2 = Math.floor((Math.random() * 10000) + 1);
var random3 = Math.floor((Math.random() * 10000) + 1);
var id = random1 + random2 + random3;
// generates things like:
// 1h754278042
// 58o83798349
// 3ls28055962

It occurred to me though (admittedly, as someone who has not pondered unique/random/crypto issues much), that perhaps joining three random numbers isn't any more random that one random number?
Is generating and concatenating 3 Math.random() values more random than 1 Math.random() value?
This answer (https://security.stackexchange.com/a/124003) states:

If the random generator really produces random data then it will not
  matter.

But I'm not sure how that applies to the usage of Math.random().
Edit:
Scenario is client side on web and not for security, just to ensure that each sentence has a unique id in the database.
Edit:
I ended up implementing:
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

var id = guid();

From: https://stackoverflow.com/a/105074/1063287
Also see comment on that answer:

Actually, the RFC allows for UUIDs that are created from random
  numbers. You just have to twiddle a couple of bits to identify it as
  such. See section 4.4. Algorithms for Creating a UUID from Truly
  Random or Pseudo-Random Numbers: rfc-archive.org/getrfc.php?rfc=4122

A: The only thing you change by concatenating 3 uniformly distributed random strings is a larger range of possible values.  The distribution is still uniform, so it's no more "random" but it does reduce the risk of collisions significantly.  The number of possible values would then by 36^12, or 4.7383813e+18.
You'd get the same effect by concatenating 12 base-36 digits (0-9,A-Z).

A: Math.random() returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy.
Here's V8's implementation:
uint32_t V8::Random() {

// Random number generator using George Marsaglia's MWC algorithm.
static uint32_t hi = 0;
static uint32_t lo = 0;

// Initialize seed using the system random(). If one of the seeds
// should ever become zero again, or if random() returns zero, we
// avoid getting stuck with zero bits in hi or lo by reinitializing
// them on demand.
if (hi == 0) hi = random();
if (lo == 0) lo = random();

// Mix the bits.
hi = 36969 * (hi & 0xFFFF) + (hi >> 16);
lo = 18273 * (lo & 0xFFFF) + (lo >> 16);
return (hi << 16) + (lo & 0xFFFF);
}

Source: http://dl.packetstormsecurity.net/papers/general/Google_Chrome_3.0_Beta_Math.random_vulnerability.pdf
In other words 3 random values ane not more 'random' than 1.

A: It's complicated.
Because of the specific way that you're using the random number generator, it is possible for the the first string to be the same while the second or third string are different.  This means that you produce more unique strings than you would get with just a single call to Math.random().  More unique strings implies fewer collisions, which is what you were aiming for.
To confirm this, simply dump a lot of these strings to a file and then sort them and see if the second and third values always change with the first value or if they can change independently (you'll need to add separators to the output to see that).
This is an artefact of the way PRNG state is hidden; and after a few appends it will stop working.  It should (no guarantees!) be after so many iterations that you won't be able to test it easily, so don't try to work it out empirically.
If you had a really primitive generator algorithm then you might find that whenever random1 was equal to X, then random2 would always be equal to Y and random3 would always be equal to Z; so if you had a collision at X, then implicitly Y and Z would also collide and so they wouldn't help.
But most PRNGs (and also the structure of your code as you take only 10000 distinct values from each call), have a state much larger than what they reveal in a single call.  This means that even if random1 is X, random2 and random3 are still completely unpredictable and the collisions are made less likely by their presence.
However, by the time you get to random100 you should start to see that you can guess what it's going to be based on the values of all the other randomXs and it won't be making the string any more unique.
Then the whole problem runs off down a rabbit hole of seed quality and state size.  Basically, it's plausible for the random number generator to be so weak that it can only produce as few as four billion unique strings, and probably far fewer in realistic situations.  The random() function wasn't intended to solve the GUID problem, so there's a risk that it will fail spectacularly at it.