text:
Q: Equivalent of objects.latest() in App Engine What would be the best way to get the latest inserted object using AppEngine ?
I know in Django this can be done using
MyObject.objects.latest()

in AppEngine I'd like to be able to do this
class MyObject(db.Model):
  time = db.DateTimeProperty(auto_now_add=True)

# Return latest entry from MyObject.
MyObject.all().latest()

Any idea ?

A: Your best bet will be to implement a latest() classmethod directly on MyObject and call it like
latest = MyObject.latest()

Anything else would require monkeypatching the built-in Query class.
Update
I thought I'd see how ugly it would be to implement this functionality.  Here's a mixin class you can use if you really want to be able to call MyObject.all().latest():
class LatestMixin(object):
    """A mixin for db.Model objects that will add a `latest` method to the
    `Query` object returned by cls.all(). Requires that the ORDER_FIELD
    contain the name of the field by which to order the query to determine the
    latest object."""

    # What field do we order by?
    ORDER_FIELD = None

    @classmethod
    def all(cls):
        # Get the real query
        q = super(LatestMixin, cls).all()
        # Define our custom latest method
        def latest():
            if cls.ORDER_FIELD is None:
                raise ValueError('ORDER_FIELD must be defined')
            return q.order('-' + cls.ORDER_FIELD).get()
        # Attach it to the query
        q.latest = latest
        return q

# How to use it
class Foo(LatestMixin, db.Model):
    ORDER_FIELD = 'timestamp'
    timestamp = db.DateTimeProperty(auto_now_add=True)

latest = Foo.all().latest()

A: MyObject.all() returns an instance of the Query class
Order the results by time:
MyObject.all().order('-time')

So, assuming there is at least one entry, you can get the most recent MyObject directly by:
MyObject.all().order('-time')[0]

or
MyObject.all().order('-time').fetch(limit=1)[0]


text:
Q: of which confusion I have serious problem with understanding stucture of the following "of which" sentences, especially the "of which's". Could anyone help me by rephrasing them in an explanatory way?

"But the press cannot expose that of which it is denied knowledge."

"The cause and that of which it is the cause go together."

A: The following rephrased sentences remove the of which phrasing but keep the essential meaning. I have tried to also keep a consistent pattern of rephrasing, and I've emphasized the changed words.

*

*But the press cannot expose that of which it is denied knowledge.→ But the press cannot expose what it is denied knowledge of.

*The cause and that of which it is the cause go together.→ The cause and what it is the cause of go together.

A: "But the press cannot expose that of which it is denied knowledge."

That of which it is denied knowledge --> what it does not (or cannot) know.

But the press cannot expose what it does not (or cannot) know.

"The cause and that of which it is the cause go together."

That of which it is the cause --> its effects

"The cause and its effects go together."

A: let me try :

*

*"But the press cannot expose that of which it is denied knowledge"
---> But the press cannot expose that which it (the press) is denied knowledge of.

*"The cause and that of which it is the cause go together."
---->The cause and that which it(the cause) is the cause of go together.

So the meaning of sentence is very obvious.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Login in to a web-based application using the "click" on VBS Our company uses a browser-based program for business operations. My goal is to be able to log into this system automatically.  The problem in front of me now is to be able to do click on one button using VBSript,
This is the code I have so far that take me to the point where I'm positioned over the button:
set WshShell = WScript.CreateObject("WScript.Shell")

call WshShell.Run("http://timeclock/portal/welcome.htm", 1, false)

WScript.Sleep 1000

WshShell.SendKeys "{ENTER}"

WScript.Sleep 2000

WshShell.SendKeys "username"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "password"

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{ENTER}"

WScript.Sleep 2000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"

WScript.Sleep 1000

WshShell.SendKeys "{ENTER}"

WScript.Sleep 4000

WshShell.SendKeys "EmployeeNumber"

WScript.Sleep 1000

WshShell.SendKeys "{TAB}"


text:
Q: openssl verify error:num=20:unable to get local issuer certificate I know theres a lot of answers for this question already but i've tried everything and I still cant get this to work. I'm just trying to get a https for my localhost working. any help/tips would be appreciated, thanks!
I'm running python 2.7 and OpenSSL 1.1.0f and MacOS 10.13 High Sierra.
What I've tried/know:

*

*I have my self signed root certificate in the keychain access marked
as always trust.

*From what I read, i understand error 20 means it can't find my root certificate, but its in my keychain access so im not sure where im missing

*I've also read about /etc/ca-certificates.conf, and making sure the certificate is in there, i've checked and it's not, but i've tried putting it there and updating ca-certificates & it hasn't worked either. from my understanding, having my root CA in keychain access should be enough?

*

*basically i have my self signed root cert in keychain & my key and cert in my python file but when i curl localhost i receive
curl: (60) SSL certificate problem: unable to get local issuer certificate
I've also tried all of these and i get the same output:
openssl s_client -connect localhost:5000
openssl s_client -connect localhost:5000 -CAfile rootCA.pem
openssl s_client -connect localhost:5000 -CApath /etc/ssl/certs/
Output:
openssl s_client -CApath /etc/ssl/certs/ -connect localhost:5000
CONNECTED(00000003)
depth=0 C = US, ST = California, L = San Fran, O = My org, OU = My unit, CN = localhost
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 C = US, ST = California, L = San Fran, O = My org, OU = My unit, CN = localhost
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:/C=US/ST=California/L=San Fran/O=My org/OU=My unit/CN=localhost
   i:/C=US/ST=California/L=San Fran/O=My org/OU=My unit/CN=localhost
---
Server certificate
-----BEGIN CERTIFICATE-----
certificate stuff...
-----END CERTIFICATE-----
subject=/C=US/ST=California/L=San Fran/O=My org/OU=My unit/CN=localhost
issuer=/C=US/ST=California/L=San Fran/O=My org/OU=My unit/CN=localhost
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: X25519, 253 bits
---
.
.
.
. other info....

    Start Time: 1530725381
    Timeout   : 7200 (sec)
    Verify return code: 21 (unable to verify the first certificate)
    Extended master secret: yes


text:
Q: How do you remove a "bad" installation of xboxdrv-ubuntu I tried to use XboxDRV-Ubuntu today.
I think the install is corrupted, because there is no joystick thing in the settings (worked quite a few days ago), joysticks aren't detected, etc. The application still runs, but doesn't seem to be complete compared to how it used to be. Installing it again says it's already installed and aborts.
Uninstallation: XboxDRV uninstalls successfully with
sudo apt-get purge xboxdrv

The following is output:
Reading package lists... Done
Building dependency tree
Reading state information... Done

The following packages were automatically installed and are no longer required:
  jstest-gtk linux-headers-3.13.0-32 linux-headers-3.13.0-32-generic
  linux-image-3.13.0-32-generic linux-image-extra-3.13.0-32-generic
  primus-libs socat
Use 'apt-get autoremove' to remove them.
The following packages will be REMOVED:
  ubuntu-xboxdrv* xboxdrv*
0 upgraded, 0 newly installed, 2 to remove and 0 not upgraded.
After this operation, 1,820 kB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 256045 files and directories currently installed.)
Removing ubuntu-xboxdrv (20140707-1) ...
stop: Unknown instance:
dpkg: error processing package ubuntu-xboxdrv (--purge):
 subprocess installed pre-removal script returned error exit status 1
dpkg: xboxdrv: dependency problems, but removing anyway as you requested:
 ubuntu-xboxdrv depends on xboxdrv.

Afterwards, I attempted to remove ubuntu-xboxdrv as follows:
sudo apt-get purge ubuntu-xboxdrv

The results I got were these:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  jstest-gtk linux-headers-3.13.0-32 linux-headers-3.13.0-32-generic
  linux-image-3.13.0-32-generic linux-image-extra-3.13.0-32-generic
  primus-libs socat
Use 'apt-get autoremove' to remove them.
The following packages will be REMOVED:
  ubuntu-xboxdrv*
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 71.7 kB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 255996 files and directories currently installed.)
Removing ubuntu-xboxdrv (20140707-1) ...
stop: Unknown instance:
dpkg: error processing package ubuntu-xboxdrv (--purge):
 subprocess installed pre-removal script returned error exit status 1
E: Sub-process /usr/bin/dpkg returned an error code (1)

After this, I typed
sudo apt-get autoremove

The results are excessively long to put in a block, so here's the output:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 ubuntu-xboxdrv : Depends: xboxdrv but it is not installed
E: Unmet dependencies. Try using -f.

Followed up with:
sudo apt-get autoremove -f

Results (Also too long to block with each line)
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following extra packages will be installed:
  xboxdrv
The following packages will be REMOVED:
  linux-headers-3.13.0-32 linux-headers-3.13.0-32-generic
  linux-image-3.13.0-32-generic linux-image-extra-3.13.0-32-generic
  primus-libs socat
The following NEW packages will be installed:
  xboxdrv
0 upgraded, 1 newly installed, 6 to remove and 0 not upgraded.
Need to get 0 B/663 kB of archives.
After this operation, 270 MB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 255996 files and directories currently installed.)
Removing linux-headers-3.13.0-32-generic (3.13.0-32.57) ...
Removing linux-headers-3.13.0-32 (3.13.0-32.57) ...
Removing linux-image-extra-3.13.0-32-generic (3.13.0-32.57) ...
Examining /etc/kernel/postrm.d .
run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.13.0-32-generic /boot/vmlinuz-3.13.0-32-generic
update-initramfs: Deleting /boot/initrd.img-3.13.0-32-generic
run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.13.0-32-generic /boot/vmlinuz-3.13.0-32-generic
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.13.0-35-generic
Found initrd image: /boot/initrd.img-3.13.0-35-generic
Found linux image: /boot/vmlinuz-3.13.0-34-generic
Found initrd image: /boot/initrd.img-3.13.0-34-generic
Found linux image: /boot/vmlinuz-3.13.0-32-generic
Found linux image: /boot/vmlinuz-3.13.0-35-generic
Found initrd image: /boot/initrd.img-3.13.0-35-generic
Found linux image: /boot/vmlinuz-3.13.0-34-generic
Found initrd image: /boot/initrd.img-3.13.0-34-generic
Found linux image: /boot/vmlinuz-3.13.0-32-generic
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
done
Removing linux-image-3.13.0-32-generic (3.13.0-32.57) ...
Examining /etc/kernel/prerm.d.
run-parts: executing /etc/kernel/prerm.d/dkms 3.13.0-32-generic /boot/vmlinuz-3.13.0-32-generic
dkms: removing: nvidia-331 331.38 (3.13.0-32-generic) (x86_64)

-------- Uninstall Beginning --------
Module:  nvidia-331
Version: 331.38
Kernel:  3.13.0-32-generic (x86_64)
-------------------------------------

Status: Before uninstall, this module version was ACTIVE on this kernel.

nvidia_331.ko:
 - Uninstallation
   - Deleting from: /lib/modules/3.13.0-32-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.

depmod.....

DKMS: uninstall completed.
Examining /etc/kernel/postrm.d .
run-parts: executing /etc/kernel/postrm.d/initramfs-tools 3.13.0-32-generic /boot/vmlinuz-3.13.0-32-generic
update-initramfs: Deleting /boot/initrd.img-3.13.0-32-generic
run-parts: executing /etc/kernel/postrm.d/zz-update-grub 3.13.0-32-generic /boot/vmlinuz-3.13.0-32-generic
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.13.0-35-generic
Found initrd image: /boot/initrd.img-3.13.0-35-generic
Found linux image: /boot/vmlinuz-3.13.0-34-generic
Found initrd image: /boot/initrd.img-3.13.0-34-generic
Found linux image: /boot/vmlinuz-3.13.0-35-generic
Found initrd image: /boot/initrd.img-3.13.0-35-generic
Found linux image: /boot/vmlinuz-3.13.0-34-generic
Found initrd image: /boot/initrd.img-3.13.0-34-generic
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
done
Removing primus-libs:amd64 (20131127-1~trustyppa1) ...
Removing socat (1.7.2.3-1) ...
Processing triggers for man-db (2.6.7.1-1) ...
Processing triggers for doc-base (0.10.5) ...
Processing 1 removed doc-base file...
Selecting previously unselected package xboxdrv.
(Reading database ... 226344 files and directories currently installed.)
Preparing to unpack .../xboxdrv_0.8.5-1_amd64.deb ...
Unpacking xboxdrv (0.8.5-1) ...
Processing triggers for man-db (2.6.7.1-1) ...
Setting up xboxdrv (0.8.5-1) ...

The end result: Now I have a still-broken xboxdrv installation, and no nvidea driver support.

A: You can get bluntly past this by just getting rid of the pre-removal script.  This is a last resort, but useful for dealing with broken packaging scripts, which seems to be the case here.
Instead of actually deleting the script, I'll post a command that merely renames the script, just for safety.
sudo mv /var/lib/dpkg/info/ubuntu-xboxdrv.prerm /var/lib/dpkg/info/ubuntu-xboxdrv.prerm.broken
After that, re-run the purge command: sudo apt-get purge ubuntu-xboxdrv
You may still get an error, but it should be a different one.  If that is the case, make sure to post the text of the new error message.
Additionally, it looks like there is a ppa for xboxdrv that may have a better package: https://launchpad.net/~rael-gc/+archive/ubuntu/ubuntu-xboxdrv
You may want to check that out after you get the current package removed.


text:
Q: 'NoneType' object is not callable error when trying to pull a number off webpage from bs4 import BeautifulSoup
import requests

url = 'https://app.wonderland.money/#/dashboard'
response = requests.get(url, timeout=5)
content = BeautifulSoup(response.content, "html.parser")

backing = content.findALL(attr={"class":"card-value"}).text
print(backing)

im trying to pull a specific number off a website, but I keep getting a 'TypeError: 'NoneType' object is not callable' error. Im not sure how to resolve it.

A: What happens?
Take a look in your soup there is no such class or element your looking for, cause content is provided dynamically and requests do not work the same way a browser does - It will not interpret javascript and render the website.
Possible solution
Try to use selenium instead to grab the page source.


text:
Q: How to delete a record from a jcombobox after using the record in another file? (java) For my current java project we are making a school application that lets supervisors be assigned to certain activities.
My activity file looks like this:
ID, Activity Name, Supervisor ID, Location, Time
My supervisor file looks like this:
Name, Specialization, EmailID, UUID
The supervisor ID and name are excerpted from supervisors file and placed in a JComboBox.
I need to remove the supervisor name and ID from the ComboBox after it has been assigned to an activity.
Thank you!


text:
Q: Can it be that two S.M.A.R.T. hard drives die at the same time? I have a PC with 2 S.M.A.R.T. drives, of different makes and age. Both started complaining about bad sectors this week and finally failed.
The PC didn't fall or something.
Can it be that it's a matter of a failing SATA controller or a power source?

A: I was right disbelieving in elves and anthropic principle.
It was an external factor: my BIOS was detecting both hard drives as "SMART bad", though only one of them was actually bad.
After disconnecting both and connecting a new good primary HDD, the secondary turned out to be good.


text:
Q: 'NoneType' object is not iterable For selection field in odoo 9 "Error"
 File "/home/tushar/odoo1/openerp/fields.py", line 1528, in get_values
    return [value for value, _ in selection]
TypeError: 'NoneType' object is not iterable
Stachtrace:
Odoo Server Error
Traceback (most recent call last):
  File "/home/tushar/odoo1/openerp/http.py", line 648, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/home/tushar/odoo1/openerp/http.py", line 685, in dispatch
    result = self._call_function(**self.params)
  File "/home/tushar/odoo1/openerp/http.py", line 321, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/home/tushar/odoo1/openerp/service/model.py", line 118, in wrapper
    return f(dbname, *args, **kwargs)
  File "/home/tushar/odoo1/openerp/http.py", line 314, in checked_call
    result = self.endpoint(*a, **kw)
  File "/home/tushar/odoo1/openerp/http.py", line 964, in __call__
    return self.method(*args, **kw)
  File "/home/tushar/odoo1/openerp/http.py", line 514, in response_wrap
    response = f(*args, **kw)
  File "/home/tushar/odoo1/addons/web/controllers/main.py", line 888, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/home/tushar/odoo1/addons/web/controllers/main.py", line 880, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
  File "/home/tushar/odoo1/openerp/api.py", line 250, in wrapper
    return old_api(self, *args, **kwargs)
  File "/home/tushar/odoo1/openerp/api.py", line 381, in old_api
    result = method(recs, *args, **kwargs)
  File "/home/tushar/odoo1/openerp/models.py", line 6028, in onchange
    record = self.new(values)
  File "/home/tushar/odoo1/openerp/api.py", line 248, in wrapper
    return new_api(self, *args, **kwargs)
  File "/home/tushar/odoo1/openerp/models.py", line 5595, in new
    record._cache.update(record._convert_to_cache(values, update=True))
  File "/home/tushar/odoo1/openerp/models.py", line 5490, in _convert_to_cache
    for name, value in values.iteritems()
  File "/home/tushar/odoo1/openerp/models.py", line 5491, in <dictcomp>
    if name in fields
  File "/home/tushar/odoo1/openerp/fields.py", line 1533, in convert_to_cache
    if value in self.get_values(record.env):
  File "/home/tushar/odoo1/openerp/fields.py", line 1528, in get_values
    return [value for value, _ in selection]
TypeError: 'NoneType' object is not iterable

I got This Error for dynamic selection for selection field in odoo. I provide the code I have done. Please help me out of this
from  openerp import models, fields, api
from test.test_support import temp_cwd

class scantech_laser_product_template(models.Model):
    _name='product.template'
    _inherit='product.template'

    values2=[('ECDS0','ECDS0'),('ECDS1','ECDS1'),('ECDS2','ECDS2')]
    main_category = fields.Selection([('SL0','SL0'),('SL1','SL1'),('SL2','SL2')],string="Main Category")

    @api.multi
    @api.depends("main_category")
    def _get_selection_name(self):
        if self.main_category == "SL0":
            return [("ESDS1","ESDS1")]

    sub_category = fields.Selection(selection=_get_selection_name,string="Sub Category")

When I am selecting the main category field it showing above error

A: The problem is that you're not returning a default value when your condition evaluates to false (and functions/methods in python that return nothing return None) so a workaround would be to do something like this
@api.multi
@api.depends("main_category")
def _get_selection_name(self):
    if self.main_category == "SL0":
        return [("ESDS1","ESDS1")]

    return [("default", "Default")] # can be anything you want as the default value

or you can make your selection field have a default value, which makes the condition to always evaluate to true and eliminates the need for a default return value in _get_selection_name
main_category = fields.Selection([('SL0','SL0'),('SL1','SL1'),('SL2','SL2')],string="Main Category", default="SLO")


text:
Q: System.Web.UI.Control howto use on a page I created a custom ASP.Net control:
namespace Chart2GoWeb.WebUI.UserControls
{
    public class NavigationBarControl : Control
    {
        protected override void Render(HtmlTextWriter output)
        {
            ...
        }
    }
}

Now it is time to use it on a aspx page.  I have tried adding:
<%@ Register Namespace='Chart2GoWeb.WebUI.UserControls' TagPrefix='c2gwwc'%>

to the page, and then used the control with this:
<c2gwwc:NavigationBarControl runat=server></c2gwwc:NavigationBarControl>

I am getting the error:
Parser Error Message: Unknown server tag 'c2gwwc:NavigationBarControl'.
How do I fix this?

A: c2gwwc should match the tag prefix TagPrefix="asp"
And shouldn't you extend WebControl and not Control? I'm not a pro but it doesn't look right.

A: replace your custom asp control markup with this
<asp:NavigationBarControl runat=server></asp:NavigationBarControl>

Updated Answer:
If You have created a custom server control, Then you have to add the dll of your custom server control to your project. You can also add custom server control to your Toobox, right click on tool box, Choose Control or some thing like that,a new popup window will open, select your dll, then the control will appear in the toolbox.

A: Wow, all I had to do was add 'Assembly="Chart2GoWeb.WebUI"' to the Register and it worked.  It would seem that it does not assume the current assembly.  Live and learn.  Thanks for everyone's help.


text:
Q: Accessing google cloud storage using hadoop FileSystem api From my machine, I've configured the hadoop core-site.xml to recognize the gs:// scheme and added gcs-connector-1.2.8.jar as a Hadoop lib. I can run hadoop fs -ls gs://mybucket/ and get the expected results. However, if I try to do the analogue from java using:
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
FileStatus[] status = fs.listStatus(new Path("gs://mybucket/"));

I get the files under root in my local HDFS instead of in gs://mybucket/, but with those files prepended with gs://mybucket. If I modify the conf with conf.set("fs.default.name", "gs://mybucket"); before obtaining the fs, then I can see the files on GCS.
My question is:
1. Is this expected behavior?
2. Is there a disadvantage to using this hadoop FileSystem api as opposed to the google cloud storage client api?

A: As to your first question, "expected" is questionable, but I think I can at least explain. When FileSystem.get() is used the default FileSystem is returned and by default that is HDFS. My guess is that the HDFS client (DistributedFileSystem) has code to prepend scheme + authority automatically to all files in the filesystem.
Instead of using FileSystem.get(conf), try
FileSystem gcsFs = new Path("gs://mybucket/").getFS(conf)

On disadvantages, I could probably argue that if you end up needing to access the object-store directly then you'll end up writing code to interact with the storage APIs directly anyways (and there are things that do not translate very well to the Hadoop FS API, e.g., object composition, complex object write preconditions other than simple object overwrite protection, etc).
I am admittedly biased (working on the team), but if you're intending to use GCS from Hadoop Map/Reduce, from Spark, etc, the GCS connector for Hadoop should be a fairly safe bet.


text:
Q: Failing to get textbox value in controller when trying to implement search in ASP.NET Core MVC I am trying to implement a search so I have a simple form with a textbox. I want to pass the value of the textbox to the controller so that I can begin the logic for my search but unfortunately when my put a breakpoint on my controller I see that the value of the string from the textbox is null and I am not sure why.
My Form:
  <form method="get" asp-action="Search" >

                    <input id="searchTerm" class="form-control" type ="text" @*asp-for="SearchTerm*@>

                        <button class="btn btn-primary" type="submit">
                            Search
                        </button>

            </form>

My Controller:
public IActionResult Search(IFormCollection Form)
{
    ViewBag.Name = Form["searchTerm"];
    return View();
}

A: Change form method to post and add a name property to the input tag
<input  type="text"  id="searchTerm" name="searchTerm" class="form-control" >


text:
Q: Java Server not receiving all data that's being sent by python client I am writing a Server Client application using TCP/IP. The issue is that my python client has a loop that runs 400 times sending 400 individual data. But only 23 datas are being received on the server side.
Here's the server java code which is basically in infinite loop reading as much as sent by client
  BufferedReader br = null;
  br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  str = br.readLine();

Here's the python client code that sends data
 for x in range (0, hmany):
        test =  "INSERT \t" + rstring(4) + " " + rstring(4) + " " + rdate() + "\n"
        client_socket.send(test)

rstring() and rdate() are just bunch of methods returning strings


text:
Q: CircleCI/Github pull request status not showing Not entirely sure if this is an appropriate place for this question but I'd like to get my pull requests to show the status of the CircleCI build but can't find any solid documentation on it. The two are integrated and the builds start running as soon as a PR is created. I found some docs that said I should go to Settings > Branches and then request that status checks pass before merging, but there are no options for CircleCI listed. Am I missing something obvious?

A: CircleCI Discuss would be the best place but I can try to answer here.
My first suggestion would be to redo the webhooks. By unfollowing and refollowing the project. This isn't the same issue but troubleshooting steps would be similar to: https://circleci.com/docs/2.0/workflows-waiting-status/


text:
Q: Understanding $PATH variable: Installed gems are not in path Good Morning!
I am working on ruby gem. So far, the gem has not been pushed to any server - all local development for now.
I would like to test out the gem as I build it (using TTD).  I have run bundle exe rake build and bundle exe rake install to build and install the gem in my local environment.  I now expect that when I type gem_name anywhere in my terminal that gem_name should be recognized. Unfortunately it isn't; instead I get this error:
    `$ -bash gem_name: command not found`

The only thing I can possible thing of that might be leading to this is some problem with my path.
Here is the output of my $PATH:
    echo $PATH
    /Users/throw/.rvm/gems/ruby-2.2.1/bin:
    /Users/throw/.rvm/gems/ruby-2.2.1@global/bin:
    /Users/throw/.rvm/rubies/ruby-2.2.1/bin:
    /usr/local:/usr/local/bin:
   /usr/local/sbin:/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:
   /usr/local/git/bin:/Users/throw/.rvm/bin:/Users/throw/.nvm/nvm.sh:
  /Users/throw/.node/bin:/Applications/Postgres.app/Contents/9.5.0.0/latest/bin

And here is the output of the command gem env:
    gem env
    RubyGems Environment:
      - RUBYGEMS VERSION: 2.5.1
      - RUBY VERSION: 2.2.1 (2015-02-26 patchlevel 85) [x86_64-darwin14]
      - INSTALLATION DIRECTORY: /Users/throw/.rvm/gems/ruby-2.2.1
      - USER INSTALLATION DIRECTORY: /Users/throw/.gem/ruby/2.2.0
      - RUBY EXECUTABLE: /Users/throw/.rvm/rubies/ruby-2.2.1/bin/ruby
      - EXECUTABLE DIRECTORY: /Users/throw/.rvm/gems/ruby-2.2.1/bin
      - SPEC CACHE DIRECTORY: /Users/throw/.gem/specs
      - SYSTEM CONFIGURATION DIRECTORY: /Users/throw/.rvm/rubies/ruby-2.2.1/etc
      - RUBYGEMS PLATFORMS:
        - ruby
        - x86_64-darwin-14
      - GEM PATHS:
         - /Users/throw/.rvm/gems/ruby-2.2.1
         - /Users/throw/.rvm/gems/ruby-2.2.1@global
      - GEM CONFIGURATION:
         - :update_sources => true
         - :verbose => true
         - :backtrace => false
         - :bulk_threshold => 1000
      - REMOTE SOURCES:
         - https://rubygems.org/
      - SHELL PATH:
         - /Users/throw/.rvm/gems/ruby-2.2.1/bin
         - /Users/throw/.rvm/gems/ruby-2.2.1@global/bin
         - /Users/throw/.rvm/rubies/ruby-2.2.1/bin
         - /usr/local
         - /usr/local/bin
         - /usr/local/sbin
         - /usr/bin
         - /usr/local/bin
         - /usr/bin
         - /bin
         - /usr/sbin
         - /sbin
         - /usr/local/git/bin
         - /Users/throw/.rvm/bin
         - /Users/throw/.nvm/nvm.sh
         - /Users/throw/.node/bin
         - /Applications/Postgres.app/Contents/9.5.0.0/latest/bin

Thus far, I think that gem_name path is included in my $PATH but I don't know ... am I missing something?
Below is the contents of gem_name.gemspec:
    # coding: utf-8
    lib = File.expand_path('../lib', __FILE__)
    $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
    require 'instructortools/version'

    Gem::Specification.new do |spec|
      spec.name          = "instructortools"
      spec.version       = Instructortools::VERSION
      spec.authors       = ["Throw"]
      spec.email         = ["throw@gmail.com"]

      spec.summary       = %q{The command line interface instructor tools}
      spec.homepage      = "https://github.com/throw/instructortools-gem"
      spec.license       = "MIT"

      # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
      # delete this section to allow pushing this gem to any host.
      if spec.respond_to?(:metadata)
        spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
      else
        raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
      end

      spec.files         = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
      spec.bindir        = "exe"
      spec.executables   = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
      spec.require_paths = ["lib"]

      spec.add_development_dependency "bundler", "~> 1.11"
      spec.add_development_dependency "rake", "~> 10.0"
      spec.add_development_dependency "rspec", "~> 3.0"
      spec.add_development_dependency "pry"

      spec.add_runtime_dependency "thor"
    end

I have an exe directory that has the following line:
    #!/usr/bin/env ruby

    require "instructortools"

    Instructortools::CLI.start(ARGV)

Thank you!

A: You should mention your executable in gemspec like so:
spec.bindir "exe"
spec.executables ["your_script_name"]

So that upon install rubygems copies it into /Users/throw/.rvm/gems/ruby-2.2.1/bin which is on $PATH
EDIT:
Your gemspec gets file list from git ls-files, so all files should be commited before gem build to be included in gem.


text:
Q: Method not allowed error when attempting to get session data with Flask I'm trying to build a test app, and am getting a 405 error when I attempt to navigate to my submitted_form page. My code is as follows:
from flask import Flask, render_template, session, redirect, url_for, flash
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)

class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name is not None and old_name != form.name.data:
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        print session['name']
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))

@app.route('/submitted_form/', methods=['GET, POST'])
def submitted_form():
    name = session.get('name')
    print name
    return render_template('submitted_form.html', name=name)

if __name__ == '__main__':
    manager.run()

I am trying to have it print the name variable, which I thought I was storing as a session variable.
My submitted_form.html template is as follows:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %}

Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!

{% endblock %}

A: @app.route('/submitted_form/', methods=['GET, POST'])

Should be
@app.route('/submitted_form/', methods=['GET', 'POST'])

Otherwise it thinks your method is 'GET, POST' and when a POST comes in it rejects it, hence the 405 Method Not Allowed.


text:
Q: my icon disappears when using navbar-fixed with materialize my icon disappears when using navbar-fixed with materialize, but if I not use fixed my icon exists
with navbar :

with navbar-fixed :

A:

            MBS EFAKTUR

search

view_module

refresh

more_vert

strong text


text:
Q: How to count number of retweets and update database accordingly? Consider the following tables:
tweets                                retweets
----------------------------------    --------------------
id  id_str             retweet_cnt    id id_str
----------------------------------    --------------------
1   46604457684901888                 1  46604457684901888
2   46556513103388672                 2  46604457684901888
3   46294368197427200                 3  46604457684901888
                                      4  46556513103388672
                                      5  46556513103388672

I would like to UPDATE tweets.retweet_cnt by counting for each (varchar) id_str how many times it occurs in retweets. Can anybody help me with the query for this? Important: it is possible for in id_str not to appear in retweets (as as the case with 46294368197427200 in the example). In that case, zero (0) should be returned.
Any help is appreciated.

A: You can use an UPDATE on tweets and join in the retweet counts per id:
update tweets t
left join (select id_str, count(id) as id_count
           from retweets r group by id_str) r
  on r.id_str = t.id_str
set t.retweet_cnt = coalesce(r.id_count, 0);

Demo: http://www.sqlfiddle.com/#!2/38e98/1

A: SELECT t.id_str, COUNT(r.id)
FROM tweets t
  LEFT JOIN retweets r
  ON t.id_str = r.id_str
GROUP BY t.id_str


text:
Q: List available artifacts from repo with gradle, ivy or other I'm looking for a way to list all available artifacts programmatically for given repo url, group and artifact. The repo is maven-based.
I know about maven-metadata.xml but the repo that is in use doesn't provide classifier details which are crucial for me.
Solution may be based on ivy, gradle or other compatible tools. If anybody has an idea please let mi know :)
I hope to find a code sample that will allow me to browse repo in an easy and friendly way.

A: Use the search features of your Maven repository manager.
If you're using Nexus, it supports searches of it's Lucene index. For example the following URL returns all the artifacts matching the string "log4j":

*

*https://repository.sonatype.org/service/local/lucene/search?q=log4j
The response is verbose but includes information like classfiers (which is what you're looking for)

A: maven-metdata.xml only has module information, and classifier belongs to artifact (not module). Gradle is probably not a good fit here. I'd consider a low-level approach with some GET requests and HTML parsing. In case the repository is backed by a repository manager such as Artifactory and Nexus, their REST API might also be an option.

A: Thanks guys for all hints. Yesterday I've managed to solve the problem using artifactory REST search API and parsing the incoming JSON respones. Thanks once again.


text:
Q: Elegant way to make site temporarily unavailable? Do You know elegant way to make site temporarily unavailable?
Any configuration or settings for this?

A: In IIS you can put a app_offline.htm
http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx
In others web servers check the manual or use a script to rename the index to a backup name and then rename the offline page to index and vice versa...
You could also create an 'inactive' file, the 'inactive' file will be checked for existence when pages are loading. If the content is found then you can abort logic.
E.g. in php you would include the following line (via an include inter alia)
<?php if(file_exists('/path/to/OffLine.file')) die('The Application is currently Offline! Please try again in a few minutes...'); ?>

If you wanted this @ the box level you would add the function to the PHP.ini... see http://uk.php.net/manual/en/ini.core.php#ini.auto-prepend-file
To set a PHP.ini per site see https://serverfault.com/questions/34078/how-do-i-set-up-per-site-php-ini-files-on-a-lamp-server-using-namevirtualhosts
The same is obviously possible in other languages.
I have a particular script which does some patching and actually creates this file for me... see Custom app_offline.htm file during publish

A: Actually, there is a mechanism already to do it, out of the box.
You can find a post about it here.
Basically you have to include an App_Offline.htm in the root of your site, and IIS will bring down the site until that file is removed.


text:
Q: Does #pragma once add inclusion guards? #pragma once is not standard, but is supported by compilers like gcc and VC++. It helps to avoid inclusion guards.
But, internally, does the compiler add inclusion guards for #pragma once? If not, how does the compiler ensure that such a header is included only once?

A: I'm sure it works just like include_once in PHP - there is a table of "files that has been included". The compiler, in this case, looks in the list for the file it is about to include and if a file has already been included, don't include it again. If the compiler, while processign the file, sees a #pragma once, then add this file to "files that have already been included".
So it's not the same as inclusion guards on a detail level, but it has the same effect as inclusion guards. It also makes the code less portable, since there are plenty of compilers that doesn't support this.

A: No, the compiler will not add include guards, but that should not matter, as it won't include the same file again, so it would never get a change to evaluate those guards in the first place.

A: When adding "#pragma once" to file "file.h",the compiler help us ensure the "file.h" will only be opened noce.
But if I have a duplication of "file.h" named "file_copy.h",if it is included, it will be opened.


text:
Q: Substituir conteúdo de uma tabela por outra? O meu caso é o seguinte:
Tenho duas tabelas TAB1 e TAB2; as duas tabelas têm a mesma estrutura: (id, nome, apelido).
Gostaria de substituir o conteúdo da TAB1 para a TAB2. Tudo que existe na TAB2 deve ser apagado e substituído pelo conteúdo da TAB1.
Gostaria também de fazer este processo apenas numa requisição ao banco de dados.
Como posso fazer isso?

A: truncate table tab2;
insert into tab2 (SELECT * FROM tab1);

A: Não está claro se quer saber somente os comandos SQL ou se quer criar a conexão com um script PHP.
Portanto, de uma forma genérica,
Primeiro exclua os dados existentes:
DELETE FROM TAB2;
Em seguida execute INSERT INTO TAB2 (SELECT * FROM TAB1);
Pode fazer isso usando um MySQL front-end como o PHPMyAdmin.

*imagem ilustrativa
Não pode fazer as suas queries ao mesmo tempo pois o MySQL impede queries múltiplas por definição padrão. É possível mudar esse padrão mas implica em questões de segurança.
Importante relevar que se for apenas substituir os dados de uma tabela com os dados de outra tabela poderia apenas aplicar o REPLACE INTO, sem uso do truncate ou do delete.
REPLACE INTO TAB2 (SELECT * FROM TAB1)

Só isso já basta.
Mas para um caso específico onde quer limpar "vestígios" da tabela TAB2 que não existem em TAB1, o melhor mesmo é excluir tudo antes de proceder com o INSERT.


text:
Q: EEPROM not writing data properly Atmega32 C I have a program that reads temperature and pressure sensors and does internal ADC conversion on them, then save data to the EEPROM, then convert back to original value and display it on the LCD. The issue is that when I debug the program in Atmel, it seems to work fine. But, the code doesn't actually on my circuit. IT seems to only write and read the first 2 bytes properly, then just writes the same byte over and over.
Here's my code for writing data. I'm using the included eeprom.h library, and writing a 16-bit value by splitting to lower and higher bytes.
void WriteToEEPROM(uint16_t value, int address){

    uint8_t low_value = value;
    uint8_t high_value = (value & 0xFF00) >> 8;
    if ((address == 0) || (address == 100)){}
    else {address++;}

    while(!eeprom_is_ready()){}
    eeprom_write_byte((uint8_t*)address, low_value);
    while(!eeprom_is_ready()){}
    address++;
    eeprom_write_byte((uint8_t*)address, high_value);
    while(!eeprom_is_ready()){}
}

This is the contents of the EEPROM after finishing writing values. Note that the value should not change because I'm keeping it constant. Correct values should be 0x134 at '0x0000' and 0x0073 at 0x0064. I'm lost on why this is not working.
Any help is appreciated!

full code
#define __DELAY_BACKWARD_COMPATIBLE__
#define F_CPU 8000000UL
#define  eeprom_is_ready()
#include <avr/io.h>
#include <avr/delay.h>
#include <stdint.h>
#include <avr/eeprom.h>
#include <stdio.h>

//******************LCD PROGRAM STARTS*********************//
#define LCD_DATA PORTD  // port D is selected as LCD data port
#define ctrl PORTC  // port C is selected as LCD command port
#define en PC2  // enable signal is connected to port D pin 7
#define rw PC1  // read/write signal is connected to port D pin 6
#define rs PC0  // register select signal is connected to port D pin 5

void LCD_cmd(unsigned char cmd);
void init_LCD(void);
void LCD_write(unsigned char data);
void LCD_write_string(char*str);
void WriteToEEPROM(uint16_t value, int address);

void scaled_delay(int delay){
    _delay_ms(delay * 1000);
}

void setup(void){
     DDRA = 0x00;               //PORTA is set as an input
     DDRD = 0xFF;               //PORTD is set as an output
     DDRC = 0xFF;
}

//Temperature sensor output connected to PA0
void ReadTemp(int address){

    ADCSRA = ADCSRA | 0b10000111;       //enable ADC, CLK/128 conversion speed
    ADMUX  = ADMUX | 0b01000000;        //Use internal 2.56V Vref and PA0 as input, right-hand justified

    ADCSRA |= (1 << ADSC);              //start conversion

    while(!(ADCSRA & (1 << ADIF))) {}

    WriteToEEPROM(ADC, address);
}

//Temperature sensor output connected to PA1
void ReadPressure(int address){

    ADCSRA = ADCSRA | 0b10000111;       //enable ADC, CLK/128 conversion speed
    ADMUX  = ADMUX | 0b01000001;        //Use AVCC and PA0 as input, right-hand justified

    ADCSRA |= (1 << ADSC);              //start conversion

    while(!(ADCSRA & (1 << ADIF))){}        // wait until process is finished
    address = address + 100;
    WriteToEEPROM(ADC, address);
}

void WriteToEEPROM(uint16_t value, int address){

    uint8_t low_value = value;
    uint8_t high_value = (value & 0xFF00) >> 8;
    if ((address == 0) || (address == 100)){}
    else {address++;}

    while(!eeprom_is_ready()){}
    eeprom_write_byte((uint8_t*)address, low_value);
    while(!eeprom_is_ready()){}
    address++;
    eeprom_write_byte((uint8_t*)address, high_value);
    while(!eeprom_is_ready()){}
}

void ReadEEPROM_Temp(uint8_t address){

    uint8_t temp_value_low;
    uint8_t temp_value_high;

    char value_buffer_temp[100] = "";

    if(address != 0) {address++;}

    temp_value_low = eeprom_read_byte((uint8_t*)address);
    address++;
    temp_value_high = eeprom_read_byte((uint8_t*)address);

    uint16_t temp_value = (temp_value_high << 8) | temp_value_low;
    int temperature = (temp_value * 4.88) / 10;

    sprintf(value_buffer_temp,"%s %d %s  ", "Temp ", temperature, "C");

    init_LCD();
    LCD_cmd(0x0C);
    _delay_ms(100);

    LCD_write_string(value_buffer_temp);
}

void ReadEEPROM_Pres(uint8_t address){

    uint8_t pres_value_low;
    uint8_t pres_value_high;

    char value_buffer_pres[100] = "";

    if(address != 100) {address++;}

    pres_value_low = eeprom_read_byte((uint8_t*)address);
    address++;
    pres_value_high = eeprom_read_byte((uint8_t*)address);

    uint16_t pres_value = (pres_value_high << 8) | pres_value_low;
    int v_out =  (pres_value * 4.88)/1000;
    int pressure = ((v_out/5.1) + 0.095) / 0.009;

    sprintf(value_buffer_pres,"%s %d %s  ", "Pres ", pressure, "kPa");
    LCD_cmd(0xC0);
    _delay_ms(100);
    LCD_write_string(value_buffer_pres);
}

void init_LCD(void){
    LCD_cmd(0x38);
    // initialization in 8bit mode of 16X2 LCD
    _delay_ms(1);
    LCD_cmd(0x01);
    // make clear LCD
    _delay_ms(1);
    LCD_cmd(0x02);
    // return home
    _delay_ms(1);
    LCD_cmd(0x06);
    // make increment in cursor
    _delay_ms(1);
    LCD_cmd(0x80);
    // "8" go to first line and "0" is for 0th position
    _delay_ms(1);
    return;
}

//**************sending command on LCD***************//

void LCD_cmd(unsigned char cmd){

    LCD_DATA = cmd; // data lines are set to send command
    PORTC   &= ~(1<<rs);    // RS sets 0
    PORTC   &= ~(1<<rw);    // RW sets 0
    PORTC   |= (1<<en); // make enable from high to low
    _delay_ms(100);
    PORTC   &= ~(1<<en);
    return;
}

//*****************write data on LCD*****************//

void LCD_write(unsigned char data){

    LCD_DATA=   data;   // data lines are set to    send command
    PORTC   |=  (1<<rs);    // RS sets  1
    PORTC   &=  ~(1<<rw);   //  RW sets 0
    PORTC   |=  (1<<en);    //  make enable from high   to low

    _delay_ms(100);

    PORTC &= ~(1<<en);

    return ;
}
//store address value of the string in pointer *str
void LCD_write_string(char *str) {

    int i=0;

    for(i; str[i]!=0; i++){
        // loop will go on till the NULL character in the string
        LCD_write(str[i]); // sending data on LCD byte by byte i++;
    }
    return;
}

int main(void)
{
    setup();
    int counter = 0;
   while (1)
   {
        scaled_delay(1);            //delay 1 hour
        ReadTemp(counter);          //get temperature reading
        ReadPressure(counter);      //get pressure reading
        counter++;                  //keep track of number of conversions
        //get reading 24 times
        if(counter == 23){
            counter = 0;
            while (counter  != 24)
            {
                ReadEEPROM_Temp(counter);
                ReadEEPROM_Pres(counter + 100);
                counter++;
            }
            counter = 0;
        }
   }
}

A: There seems to be a mistake in the address variable. It is of type int but should be of type unsigned int (address can not be negative). Can you try the following code:
void WriteToEEPROM(unsigned int value, unsigned int address)
{
  unsigned char low_value = (unsigned char)value;
  unsigned char high_value = (unsigned char)(value>>8);

  eeprom_write_word((unsigned char*)address ,value);
  address++;
  address++;
}

Pleas also change the delay.h path to
#include <util/delay.h>

The read function maybe contains also some unnecessary stuff:
void ReadEEPROM_Temp(unsigned int address)
{
  char buffer[100];

  unsigned int temp = eeprom_read_word((unsigned char*)address) * 4.88 / 10UL;
  address++;
  address++;

  sprintf(buffer,"Temp %5d C", temp);

  init_LCD();
  LCD_cmd(0x0C);
  _delay_ms(100);

  LCD_write_string(buffer);
}

WARNING:

It is possible that your EEPROM is currently destroyed cause of you are writing several times to same addresse space in your main routine:

while (1)
{
  scaled_delay(1);            // !!!THIS CREATES A DELAY OF 1 SECOND
  ReadTemp(counter);          // WRITE DATA TO EEPROM
  ReadPressure(counter);      // WRITE DATA TO EEPROM
// ...

Normaly if your functions are above the main routine it is not necessary to declare prototypes. Are you developing with Atmel Studio?

A: Try using an EEPROM clear program and retry running your program.


text:
Q: Jquery UI Accordion - no vertical scrollbar inside a pane content I use a JQuery UI Dialog with an accordion and now I'm trying to show a vertical scrollbar on with ajax loaded content inside a pane. The problem is, that the scrollbar is not appearing on an Ipad. The problem exists only on IOS-Systems (Android not tested).
Here is the initialization part of the accordion:
var uiAccIcons = { header: "ui-icon-circle-arrow-e"
                 , headerSelected: "ui-icon-circle-arrow-s" };

$("#uiAccordion").accordion({
   autoHeight: true,
   icons: uiAccIcons
 });


text:
Q: android fatal error at - URL_REGISTER, new Response.Listener Coding android app registration module for the first time, getting a fatal error while running App after entering the mobile number during registration function & there is no request reaching to backend web-server -
Code is as below :
private void registerUser(final String name, final String MobileNo) {

        final String TAG = "MY_TAG";

       String tag_string_req = "req_register";
       StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_REGISTER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {

              Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
                DialogOTP dialogOTP= new DialogOTP();
                dialogOTP.show(getFragmentManager(),"DialogOTP");

                    } else {

                          String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                  Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("MobileNo", MobileNo);
                 return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

wherein, AppConfig.java refers to the url for the backend .php code i.e. -
public class AppConfig {
    // Server user login url
    public static String URL_LOGIN = "http://testing.co.in/android/login.php";

    // Server user register url
    public static String URL_REGISTER = "http://testing.co.in/android/register.php";

*

*Register.php exists an the required url path

Can someone suggest how to make out the exact problem in syntax or what can be the root cause ?
Pls Find below the extact from LogCat  -
11-22 20:24:01.690  18539-18539/com.android4dev.navigationview D/AndroidRuntime﹕ Shutting down VM
11-22 20:24:01.690  18539-18539/com.android4dev.navigationview W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4156a930)
11-22 20:24:01.700  18539-18539/com.android4dev.navigationview E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.abc.abc.activity.MobileVerification.registerUser(MobileVerification.java:243)
            at com.abc.abc.activity.MobileVerification.access$100(MobileVerification.java:36)
            at com.abc.abc.activity.MobileVerification$1.onClick(MobileVerification.java:92)
            at android.view.View.performClick(View.java:4439)
            at android.widget.Button.performClick(Button.java:139)
            at android.view.View$PerformClick.run(View.java:18395)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5317)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)
11-22 20:24:01.790    2246-2344/? W/SignalStrength﹕ Size of signalstrength parcel:56


text:
Q: Beaglebone / Yocto / Kernel configuration I want to change Kernel configuration.
I have my own layer created and inside my layer I have a _%.bbappend file which directly targets the recipe linux-ti-staging.bb (link). This recipe builds my kernel:
ziga@host:~/yocto/$ oe-pkgdata-util lookup-recipe kernel
linux-ti-staging

The recipe is part of the official layer meta-ti (link).
My layer looks like this:
002--layers/meta--001/
├── conf
│   ├── distro
│   │   └── distro.conf
│   ├── layer.conf
│   └── machine
│       └── photovolt.conf
├── recipes-all
│   ├── application
│   │   └── application.bb
│   ├── image-003
│   │   └── image-003.bb
│   └── qtbase
│       └── qtbase_%.bbappend
├── recipes-bsp
│   └── u-boot
│       ├── u-boot-ti-staging
│       │   ├── 0001--add-fotovolt-dts-to-makefile.patch
│       │   └── photovolt.dts
│       └── u-boot-ti-staging_%.bbappend
└── recipes-kernel
    └── linux
        ├── linux-ti-staging
        │   ├── 0001--add-photovolt-dts-to-makefile.patch
        │   ├── 0002--disable-hdmi-node.patch
        │   ├── 0003--remove-conflicting-mmc-pinmuxing.patch
        │   ├── defconfig
        │   ├── fragment.cfg
        │   └── photovolt.dts
        └── linux-ti-staging_%.bbappend

I tried to follow the official Yocto reference (link) to configure my _%.bbappend file in one of the two ways described there.
1st  - using configuration fragment
First, I tried to use a Linux kernel fragment. I executed:
ziga@host:~/yocto/$ bitbake -c menuconfig linux-ti-staging

made my configuration in kconfig/curses interface and saved the configuration under a default name .config. Then I created a Linux configuration fragment:
ziga@host:~/yocto/$ bitbake -c diffconfig linux-ti-staging

Fragment was created and it looks like this:
ziga@host:~/yocto/$ cat 003--builds/001--fotovolt/tmp/work/fotovolt-poky-linux-gnueabi/linux-ti-staging/5.10.65+gitAUTOINC+dcc6bedb2c-r22b/fragment.cfg
CONFIG_TOUCHSCREEN_ST1232=y

I copied this fragment to my layer as can be seen from the first code snippet. Now according to the official reference I also created the linux-ti-staging_%.bbappend (is detected by bitbake-layers) with this content:
FILESEXTRAPATHS:prepend := "${THISDIR}/linux-ti-staging:"
SRC_URI += "file://fragment.cfg"

I hoped that Yocto might treat a fragment.cfg file similar as patches, but it didn't do anything.

2nd - using an entire configuration
Secondly, I tried to use an entire Linux kernel configuration. I executed:
ziga@host:~/yocto/$ bitbake -c menuconfig linux-ti-staging

made my configuration in kconfig/curses interface and saved the configuration under a diferent name i.e. defconfig (7234 lines):
ziga@host:~/yocto/$ wc -l 003--builds/001--fotovolt/tmp/work/fotovolt-poky-linux-gnueabi/linux-ti-staging/5.10.65+gitAUTOINC+dcc6bedb2c-r22b/build/.config
7234

I copied this defconfig in my layer as can be seen from the first fragment of code. I then edited my linux-ti-staging_%.bbappend acccording to the official Yocto reference manual like this:
FILESEXTRAPATHS:prepend := "${THISDIR}/linux-ti-staging:"
SRC_URI += "file://defconfig"
KCONFIG_MODE = "alldefconfig"

But this also did not work.

I cleaned before building
In both cases I used two commands to cleanly build everything:
bitbake -c cleansstate virtual/kernel
bitbake image-003

But this does absolutely nothing to the kernel configuration. I can verify that no changes were applied by (a) logging in a running target, (b) extracting the /proc/config.gz somewhere and (c) read the obtained config  file. File is identical as it was...
So, how can I permanently modify the kernel configuration?

Machine
My MACHINE is defined in photovolt.conf which basically reuses machine beaglebone (link) from official layer meta-ti. It looks like this:
#@TYPE: Machine
#@NAME: Photovolt machine - Beaglebone based machine
#@DESCRIPTION: Machine configuration for my machine

require conf/machine/beaglebone.conf

KERNEL_DEVICETREE = "photovolt.dtb"
UBOOT_MACHINE = "photovolt_defconfig"

Distribution
Distribution that I use is defined in a distro.conf like this:
require conf/distro/poky.conf

DISTRO = "distro"
DISTRO_NAME = "Distro (Yocto derived GNU/Linux distribution)"
DISTRO_VERSION = "1.0.0"
DISTRO_CODENAME = "Heart I"
MAINTAINER = "Me <me.me@gmail.com>"

DISTRO_FEATURES:append = " systemd"
DISTRO_FEATURES_BACKFILL_CONSIDERED = "sysvinit"
VIRTUAL-RUNTIME:init_manager = "systemd"
VIRTUAL-RUNTIME:initscripts = ""

PREFERRED_PROVIDER:virtual/libgbm = "mesa"

Recipe looks weird
Recipe linux-ti-stagging.bb (link) looks simple at a first glance, but it does some fishy things. It first requires a setup-defconfig.inc (link) which has a task do_configure(). Here it does some copy operations where it also uses a weird defconfig file (link). Maybe this is somehow connected to my problems...

A: It is obvious in setup-defconfig.inc that they handle config fragments in do_configure with this part:
# Fourth, handle config fragments specified in the recipe
    # The assumption is that the config fragment will be specified with the absolute path.
    # E.g. ${WORKDIR}/config1.cfg or ${S}/config2.cfg
    if [ -n "${KERNEL_CONFIG_FRAGMENTS}" ]
    then
        for f in ${KERNEL_CONFIG_FRAGMENTS}
        do
            # Check if the config fragment is available
            if [ ! -e "$f" ]
            then
                echo "Could not find kernel config fragment $f"
                exit 1
            fi
        done
    fi

    # Now that all the fragments are located merge them
    if [ -n "${KERNEL_CONFIG_FRAGMENTS}" -o -n "$configfrags" ]
    then
        ( cd ${WORKDIR} && ${S}/scripts/kconfig/merge_config.sh -m -r -O ${B} ${B}/.config $configfrags ${KERNEL_CONFIG_FRAGMENTS} 1>&2 )
        yes '' | oe_runmake -C ${S} O=${B} oldconfig
    fi

So, here is the explanation of what it does:

*

*It checks if the variable KERNEL_CONFIG_FRAGMENTS has a content

*If yes, it checks if its content (files) exist

*Merge all config fragments of and KERNEL_CONFIG_FRAGMENTS and configfrags into ${B}/.config which is the final configuration that will be built

configfrags just used to hold extracted fragments from other defconfig file. It does not matter for your case.
So, here what you can do in linux-ti-staging_%.bbappend:
FILESEXTRAPATHS:prepend := "${THISDIR}/files:"
SRC_URI += "file://fragment.cfg"
KERNEL_CONFIG_FRAGMENTS += "${WORKDIR}/fragment.cfg"

Since they are checking directly on the content of KERNEL_CONFIG_FRAGMENTS it will fail if you set it without ${WORKDIR}.
${WORKDIR} is where fragment.cfg will be unpacked.
So, based on what they are using on do_configure, the test on KERNEL_CONFIG_FRAGMENTS should pass because it will have content, and it will merge its config into the configuration file ${B}/.config.
To check that, after do_configure just check the content of ${B}/.config for your new fragment content.
ALERT
YOU NEED TO LEFT THE FIRST LINE IN THE FRAGMENT FILE AS EMPTY LINE. BECAUSE merge_config.sh WILL SKIP IT.
So, your fragment will look like the following:

CONFIG_TOUCHSCREEN_ST1232=y

If that did not work, try to add this custom function to apply your fragment.cfg into the final configuration file:

*

*linux-ti-staging_%.bbappend:

FILESEXTRAPATHS:prepend := "${THISDIR}/files:"
SRC_URI += "file://fragment.cfg"

CUSTOM_FRAGMENTS += "fragment.cfg"

do_merge_fragment(){
   for f in ${CUSTOM_FRAGMENTS}; do
       if [ -f "${WORKDIR}/${f}" ]; then
           ${S}/scripts/kconfig/merge_config.sh -m ${B}/.config ${WORKDIR}/${f}
       fi
   done
}

addtask merge_fragment after do_configure before do_compile

With that you will make sure that the fragment will be applied.

A: Your directory structure should be like this
meta-something
└── recipes-kernel
    └── linux
        ├── files
        │   └── defconfig
        └── linux-ti-staging.bbappend

And linux-ti-staging.bbappend
FILESEXTRAPATHS:prepend := "${THISDIR}/files:"
SRC_URI += "file://defconfig"


text:
Q: Session key for IOS I am developing an iOS app, and i want to access the currently logged in user's session key logged in onto the device. Is it possible to get session key of logged in user, in iOS?

A: You can get the token and expiration date. Why would you want that information?


text:
Q: Why may Squid give a MISS? I do a request to my Squid through CloudFront and receive a miss:
< content-type: text/html
< date: Thu, 17 Mar 2022 08:22:46 GMT
< server: Apache/2.4.48 (Ubuntu)
< cache-control: max-age=3153600000, public, only-if-cached, immutable
< last-modified: Thu, 01 Jan 1970 00:00:00 GMT
< x-cache-lookup: MISS from ip-172-31-68-17:3128
< via: 1.1 ip-172-31-68-17 (squid/4.13), 1.1 c929a0b0be95dbd556dd38270accc062.cloudfront.net (CloudFront)
< content-security-policy: default-src * 'unsafe-eval' 'unsafe-inline' 'unsafe-dynamic' data: blob: ws: wss:; img-src http: https: data: mediastream: 'unsafe-eval' 'unsafe-hashes' 'unsafe-inline' blob: ws: wss:; frame-ancestors 'self'; frame-ancestors https://allfilesnews.com https://*.allfilesnews.com
< x-frame-options: SAMEORIGIN
< link: <https://Reb1lBkV3d9kbe7qlaaC7nZDFGNEErQKHQBk51bdA6c.allfilesnews.com/Reb1lBkV3d9kbe7qlaaC7nZDFGNEErQKHQBk51bdA6c/VvaYNP0fJiVQfefYmC>; rel="canonical"
< expires: Thu, 15 Apr 2110 20:00:00 GMT
< vary: Origin
< x-cache: Miss from cloudfront
< x-amz-cf-pop: TLV50-C1
< x-amz-cf-id: t6P2Rr1HqwCmSDmzC4oVh2fzq25ooHzPY4OZPwWras-9tBbMqinr3Q==

You see that max-age is very long and Last-Modified is in deep past. Why then this (repeated, I already queried this URL no more than a few days ago) query to Squid gives a MISS?
Here is my Squid config:
read_timeout 60 minutes

http_port 3128 accel vhost allow-direct

cache_dir ufs /Files/main/cache 120000 16 256
cache_peer 127.0.0.1 parent 9003 0 no-query default
acl all src 0.0.0.0/0.0.0.0
http_access allow all
never_direct allow all
forward_max_tries 5

Note that 120GB of the cache space is nearly not used:
$ df -h /Files/main/
Filesystem      Size  Used Avail Use% Mounted on
Files/main      125G  187M  125G   1% /Files/main


text:
Q: Filter data with multiple complex clauses joined with OR operation in where function How is it possible to filter data based on some set of filters or expressions that should be used with or operation in where clause?
For example, there is a class:
class DTOFilter
{
    public string Domain { get; set; }
    public string Mobile { get; set; }
}

It is required to filter Users list based on the list of the filters next way:
u=>
(u.Email.Contains(filters[0].Domain) && u.PhoneNumber.StartsWith(filters[0].Mobile)) ||
(u.Email.Contains(filters[1].Domain) && u.PhoneNumber.StartsWith(filters[1].Mobile)) ||
...

Obviously that should be build automaticaly in form like:
db.Users.Where(filters.Filter<Users, DTOFilter>(
                        (u, f) => u.Email.Contains(f.Domain)
                               && u.PhoneNumber.StartsWith(f.Mobile))
              .Or())

A: To perform that task it's required to implement two functions:

*

*Or expression join function

*Filter data split function

Or function goes through a collection of expressions and joins them in a Or expression like (((expression1 or expression2) or expression3) or expression4)
public static Expression<Func<T, bool>> Or<T>(
    this IEnumerable<Expression<Func<T, bool>>> source)
    {
        var expressions = source.ToList();
        if (expressions.Count == 0)
            return x => false;

        var orExpression = expressions
            .Select(e => e.Body)
            .Aggregate((a, b) => Expression.OrElse(a, b));
        var parameter = expressions.First().Parameters.First();
        return Expression.Lambda<Func<T, bool>>(orExpression, parameter);
    }

This function can already be used if filters are already valid expressions.
Filter split data function, should multiply the selector expression and replace in the result expression parameter with the exact object value. Filter data population is done in the function:
public static IEnumerable<Expression<Func<T, bool>>> Filter<T, TData>(
    this IEnumerable<TData> data,
    Expression<Func<T,TData, bool>> selector)
{
    var parameter = selector.Parameters.First(p => p.Type.IsAssignableFrom(typeof(T)));

    return data.Select(item => Expression.Lambda<Func<T, bool>>(
        new DataVisitor<TData>(item).Visit(selector.Body), parameter));
}

Next visitor implementation helps to replace parameter with the exact value:
public class DataVisitor<T> : ExpressionVisitor
{
    private readonly ConstantExpression _data;

    public DataVisitor(T dataItem)
    {
        _data = Expression.Constant(dataItem);
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
            return node.Type.IsAssignableFrom(typeof(T))
                    ? _data : base.VisitParameter(node);
    }
}

The build expression is a correct lambda expression that can be parsed by the EF expression tree parser.


text:
Q: Searching by letters in Postgresql vs. sqlite3 in ActiveRecord I am having trouble searching a string by the first letters. For example, if I have "animal", "ant", and "abs" in my database, I would like a query of "an" to return "animal" and "ant" (case insensitive). I got this working just fine with sqlite3:
Thing.where("name LIKE ?", params[:query] + '%')
However, this does not work in PostgreSQL (database used in pushing to Heroku). What is the correct query using PostgreSQL?

A: In PostgreSQL, you have to use ILIKE instead of LIKE to do a case-insensitive pattern match.

A: Your query will be:
Thing.where("name LIKE '?%'", params[:query])

This makes the query case insensitive:
Thing.where("lower(name) LIKE '?%'", params[:query].to_s.downcase)

If your production uses Postgres, I recommend development does it also, to prevent a further error like this!


text:
Q: Informatica Source File Name with Special Character like 'ä' I am having a problem with my source file name when loading a source from list file. My file is named: "Bär.csv" but when executing, this error occurs. It can't find my file as it was changed to "Bör.csv". Is there a way for the reader to read special characters in the file name?
Error opening file [C:\Informatica\10.2.0\server\infa_shared\SrcFiles\Inbound\test\Bör.csv].  Operating system error message [The system cannot find the file specified.].

A: You have to configure your integration service to use Unicode.


text:
Q: Yii Query Execution I have the following code in my controllers, the insert query is not happening.
 I'm using postgresql for database.
 $connection = Yii::app()->db2 ;
 $command1 = "INSERT INTO USERS (username, user_type) VALUES (:username,:user_type)";
 $cmd1 = $connection->createCommand($command1);
 $cmd1->bindParam(":username",$username,PDO::PARAM_STR);
 $cmd1->bindParam(":user_type",'USER',PDO::PARAM_STR);
 $cmd1->execute();
 echo "Completed...";

What's wrong in the code. the echo "Completed..."; is not printing. I have enabled my postgressql logs the insert query is not executed. No errors display in browser, only blank page is displaying.
the below formate is working to insert into my table. and the query is logged into postgresql log.
$command->insert('users', array(
                                              'username'=>$username,
                                              'user_type'=>'USER',
                                              ));

Thanks in Advance.

A: Try use 'bindValue()' instead of 'bindParam()':
$connection = Yii::app()->db2 ;
 $command1 = "INSERT INTO USERS (username, user_type) VALUES (:username,:user_type)";
 $cmd1 = $connection->createCommand($command1);
 $cmd1->bindValue(":username",$username,PDO::PARAM_STR);
 $cmd1->bindValue(":user_type",'USER',PDO::PARAM_STR);
 $cmd1->execute();
 echo "Completed...";

A: You do not have to bind the value 'USER', you can write it directly in query like this:
 $connection = Yii::app()->db2 ;
 $command1 = "INSERT INTO USERS (username, user_type) VALUES (:username,'USER')";
 $cmd1 = $connection->createCommand($command1);
 $cmd1->bindParam(":username",$username,PDO::PARAM_STR);
 $cmd1->execute();
 echo "Completed...";


text:
Q: Why does my preg_replace() on multi-line file contents on Windows fail? I have a text file Qfile.txt and the contents are follows, and want to create another file with the same informations and but answers are diffrent. Qfile1.txt,Qfile2.txt
Qfile.txt
Question "What is your age?"
Answer ""

Question "What you doing?"
Answer ""

Question "What is you name?"
Answer ""

Qfile1.txt
Question "What is your age?"
Answer "25"

Question "What you doing?"
Answer "chatting"

Question "What is you name?"
Answer "Midhun"

I want to read the questions from the Qfile.txt and store the informations to Qfile1.txt
with in PHP. I wrote some code but the pattern matching is not working:
$contents=file_get_contents("Qfile.txt");
foreach(/*bla bla*/)
{
  $pattern = "/Question \"".preg_quote($id, '/')."\"\nAnswer \"\"/";

  $string = str_replace('"', '\"', $string);

  $replacement = "Question \"$id\"\nAnswer \"". $string . "\"";

  $result = preg_replace($pattern, $replacement, $contents);
}

The preg_replace($pattern, $replacement, $contents); is not working.

A: Unable to replicate; your code, suitably adapted, actually works fine for me.  The only thing I can think of is that perhaps you're writing this on a Windows machine and your text file has CRLF line terminators.  In that case, you'd need to change your code to:
$contents=file_get_contents("Qfile.txt");
foreach(/*bla bla*/)
{
  $pattern = "/Question \"".preg_quote($id, '/')."\"(\r?\n)Answer \"\"/";

  $string = str_replace('"', '\"', $string);

  $replacement = "Question \"$id\"$1Answer \"". $string . "\"";

  $result = preg_replace($pattern, $replacement, $contents);
}

The changes are on the $pattern = and $replacement = lines.  I've written it so that it will preserve whichever line termination pattern is in place (out of the two it supports, LF and CRLF).


text:
Q: React Native: Exporting a function from a functional component Issue:

*

*I'm trying to figure out how to export a function that is called "addPostCode" from the functional component "ContractHandler".

*I want to use "addPostCode" in an other functional component called "RentalDetailScreen" so that when I navigate to the next page it will trigger the "addPostCode" and store the state of "postCode" in "ContractHandler".
This is the "ContractHandler.js":
import React, { useState } from 'react';

const ContractHandler = () => {

  const [postCode, setPostCode] = useState();

  const addPostCode = (data) => {
    setPostCode(data)
    console.log(postCode)
  };

  return(
    <View>
      <Text></Text>
    </View>
  )

}

export default ContractHandler;

These are parts of the RentalDetailScreen.js where I navigate to the next page and want to trigger the "addPostCode"-function and send the "postCode"-value to the "ContractHandler.js".
This is the import:
import { addPostCode } from '../../database/ContractHandler';

This is the navigation with the "addPostCode"-function.
<TouchableOpacity onPress={() => { navigation.navigate('SecurityDetail'); addPostCode(postCode); }}>
  <View style={slider.buttonStyle}>
    <Text style={slider.textStyle}>Neste</Text>
    <Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
  </View>
</TouchableOpacity>

"postCode" is just a variable that is given a value from a TextInput.
If I'm not being clear enough please let me know and I will try to explain better :)

A: The components' own state cannot be set from outside (technically you can solve it but this is not the right way). If you wanna share state between components, use global state manager (redux) or Context or if the components are siblings, just use their common parent to store the state.

A: There are two ways to solve this. You can use a state manager like redux or you have to pass the function as props from component to component. Personally I would use redux because it makes it simpler to share state between components.


text:
Q: How to create an animated marquee label in .NET MAUI that fades in and out? In a streaming music player, I am currently developing, I want to scroll title labels that are too long for the displays width. This is commonly known as a marquee effect and I achieve that one on .NET MAUI by automating the TranslationX property which works really great.
Now I would like to fade in and fade out the label when it's entering the display and leaving it.
I found a way that works but still feels like a hack:
I simply created two rectangular images. One starting black on the left and fading to full alpha value to the right and another one that's basically mirrored. I then render these images on the left and on the right side of the display and make use of the zIndex property to make sure that the label is rendered behind these masking layers.
The result looks like this (fading in):

(fading out):

Obviously, I had to provide two versions of these masking images: One that fades from alpha to white and one that fades to black. And well... as you can image, this works really great when your background is white or black. Of course that would work with any other plain color as well.
Now here is the problem:
My background is not supposed to be filled with a single color. Actually, I scale and blur the cover images of the titles that are currently being played. That looks awesome... but now my hack from above does not work anymore.
So I am left with a simple marquee label that scrolls in and out with no fading at all:

If I had a rectangular copy of the regions of the background image and would be able to apply a linear fade to alpha at runtime, I guess, my original hack would still work. But I cannot thing of any way of how to achieve this.
Do you guys have an idea?


text:
Q: Adding total character limit to regexp I have the following regular expression which works fine, but I need to add an over all limit to the number of characters so it can not be more than 50 long
^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$

Any ideas? I tried adding {1,50} in various places but none that worked!
I know email addresses can be more than 50 characters but for reasons I won't go in to, I need to limit it.

A: You probably should not add this to your regex, since it already seems to be quite complex.  Rather, perhaps you should think about capturing the string length BEFORE evaluating and returning whatever you need for your pass/fail criteria.
var inp = document.getElementById('myinput');
inp.onkeyup = function() {
  alert(inp.value.length);
}

Alernatively, you could simply limit the input field length in the HTML
<input type="text" id="Textbox" name="Textbox" maxlength="50" />

A: You can wrap the body of your regex in a non capturing group and place the 50 character limit there:
^(?:([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)){1, 50}$

A: If you need to know if the string is less than 50 characters, you can check it's length property before doing the regexp. Something like this should work:
if ( emailString.length <= 50 ) {
    // The string is an acceptable length, apply regexp check
} else {
    // The string is too long, no need to check via regexp
}

Of course, you can also add the length constraints to the regexp, but it is may be easier to think of length and format as to separate types of validation. Hope that helps. Cheers!


text:
Q: Get rid of this proxy I wrote a js widget for listing one's github repos on any website with a single line of js:
http://gitview.logicalcognition.com
Currently gitview.js hits gitview.php (which i host remotely) which in turn hits api.github.com to pull user / repo info. Originally, I just did the XHR GET directly to api.github.com rather than through the proxy, but I hit the same origin policy.
I tried using CORS or JSONP, but according to http://developer.github.com/v3/ this only works if the originating domain "is registered as an OAuth Application". I didn't want to make developers do this just to use the widget.
Any suggestions? Am I missing something?

A: The documentation linked indicates a registered domain is needed for CORS (used if you wanted to do a direct XHR), but not JSON-P. With JSON-P, you'd insert a script tag like this programatically (using document.write or DOM manipulation):
<script type="text/javascript"
        src="https://api.github.com/some_request?callback=foo"
></script>

This will then invoke the global function foo with the returned data as an argument. Since this is a script tag and not an XHR request, the same-origin policy does not apply and CORS authorization is not required.


text:
Q: Lua 5.2 new binary library problem Okay, so I decided to try out Lua 5.2 today.
I was really interested in the new binary library called bit. Some of the functions run lightning fast compared to what I can make on my own, mainly because they've been implemented on the C side of Lua. Take the binary XOR function, it runs 34 times faster than my Lua implementation of XOR.
So, my dilemma is:
I think there's a bug in the binary functions already
print(bit.bnot(0)) --> 4294967295

That's correct, because 4294967295 is 11111111 11111111 11111111 11111111 in binary
However,
print(bit.band(4294967295, 65535)) --> 0

Which is wrong, or atleast I think it should be.
65535 in binary is 11111111 11111111.
When I use bit.band in the afore mentioned situation shouldn't 65535 be returned ?
I'm using Lua 5.2.0-work2 precompiled binaries from here

A: I have not looked at the Lua 5.2 releases at all, but if your primary interest is in binary operations, there is a BitOp module for Lua 5.1 here which is source compatible with the native implementations provided by LuaJit.


text:
Q: Can't show value with json format on apache tomcat server I've been trying to make a certain API and I need it to show result of a method on server in JSON format. If I try simple
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/messages")
public class MessageResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getMessages() {
        return "Hello World!";
    }

}

it works but when I try to use my class where I return values in JSON format it shows some errors on the server (it works in ordinary console).
I'm new to this, hope I explained it well enough.
type Exception report

message org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper
    org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:278)
    org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:260)
    org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:509)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:334)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper
    valendor.messenger.ReturnJson.main(ReturnJson.java:27)
    sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$VoidOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:143)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.36 logs.

thats the error

A: Obviously, as the error message states, you are missing the org.codehaus.jackson.map.ObjectMapper class. You have to add jackson-mapper library to your classpath, i.e. to your WEB-INF/lib folder.
If you use Maven to build your project, add the following dependency to your pom.xml:
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-lgpl</artifactId>
    <version>1.9.13</version>
</dependency>

(replace the version with the one you want to use, 1.9.13 is the newest ATM)


text:
Q: Change language of Datepicker with maintaining format of Material Angular 10 I do have Multilanguage support in my application and would like to implement translation for the angular material date picker. I have used dateAdapter class from material and set the values but while doing so my format of display is getting changes.
Is anyone have faced same issue?

export const MY_FORMATS = {
    parse: {
        dateInput: 'LL',
    },
    display: {
        dateInput: 'ddd, MMM. D YYYY',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
    },
};

@Component({
  selector: 'test',
  templateUrl: './test.html',
  styleUrls: ['./test.scss'],
  providers: [{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }],
})
ngOnInit(): void {
    //on language change
    //change language
    this.dateAdapter.setLocale('fr');
}

A: For multilanguage support I would recommend you to use the MomentDateAdapter. Here is one note from Angular docs about multi-language support and the NativeDateAdapter (the default one's):

MatNativeDateModule is based off the functionality available in JavaScript's native Date object. Thus it is not suitable for many locales. One of the biggest shortcomings of the native Date object is the inability to set the parse format. We highly recommend using the MomentDateAdapter or a custom DateAdapter that works with the formatting/parsing library of your choice.

The only counterpart is that by using MomentDateAdapter you will now have moment as a dependency... but not big deal, and you may already be using it.
Here is some example code (taken from Angular docs):
import {Component} from '@angular/core';
import {
  MAT_MOMENT_DATE_FORMATS,
  MomentDateAdapter,
  MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

/** @title Datepicker with different locale */
@Component({
  selector: 'test',
  templateUrl: 'test.html',
  styleUrls: ['test.css'],
  providers: [
    // The locale would typically be provided on the root module of your application. We do it at
    // the component level here, due to limitations of our example generation script.
    {provide: MAT_DATE_LOCALE, useValue: 'fr'},

    // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
    // `MatMomentDateModule` in your applications root module. We provide it at the component level
    // here, due to limitations of our example generation script.
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },
    {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
  ],
})
export class DatepickerLocaleExample {
  constructor(private _adapter: DateAdapter<any>) {}

  // Change adapter language to japanese
  japanese() {
    this._adapter.setLocale('ja-JP');
  }
}


text:
Q: Dragging from one view to another in a frameset does not execute PostDragDrop I have two side-by-side views in a frameset, one outline view and one calendar view. On the calendar view, I can drag between dates, my code perfectly executing. However, when I try to drag from my outline view onto a date on the calendar view, the Postdragdrop event on the calendar view does not execute.
How can I drag/drop between views in a frameset?
Thanks.


text:
Q: Hide element on hover of another element I know it can be done in JavaScript, however I am looking for solution in CSS.
I have three divs.

*

*div#hide should be visible by default, #show should be hidden.

*When I hover on #main, #hide should hide and #show should be visible.

div#show works fine but #hide doesn't hide when #main is hovered. How can we do it in css?

#show {
  display: none
}
#main:hover + #show {
  display: block
}
#main:hover + #hide {
  display: none
}

  Hover me

  Show me on hover

  Hide me on hover

A: Instead of + you want to use ~ combinator for hide element because + selects only next-sibling

#show {
  display: none
}
#main:hover + #show {
  display: block
}
#main:hover ~ #hide {
  display: none
}

  Hover me

  Show me on hover

  Hide me on hover

A: You just have to replace the + selector with ~ cause the #hide is not placed after #main
So your code is:
#show {display:none}
#main:hover + #show { display:block }
#main:hover ~ #hide { display:none }

A: You've to use tilda '~' for this case.
The difference between + and ~ is that ~ matches all following siblings regardless of their proximity from the first element, as long as they both share the same parent.
    #show {display:none}
    #main:hover + #show { display:block }
    #main:hover ~ #hide { display:none }

A: Try something like this: "#main:hover + #show + #hide"
div#show {
    display:none;
}
#main:hover + #show {
    display:block
}
#main:hover + #show + #hide {
    display:none
}

It's working for me.


text:
Q: Python string (argument) -> Regex I'm trying to take a regular expression as an argument to my python program (which is a string naturally) and simply match it against another string.
Let's say I run it as
python program.py 'Hi.there'
I'd like to be able to then take that input (call it input) and say whether or not it matches 'HiTthere' (it should).
How should I do this? I'm inexperienced at regex.

A: From my understanding, you're looking for something like:
import sys, re

regex = sys.argv[1]

someOtherString = 'hi there'

found = re.search(regex, someOtherString)
print('ok' if found else 'nope')

Run this program with an expression as a first argument:
> python test.py hi.th
ok
> python test.py blah
nope

Unlike, say, javascript, python regexes are simple strings, so you can directly use sys.argv[1] as an argument to re.search.

A: Python 3 syntax (Python 2, use print xxx instead of print(xxx)):
import re

if re.match(r'^Hi.there$', 'HiTthere'): # returns a "match" object or None
    print("matches")
else:
    print("no match")

Note that I'm using the anchors ^ and $ to guarantee that the match spans the entire input. ^ matches the start of the string and $ matches the end of the string.
See the documentation for much more detail.


text:
Q: Ruby metaprogramming, how does RSpec's 'should' work? I was reading up on RSpec and I was trying to figure out how RSpec's "should" was implemented.
Could someone give a hand on how the meta nature of this function works?
The code is located here:
http://github.com/dchelimsky/rspec/blob/master/lib/spec/expectations/extensions/kernel.rb
TIA,
-daniel
Clarification:
target.should == 5

How did target's value get passed along to "should", which in turn was "=="'d against 5?

A: Take a look at class OperatorMatcher.
It all boils down to Ruby allowing you to leave out periods and parenthesis.  What you are really writing is:
target.should.send(:==, 5)

That is, send the message should to the object target, then send the message == to whatever should returns.
The method should is monkey patched into Kernel, so it can be received by any object.  The Matcher returned by should holds the actual which in this case is target.
The Matcher implements the method == which does the comparison with the expected which, in this case, is the number 5.  A cut down example that you can try yourself:
module Kernel
  def should
    Matcher.new(self)
  end
end

class Matcher
  def initialize(actual)
    @actual = actual
  end

  def == expected
    if @actual == expected
      puts "Hurrah!"
    else
      puts "Booo!"
    end
  end
end

target = 4
target.should == 5
=> Booo!

target = 5
target.should == 5
=> Hurrah!


text:
Q: How to invert Euler's totient $\varphi$ I am writing this one since I have struggled a lot, at the very beginning of my Analytic Number Theory Course, to learn how to invert Euler's Totient. I wanted to find an algorithm, but, given the fact that inverting $\varphi$ is an NP-hard problem, I didn't find too much.
Feel free to comment and improve.

The problem is:
Find all positive integers $n$ such that $\varphi\left(n\right)=k$,
  for a given $k$. To fix the ideas, let us take $k=18$.

A: First step: define the set:
$$S\left(k\right):=\left\{ \text{prime }p:\;\left(p-1\right)\mid k\right\}$$
In this case it is:
$$S\left(18\right):=\left\{ \text{prime }p:\;\left(p-1\right)\mid 18\right\}=\left\{ 2,3,7,19\right\} $$
The result is a set $\left\{ p_{1},p_{2},\dots,p_{n}\right\}$. Obviously, every solution $E$ of the equation $\varphi\left(n\right)=k$ is of the form
$$p_{1}^{a_{1}}p_{2}^{a_{2}}...p_{n}^{a_{n}}\;\;a_i\in\mathbb{N},i=1,2,\dots,n$$
Second step: (not mandatory, but I find it very useful later). For every prime divisor $p_i$ found in the previous step, determine $\varphi\left(p_{i}^{a_{i}}\right)$ and stop when you find the first $i$ such that $\varphi\left(p_{i}^{a_{i}}\right)>k$. In fact, the property of the Euler function:
$$\varphi\left(p^r\right)=p^r-p^{r-1}$$
grants that after that index $i$ there is no more 'useful' power of the prime - meaning that all other powers of the prime are greater than $k$.
We have:
$$\begin{array}{ccccc}
\varphi\left(2\right)=1 & \varphi\left(2^{2}\right)=2 & \varphi\left(2^{3}\right)=4 & \varphi\left(2^{4}\right)=8 & \varphi\left(2^{5}\right)=16\end{array}$$
$$
\begin{array}{ccc}
\varphi\left(3\right)=2 & \varphi\left(3^{2}\right)=6 & \varphi\left(3^{3}\right)=18\end{array}
$$
$$
\begin{array}{cc}
\varphi\left(7\right)=6 & \varphi\left(19\right)=18\end{array}
$$
Third step: analyse all the cases of $\prod_{i=1}^{n}p_{i}^{a_{i}}$, starting from the highest prime.
In our case, the generic solution can be written as $2^a3^b7^c19^d$; the highest prime is 19. Two cases arise: either $d=0$ or $d=1$. If $d=1$ then:
$$\varphi\left(2^{a}3^{b}7^{c}19\right)=\varphi\left(2^{a}3^{b}7^{c}\right)\varphi\left(19\right)=18\varphi\left(2^{a}3^{b}7^{c}\right)$$
imposing the RHS equal to 1 gives raise to two more cases: either $a=0$ or $a=1$, leading to the solutions $E_1=19\cdot1=19$ and $E_2=19\cdot2=38$.
Analyse the case $d=0$; rewrite the generic solution as $2^a3^b7^c$ Consider that $\varphi\left(7\right)=6$ so $c$ cannot be 1. In fact, in that case, it should be $\varphi\left(2^a3^b\right)=3$, which is not possible.
So, $c=d=0$; rewrite the generic solution as $2^a3^b$. The given equation has solution if and only if $b=3$. This gives raise to the cases $a=0$ and $a=1$, leading to the solutions $E_3=27\cdot1$ and $E_4=27\cdot2=54$.
Final note: this is a quick'n'dirty approach. You should have no problem, except for the computational weight. The real risk here is forgetting some cases. That's why I suggest to draw somehow a tree or a matrix to help visualising all the possible combinations.