Q:

Finding element with selenium using string formating

I am trying to find an element in the DOM/HTML using css selector with selenium and python.
However I am receiving an error, the syntax appears to be the same but it outputs an error.
Here is the code:
def find_element(self):
        var1, var2 = input("enter class and div (seperated by comma): ").split(',')
        var_list = [var1,var2]
        for x in var_list:
            x.strip()
        find_elem = ("{}[class*='{}']").format(var1, var2)
        try:
            if (self.driver.find_element_by_css_selector("{}[class*='{}']".format(var1,var2)).is_displayed()):
                print('Exist')
            else:
                print('does not exist')
        except Exception as e:
            raise Exception('Not looking for element')

Here is the error:
Traceback (most recent call last):
  File "/home/gregory/projects/parser/Scraper1/WebGrab.py", line 55, in find_element
    if (self.driver.find_element_by_css_selector("{}[class*='{}']".format(var1,var2)).is_displayed()):
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 598, in find_element_by_css_selector
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
    'value': value})['value']
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/gregory/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: div[class*='lga']

I am using google.com landing page as the test case: The element I am looking for is the Google logo. This is the element I have from the inspector. I input "div" and "lga" as div,lga.
BONUS if you can tell me why the strip function is not working either.
Thanks!

A:

x.strip() doesn't change x, so you'd need something like x = x.strip().. but that won't work in the loop you have, because changing x still won't change var1, var2.
So, instead, just do something along the lines of:
find_elem = ('{}[class*="{}"]').format(var1.strip(), var2.strip())

Quick look at the google homepage, I don't see any divs with class similar to lga, though there is a div with id=lga. So my guess as to why it can't be found is, because it's not there.


Q:

Block based enumeration getting BAD_ACCESS

I have a block based enumeration setup to go through an array of NSDictionaries like this:
__block NSURL *contentURL;

 //This method of enumerating over the array gives the bad_access error
[documents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    NSString *aName = [(NSDictionary *)obj objectForKey:@"Name"];

    if([aName isEqualToString:name]) {

        contentURL = [NSURL URLWithString:[(NSDictionary *)obj objectForKey:@"Content"]];
        *stop=YES;
    }
}];

NSLog(@"Content URL for issue with name %@ is %@", name, contentURL);

Which if I use this method I get a EXC_BAD_ACCESS error on contentURL when I try to print it out in the NSLog statement.
If however, I enumerate through the array like this:
NSURL *contentURL;

//This method of enumerating over the array works fine
for (NSDictionary *obj in documents) {

    NSString *aName = [obj objectForKey:@"Name"];

    if([aName isEqualToString:name]) {

        contentURL = [NSURL URLWithString:[obj objectForKey:@"Content"]];

    }
}

NSLog(@"Content URL for issue with name %@ is %@", name, contentURL);

All works fine. Why is this?

A:

I ran into a similar problem a while ago.
Turns out that some of the block-based enumeration methods wrap the enumeration in an autorelease pool. Since you're assigning an autoreleased object, it gets deallocated before -enumerateObjectsUsingBlock: returns.
(I ran into the problem with -[NSDictionary enumerateKeysAndObjectsUsingBlock:, but the same principle applies here)
Try this instead:
contentURL = [[NSURL alloc] initWithString:[(NSDictionary *)obj objectForKey:@"Content"];

Out of interest, are you using ARC? If you are, I'd have expected it to add in a -retain on assignment.
Edit:
You are using ARC, so this isn't the answer to your question. Assigning to a __block variable will retain the object (unless you've encountered a bug in ARC, which is unlikely. The code you've provided doesn't have this issue when compiled using Apple LLVM 5.0).
It is likely that your problem is elsewhere and changing from using the convenience constructor is just masking the problem.
Likewise, the autorelease pool set up for the duration of the enumeration is likely revealing a problem that is caused elsewhere in your code. It explains why switching to using fast enumeration seems to fix the problem, but as before it is likely just masking a problem caused elsewhere in your code.
I'll leave the answer here because the information about autorelease pools may still be relevant to people who stumble across this.


Q:

Rails - simple form

I use simple_form gem in my Rails app. When I use code like this
= f.input_field :name, label: false, placeholder: 'Name'
= f.input_field :price, label: false, placeholder: 'Price'
= f.input_field :description, label: false, placeholder: 'Description'
= f.input_field :image, label: false, placeholder: 'Image'

I get HTML for input:
<input class="string required textform" id="item_name" label="false" maxlength="255" name="item[name]" placeholder="Имя" size="255" type="text">

As you can see size of input is 255 now. Actually it's much more than enough. How can specify the size of inputs?

A:

Following is from simple_form documentation here

It is also possible to pass any html attribute straight to the input,
  by using the :input_html option, for instance:
<%= simple_form_for @user do |f| %>
  <%= f.input :username, input_html: { class: 'special' } %>
  <%= f.input :password, input_html: { maxlength: 20 } %>
  <%= f.input :remember_me, input_html: { value: '1' } %>
  <%= f.button :submit %>
<% end %>


Q:

Not Working Jquery Enter Key and Shift-Enter key

My J-Query key press,shift-key is not working in Mozilla Firefox need help thanks in advance.
J-Query using : jquery-1.7.2.min.js
<html><body>
<textarea id = 'text' rows='4' cols='50' style = 'width: 50%;height:15%;' placeholder = 'Enter Post....'></textarea>
</body></html>

<script>

$('#text').keypress(
    function(e){
        if (e.keyCode == 13 && e.shiftKey) {
            alert("a");
        }
        else if(e.keyCode == 13){
            alert("sdf");
        }
    }
);

</script>

A:

Place your code in a document ready handler -
$(document).ready(function() {
   $('#text').keypress(function (e) {
       if (e.keyCode == 13 && e.shiftKey) {
           console.log("a");
       } else if (e.keyCode == 13) {
           console.log("sdf");
       }
   });
});


Q:

Default Value Many To Many Field doesn't work, Django 1.8

I have following model:
class Editor(models.Model):
    nombre = models.CharField(max_length=30)
    domicilio = models.CharField(max_length=50)
    #....

class Autor(models.Model):
    nombre = models.CharField(max_length=30)
    apellido = models.CharField(max_length=40)
    email = models.EmailField(blank=True, verbose_name='e-mail')
    #....

def defaultM2M():
    return [Autor.objects.first().pk]

class Libro(models.Model):
    titulo = models.CharField(max_length=100)
    autores = models.ManyToManyField(Autor, default=default2M2)
    editor = models.ForeignKey(Editor, default=Editor.objects.filter(pk=1))

I have a function named defaultM2M to change default value in my ManyToMany attribute for  'Libro', so the issue is when I create a new object 'Libro', this is relationated with my default Autor, no matter if I choose another Autor, My object 'Libro' is create with 2 'Autor' objects, default Autor and chosen Autor. How can set Autor default without this issue?
Thanks

A:

Looking at the Django docs default doesn't seem to be an option for ManyToMany fields. You can however overload the save() method to achieve what you want:
def save(self, *args, **kwargs)
    if 'autores' not in kwargs:
         kwargs['autores'] = defaultM2M()
    super(Libro, self).save(*args, **kwargs)


Q:

Is it wrong to use auto_ptr with new char[n]

If I declare a temporary auto deleted character buffer using
std::auto_ptr<char> buffer(new char[n]);

then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.
However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[].
What possibility is there that this mismatch might cause a memory leak?

A:

The behaviour of calling delete on a pointer allocated with new[] is undefined. As you assumed, auto_ptr does call delete when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible.
If you don't need to transfer the ownership of the pointer, Boost's scoped_array class might be what you're looking for.

A:

I would use a vector of char as the buffer.
std::vector<char>    buffer(size);

read(input,&buffer[0],size);

Basically you don't even want to call new if you don't need to.
A vector provides a run-time sized buffer that you can use just like an array (buffer).
The best part is that the vector cleans up after itself and the standard guarantees that all element in the vector will be in contigious storage. Perfect for a buffer.
Or more formaly the guarantee is:
(&buffer[0]) + size == (&buffer[size])

A:

That yields undefined behaviour (could be worse than memory leak, for instance heap corruption) try boost's scoped_array or shared_array instead.


Q:

LocalStorage not found on Desktop Bridge WebBrowser

I have a converted WPF app with Desktop Bridge that has a WebBrowser which loads two AngularJS WebApps.
An error is happening due to object localStorage, which WeBbrowser can't access, same error at both WebApps. The URL loaded is remote, there is nothing locally loaded in WebBrowser.
The exception happens when trying to execute "window.localStorage" (javaScript code of page loaded) and the error message is: System can't find the specified file.
However, when I run the MSI installer and use it as a regular WPF app, everything works right.
EDIT
I've found that localStorage files from converted app are saved at path: %userprofile%\AppData\Local\Packages\PackageName\AC\Microsoft\Internet Explorer\DOMStore
But converted app when fails, this structure folder doesn't exist. I don't know why...
Do you know what it's causing the problem or any solution to it? Thanks.

A:

I've tested in a lot of devices with Windows 10 and found that always fails when users have Anniversary Update but it works always OK when users have Creators Update.
I don´t know the reason. I suspect is something that has been correct with this build.
So I decided to retarget the App min version to Creators Update and everything is working now.


Q:

Claiming '1' vs. Tax Refund Amounts

If I claim '1' on my W-4, that amount is equal to ~$4050.00, spread over the year, and I believe is counted toward taxable income, and is taxed on your paychecks. If I were to claim '0', is that same money just 'saved' until I do my taxes, and then it is taxed anyway at tax time, before my refund? My question is; is the money in my pocket the same (at the end of the year), whether in my paychecks over the year, or at refund time? thanks!

A:

The number of exemptions you claim directly translates into an amount withheld from your paycheck for taxes.  A larger number means less withheld, a smaller number more.  0 would be the most possible withheld.  You can see Publication 15 for the table of how much would be withheld based on your paycheck, and how the number of exemptions affects this.
This number does not in any way affect your tax due, however.  As long as you have withheld at least as much as you owe in taxes, you'll get a refund of whatever extra is withheld; if you have less withheld than you owe, it's possible you might owe a penalty if you owe more than $1000 and don't meet any of the exemptions (for most filers, paying as much in taxes as you paid last year, or 90% of what you owe this year).
If you end up withholding more than you owe, you're basically giving the government an interest-free loan until tax time; and if you have less withheld, you are getting an interest-free loan (unless it's > $1000 and you owe a penalty which is basically that interest).
Note that the specifics here are appropriate for the 2017 and earlier tax years, but will change in 2018 with the change in personal exemptions going away; this hasn't been finalized yet, however.  If you're considering making a change right now, I would wait until late February when the IRS should have new guidance and perhaps a new form W-4.


Q:

How are POSIX Threads implemented on Linux?

I was wondering if threads created via the pthreads library are actually kernel-level threads or user-space threads that have nothing to do with the kernel? I have heard mutually exclusive opinions about this, so I want to know the truth.

A:

Before Linux 2.6 they were essentially userspace threads, separate processes which were glued together, because the kernel had no real thread support. Edit: There was some limited support for kernel level threads (a clone() function) before 2.6, but it wasn't used with posix threads, only with an alternative thread library called linuxthreads.
Since the arrival of NPTL (Native Posix Thread Library) the are kernel threads.

A:

Threads created by pthread_create() on Linux have always been kernel-level threads. LinuxThreads didn't comply fully with POSIX (threads in a same process had different pid's, signal handling was different than what POSIX requires, ...), so NPTL was created to fix those issues.
There are libraries that implement user-level threads (e.g: GNU pth, the p is for Portable), but they don't use the POSIX thread API.


Q:

How can I implement an AutoSize property to a Custom Control?

I want to implement an AutoSize property in a Custom Control (not User Control), in such a way that it behaves like other standard .NET WinForms controls which implement AutoSize (ala CheckBox) in design mode.
I have the property set up, but it's the way the control behaves in design mode that bugs me. it can still be resized, which doesn't make sense because the visual resize isn't reflected in the AutoSize and Size properties i've implemented.
Standard .NET controls do not allow resizing (or even show resize handles) in design mode when AutoSize is true. I want my control to behave in the same fashion.
Edit: I have it working using the SetBoundsCore() override, but it doesn't visually restrict a resize when AutoSize is set to true, it just has the same effect; the functionality is equivalent, but it feels unnatural.
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
    if (!this.auto_size)
        this.size = new Size(width, height);
    base.SetBoundsCore(x, y, this.size.Width, this.size.Height, specified);
}

Any ideas on doing this the standard way?

A:

Here's my recipe to have your control AutoSize.
Create a method GetAutoSize() to calculate the required size of the control according to your specific implementation. Maybe it's the size of the text it contains or the total height of the controls for the current width, whatever.
Create a method ResizeForAutoSize() to force the control to resize itself following a change in its state. For example if the control is sized for the text it contains, changing the text should have the control resized. Just call this method when the text changes.
Override GetPreferredSize() to notify whoever wants to know (like a FlowLayoutPanel for instance) what is our preferred size.
Override SetBoundsCore() to enforce our sizing rule the same way an AutoSize label cannot be resized.
See sample here.
/// <summary>
/// Method that forces the control to resize itself when in AutoSize following
/// a change in its state that affect the size.
/// </summary>
private void ResizeForAutoSize()
{
    if( this.AutoSize )
        this.SetBoundsCore( this.Left, this.Top, this.Width, this.Height,
                    BoundsSpecified.Size );
}

/// <summary>
/// Calculate the required size of the control if in AutoSize.
/// </summary>
/// <returns>Size.</returns>
private Size GetAutoSize()
{
    //  Do your specific calculation here...
    Size size = new Size( 100, 20 );

    return size;
}

/// <summary>
/// Retrieves the size of a rectangular area into which
/// a control can be fitted.
/// </summary>
public override Size GetPreferredSize( Size proposedSize )
{
    return GetAutoSize();
}

/// <summary>
/// Performs the work of setting the specified bounds of this control.
/// </summary>
protected override void SetBoundsCore( int x, int y, int width, int height,
        BoundsSpecified specified )
{
    //  Only when the size is affected...
    if( this.AutoSize && ( specified & BoundsSpecified.Size ) != 0 )
    {
        Size size = GetAutoSize();

        width   = size.Width;
        height  = size.Height;
    }

    base.SetBoundsCore( x, y, width, height, specified );
}


Q:

Input using Scanner Class

I am a new java programmer, In my below code when am trying to enter the employee name like john smith, only john is getting printed in output.
And if I put
System.out.print("Enter Employee Name: ");
String employeeName = s.next();

above
System.out.print("Enter SEX: ");
char SEX = s.next().charAt(0);

this piece of code in output is not asking for my employeename value. and directly printing the remaining values.
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
**package cs480;
import java.util.Scanner;
public class CS480D1_Richa_2_Week2 {
    public static void main(String [] args){
     Scanner s=new Scanner(System.in);
     System.out.print("Ente Employee ID: ");
     int employeeId = s.nextInt();
     System.out.print("Ente SEX: ");
     char SEX = s.next().charAt(0);
     System.out.print("Ente Employee Name: ");
     String employeeName = s.next();
     System.out.println("Employee ID is " +employeeId);
     System.out.println("Employee Name is " +employeeName);
     System.out.println("Employee gender is " +SEX);
    }

}**

A:

Please try with this:
public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    System.out.print("Ente Employee ID: ");
    int employeeId = s.nextInt();
    System.out.print("Ente SEX: ");
    char SEX = s.next().charAt(0);
    System.out.print("Ente Employee Name: ");
    String employeeName = s.nextLine();
    employeeName = s.nextLine();// Try to add this line of code
    System.out.println("Employee ID is " + employeeId);
    System.out.println("Employee Name is " + employeeName);
    System.out.println("Employee gender is " + SEX);

}


Q:

Reply from “nsa.gov” while pinging “gen.lib.rus.ec”

Running ping gen.lib.rus.ec (a Library Genesis server) returns this output:
PING gen.lib.rus.ec (91.200.14.96) 56(84) bytes of data
64 bytes from nsa.gov (91.200.14.96): icmp_seq=1 ttl=57 time=69.1 ms

Why nsa.gov?

A:

It is a joke :)
What you are seeing is the PTR record for 96.14.200.91.in-addr.arpa, otherwise known as the reverse dns for ip 91.200.14.96.
The reverse records for ip-adresses are delegated to the owners, and they can set the response to be whatever they like.
If you run the command: dig -t PTR +trace 96.14.200.91.in-addr.arpa, you can see which nameserver that have configured the PTR/Reverse DNS-record.
The output is truncated for readability:
14.200.91.in-addr.arpa. 172800  IN  NS  ns1.vhoster.net.
14.200.91.in-addr.arpa. 172800  IN  NS  ns2.vhoster.net.
14.200.91.in-addr.arpa. 3600    IN  NSEC    140.200.91.in-addr.arpa. NS RRSIG NSEC
14.200.91.in-addr.arpa. 3600    IN  RRSIG   NSEC 8 5 3600 20180518163550 20180418153550 23854 91.in-addr.arpa. SZdra/lg7c9+Arxp2hgfd3DvB2T0KMmxfSm6rzsGtLbuGPc5PEnYZPI7 qP5qoqpNXQXbNYxBKIKZn/3Q3ijPSoZZhbr83ABf9SLjuVswvSY1Wrrr dzu7bbLWxjIKe6U7tN+57LqgfY71dHVO8chaZAHwoj0JAxBnVbiLqUvD E5Y=
;; Received 321 bytes from 193.0.9.5#53(pri.authdns.ripe.net) in 10 ms

96.14.200.91.in-addr.arpa. 3600 IN  PTR nsa.gov.
14.200.91.in-addr.arpa. 3600    IN  NS  ns2.vhoster.net.
14.200.91.in-addr.arpa. 3600    IN  NS  ns1.vhoster.net.
;; Received 122 bytes from 91.200.14.2#53(ns1.vhoster.net) in 47 ms

As you can see, the answer is coming ns1.vhoster.net, which is responsible for the PTR-record for 91.200.14.96.
There are many other interesting reverse records in the 91.200.14.0/24 range:
12.14.200.91.in-addr.arpa domain name pointer disney.com.
61.14.200.91.in-addr.arpa domain name pointer bot.4.
251.14.200.91.in-addr.arpa domain name pointer whitehouse.gov.

Check all of them here
Can this be a security problem? Yes, potentially. If the reverse-dns is not threated as untrusted input, it can lead to different problems.

If an application only log connections based on PTR-records instead
of IP-address, you lose traceability.
If the reverse-dns is used as part of an SQL-command, it might be used
to conduct an sql-injection attack.
If used in HTML-documents, unsanitized PTR-records can be used for
HTML-injection/XSS attacks.


Q:

Getting conflicting ClassCastException when calling getChildAt from LinearLayout

The system I'm currently working on relies on the layout being built from a JsonArray returned from an API, it does this by primarily using several different ViewHolders in the adapter class.
The problem I'm having is trying to build a RadioGroup that can only have one option selected at once. The code for that is below.
public class RadioGroupModule extends View implements View.OnClickListener{

    private JSONObject jsonObject;
    private Context context;
    private RadioGroupInterface radioGroupInterface;

    private LinearLayout parentLayout, ll_radio_group;
    private ImageView img_radio_group;
    private TextView txt_radio_group_text;

    public RadioGroupModule(JSONObject jsonObject, LinearLayout parentLayout, Context context,
                            RadioGroupInterface radioGroupInterface){
        super(context);
        this.jsonObject = jsonObject;
        this.parentLayout = parentLayout;
        this.context = context;
        this.radioGroupInterface = radioGroupInterface;

        renderView(parentLayout);
    }

    public void renderView(LinearLayout parentLayout){
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.module_radio_group, parentLayout, false);

        //Logic shit yo

        setUpLinearLayout(view);
        setUpTextView(view);
        setUpImageView(view);

        parentLayout.addView(view);
    }

    private void setUpLinearLayout(View view){
        ll_radio_group = (LinearLayout)view.findViewById(R.id.ll_radio_group);
        ll_radio_group.setOnClickListener(this);
    }

    private void setUpImageView(View view){
        img_radio_group = (ImageView)view.findViewById(R.id.img_radio_group);
        img_radio_group.setOnClickListener(this);

        try{
            if(jsonObject.has("selected")){
                if(jsonObject.getBoolean("selected")){
                    setSelectedTrue();
                } else {
                    setSelectedFalse();
                }
            } else {
                setSelectedFalse();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setUpTextView(View view){
        txt_radio_group_text = (TextView)view.findViewById(R.id.txt_radio_group_text);
        txt_radio_group_text.setOnClickListener(this);

        try{
            txt_radio_group_text.setText(jsonObject.getString("label"));
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public JSONObject getJsonObject(){
        return jsonObject;
    }

    public void setSelectedTrue(){
        txt_radio_group_text.setBackgroundColor(context.getResources().getColor(R.color.black));
        txt_radio_group_text.setTextColor(context.getResources().getColor(android.R.color.white));
    }

    public void setSelectedFalse(){
        txt_radio_group_text.setBackgroundColor(context.getResources().getColor(android.R.color.white));
        txt_radio_group_text.setTextColor(context.getResources().getColor(R.color.black));
    }

    @Override
    public void onClick(View v) {
        try{
            jsonObject.put("selected", true);
        } catch (Exception e){
            e.printStackTrace();
        }
        radioGroupInterface.returnUpdatedObject(jsonObject);
    }
}

The view is then added to a LinearLayout in a View that holds the RadioGroupModule, the XML for that view is below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true">

    <TextView
        android:id="@+id/txt_radio_group_title"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:textColor="@color/black"/>

    <LinearLayout
        android:id="@+id/ll_radio_group_holder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"/>

</LinearLayout>

The module is added to that linear layout like so, setPayload is called from onBindViewHolder after getItemViewType is called.
public void setPayload(JSONObject jsonObject){

    this.jsonObject = jsonObject;
    answerArray.put(jsonObject);

    try{
        txt_radio_group_title.setText(jsonObject.getString("label"));
        valuesArray = jsonObject.getJSONArray("values");

        for(int i = 0; i < valuesArray.length(); i++){
            JSONObject object = valuesArray.getJSONObject(i);
            ll_radio_group_holder.addView(new RadioGroupModule(object, ll_radio_group_holder, context, new RadioGroupInterface() {
                @Override
                public void returnUpdatedObject(JSONObject jsonObject) {

                    for(int i = 0; i < valuesArray.length(); i++){

                        try{
                            JSONObject valueObject = valuesArray.getJSONObject(i);
                            if(valueObject.getInt("id") == jsonObject.getInt("id")){
                                valueObject.put("selected", jsonObject.getBoolean("selected"));
                                setValuesAsFalse(valueObject);
                            }

                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }));
        }

    } catch (Exception e){
        e.printStackTrace();
    }
}

The module is added the the linear layout no problem. The problem occurs when I'm calling getChildAt from the module holder LinearLayout and trying to cast it RadioGroupModule. The modules constructor passes in an interface that is used for callback when the user clicks on a the Module in the LinearLayout.
The callback passes back the JSONObject that has been selected. From there I need to loop through a JSONArray of all the results and put the selected value to false in all the other objects, and change an ImageViews source to not selected if it was previously selected, this is where the problems arise. Below this is the method I've written to do this and the JSONArray of the checkboxes.
public void setValuesAsFalse(JSONObject correctObject) throws Exception{
    JSONArray jsonArray = jsonObject.getJSONArray("values");
    for(int i = 0; i < jsonArray.length(); i++){
        JSONObject valueObject = jsonArray.getJSONObject(i);
        if(valueObject.getInt("id") != correctObject.getInt("id")){
            valueObject.put("selected", false);
            RadioGroupModule radioGroupModule = (RadioGroupModule) ll_radio_group_holder.getChildAt(i);
        }
    }
}

And the values array.
[
  {
    "label": "Option 1",
    "value": "option-1",
    "selected": true,
    "id": 31
  },
  {
    "label": "Option 2",
    "value": "option-2",
    "id": 32,
  },
  {
    "label": "Option 3",
    "value": "option-3",
    "id": 33
  },
  {
    "label": "option-4",
    "value": "option 4",
    "id": 34
  }
]

That method throws the following ClassCastException
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to com.unisaas.unisaas.risk_assessment.modules.RadioGroupModule
04-18 12:12:47.318 2201-2201/com.unisaas.unisaas W/System.err:     at com.unisaas.unisaas.risk_assessment.risk_assesment_fragment.RiskFormAdapter$RadioGroupViewHolder.setValuesAsFalse(RiskFormAdapter.java:606)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at com.unisaas.unisaas.risk_assessment.risk_assesment_fragment.RiskFormAdapter$RadioGroupViewHolder$1.returnUpdatedObject(RiskFormAdapter.java:582)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at com.unisaas.unisaas.risk_assessment.modules.RadioGroupModule.onClick(RadioGroupModule.java:112)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at android.view.View.performClick(View.java:5609)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at android.view.View$PerformClick.run(View.java:22262)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at android.os.Looper.loop(Looper.java:154)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
04-18 12:12:47.319 2201-2201/com.unisaas.unisaas W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

For arguments sake I changed this line
RadioGroupModule radioGroupModule = (RadioGroupModule) ll_radio_group_holder.getChildAt(i);

to
LinearLayout linearLayout = (LinearLayout) ll_radio_group_holder.getChildAt(i);

and the following exception was thrown
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err: java.lang.ClassCastException: com.unisaas.unisaas.risk_assessment.modules.RadioGroupModule cannot be cast to android.widget.LinearLayout
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at com.unisaas.unisaas.risk_assessment.risk_assesment_fragment.RiskFormAdapter$RadioGroupViewHolder.setValuesAsFalse(RiskFormAdapter.java:606)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at com.unisaas.unisaas.risk_assessment.risk_assesment_fragment.RiskFormAdapter$RadioGroupViewHolder$1.returnUpdatedObject(RiskFormAdapter.java:582)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at com.unisaas.unisaas.risk_assessment.modules.RadioGroupModule.onClick(RadioGroupModule.java:112)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at android.view.View.performClick(View.java:5609)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at android.view.View$PerformClick.run(View.java:22262)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at android.os.Looper.loop(Looper.java:154)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
04-18 12:38:25.965 26129-26129/com.unisaas.unisaas W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

So the LinearLayout that holds the RadioGroupModule does actually contain RadioGroupModule but they cannot be cast when calling getChildAt. The reason I want the RadioGroupModule at position is so that I can call setSelected false which will change the TextView backgroud colour and eventually the ImageView source when I get the asset.
Can anyone see a possible solution to this? Or is it not possible to do it this way?
Cheers for any help!
Edit:
I forgot to put the XML for the front end of the RadioGroupModule, it's below this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/ll_radio_group"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true">

    <ImageView
        android:id="@+id/img_radio_group"
        android:layout_width="60dp"
        android:layout_height="60dp" />

    <TextView
        android:id="@+id/txt_radio_group_text"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:textSize="22sp"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"/>

</LinearLayout>

A:

I have fixed this issue. The problem was down to the fact that there was both RadioGroupModules and LinearLayouts inside the parent layout when calling getChildAt, this lead to the separate ClassCastExceptions. The fixed and working loop looks like this.
        for(int i = 0; i < ll_radio_group_holder.getChildCount(); i++){
            try{

                RadioGroupModule radioGroupModule = (RadioGroupModule) ll_radio_group_holder.getChildAt(i);

                JSONObject jsonObject = radioGroupModule.getJsonObject();

                if(jsonObject.getInt("id") != correctObject.getInt("id")){
                    radioGroupModule.setSelectedFalse();
                    jsonObject.put("selected", false);
                } else {
                    radioGroupModule.setSelectedTrue();
                }

            } catch (Exception e){
                continue;
            }
        }


Q:

C++: Union vs Bitwise operators

I have two char's and I want to "stitch" them bitwise together.
For example:
char c1 = 11; // 0000 1011
char c2 = 5;  // 0000 0101
short int si = stitch(c1, c2); // 0000 1011 0000 0101

So, what I first tried was with bitwise operators:
short int stitch(char c1, char c2)
{
    return (c1 << 8) | c2;
}

But this doesn't work: I'm getting a short equals to c2... (1) Why?
(But: c1 and c2 are negative numbers in my real app... maybe this is a part of the problem?)
So, my second solution was to use a union:
union stUnion
{
    struct
    {
         char c1;
         char c2;
    }
    short int si;
}

short int stitch(char c1, char c2)
{
    stUnion u;
    u.c1 = c1;
    u.c2 = c2;
    return u.si;
}

This works like I want... I think
(2) What is the best/fastest way?
Thanks!

A:

The union method is implementation-defined at best (in practice, it will pretty reliably work but the format of si depends on the endianness of the platform).
The problem with the bitwise way is, as you suspect, the negative numbers. A negative number is represented by a chain of leading 1's. So -5 for example is
1111 1011

If you cast this to int or even unsigned int, it becomes
1111 1111 1111 … 1111 1011

and all those 1's will drown out the left-shifted data when OR is applied.
To solve the problem, cast the chars to unsigned char and then to int (to prevent overflow, or even the appearance of the possibility of overflow) before shifting:
short int stitch(char c1, char c2)
{
    return ( (int) (unsigned char) c1 << 8) | (unsigned char) c2;
}

or, if you are free to change the types of the arguments and you can include <cstdint>,
uint16_t stitch( uint8_t c1, uint8_t c2)
{
    return ( (int) c1 << 8 ) | c2;
}

A:

$5.8/1 states- "The operands shall be of integral or enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or reater than or equal to the length in bits of the promoted left operand."
So try to typecast c1 to unsigned int and then bitwise OR with C2. Also return the output as unsigned int. chars are promoted to int but we want to be 'unsigned int'


Q:

Regex-replace text when text contains more than one dot

I have to make a regex that replace text except numbers and only one dot
Here is my regex::
var a = text.replace(/[^0-9,.]/g, '');

But it does not replace dot. I have to replace dots more than one.
here is the code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<input production-qty ID="test"  ng-model="testmodel" type="text"  />
</div>

<script>
var app = angular.module("myApp", []);
app.directive('productionQty', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            function fromUser(text) {
                var transformedInput = text.replace(/[^0-9,.]/g, '');
                //var transformedInput = text.matches(/^[0-9]+(?:\.[0-9]+)?$/g);
                  console.log(transformedInput);
                if (transformedInput !== text) {
                    ngModelCtrl.$setViewValue(transformedInput);
                    ngModelCtrl.$render();
                }
                return transformedInput;
            }
            ngModelCtrl.$parsers.push(fromUser);
        }
    };
});
app.controller("myCtrl", function($scope) {

});
</script>

</body>
</html>

A:

update 2 :
you can do like this:
value.replace(/[\.]/g, function(match, offset, all) {
     return match === "." ? (all.indexOf(".") === offset ? '.' : '') : '';
  })

use this Link for description
update 1 :
You can do with some trick..
lets replace your first .with some other special character
mystring =  mystring.replace(/\./,$)

this will update only first dot to $
now update all the dots to blank
mystring  = mystring.replace(/\./g,' ')

now update that $ to dot
mystring = mystring.replace(/\$/g,.)


Q:

openGL glGenList Segmentation Fault on OSX

I am working with OpenGL and am having an issue using glGenLists. Every time I call it, I am getting a segfault. I wrote a simple program to test if it was the external libraries I was using, but discovered it was not. Here is the simple program:
#include "GLUT/glut.h"

int main(){
    GLuint list = glGenLists(1);
    return 0;
}

I am running this on Mac OS X 10.6.7 and am compile with:
g++ -framework OpenGL -framework GLUT -o test test.cpp

Any suggestions would be greatly appreciated

A:

I believe, before using any OpenGL commands, you have to set up your OpenGL context.
There are a few things you have to do before you can just jump in and draw some triangles. You have to let the OS know that you need a window of x size with y properties, and that you're going to be drawing in it with OpenGL.
If you don't know how to set up your OpenGL context, you could try this. It could be old and a bit deprecated, but it'll work :)


Q:

Mysql enum not searching record without quote value

I have table field with enum enum('0','1','2','3','4','5','6').
In query when I try with IN (1) it is not working but when I use IN ("1") it is working.
If I use In (1,2) it is working.
So when there is one value in "IN" clause then it should work without quote

A:

ENUM values are defined and stored as strings. They can be accessed via their string value or via their numeric index value (which starts at 1 and not 0).
Your enum values start at '0' which would have a numeric index value of 1. So, it would be possible to get some data back from your query using IN(1,2) but those numbers will be treated as the index and you will actually get data returned for records where the enum values are '2' and '3' (probably not what you think you are getting back).
IN(1) doesn't work because you have no data with an index value of 1 (emum value = '0')
IN('1') does work because you do have data with an enum value of '1'
Try this for a practical example
http://sqlfiddle.com/#!9/3993b/1
or read the section on Handling of Enumeration Literals in the mysql documentation


Q:

Binding a collection to Listbox

I basically started today with WPF, and I'm astounded by how difficult it is to do binding. I have an array of TextBoxes, in an ObservableCollection, and just want to bind that in my Listbox, so that they arrange themselves vertically.
I have fiddled around with this for 3 already, can you help?
I'm working in a WPF UserControl, not a window as so many tutorials seem to rely on.

A:

In your C# code, you can do something like this:
myListBox.ItemsSource = myTextBoxesCollection;

Or in your XAML code:
<ListBox ItemsSource="{Binding MyTextBoxesCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Text}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

For the XAML, MyTextBoxesCollection needs to be a public property on your data context. One way to set the DataContext could be, in your constructor:
DataContext = this;

A:

Having an ObservableCollection<TextBox> is alomost always the wrong approach.  You likely want an ObservableCollection<string> instead.
Then, in your ListBox (or ItemsCollection) you have the following code:
<ListBox ItemsSource="{Binding MyStrings}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding .}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


Q:

Add code coverage to Jasmine testing in browser

I use code coverage with npm and grunt locally, but I want to demonstrate this in browser.
If I open a codepen how can I have code coverage generated in browser?
Please show an example of this.
Here I'm testing a controller and Jasmine tests the code but I would like to know if it's 100% covered and show that in browser.
http://codepen.io/clouddueling/pen/Jwaru?editors=001
Could I submit my code to a server?  Have it tested instantly elsewhere like on heroku and get the results?
Can Instanbul run in the client somehow and output an html report or json string?

A:

You can use Blanket.js, which support jasmine test runner, to run a code coverage in the browser itself.
Here is a PLUNKER demonstrating your sample app and specs. Few key points to note here are:
<!-- Use of data-cover provided by blanket to test coverage of concerned file -->
<script type="text/javascript" src="app.js" data-cover></script>

Blanket js needs an adapter for jasmine. jasmine-blanket.js is the adapter shown in the plunker.
I preferred plunker over codepen. Hope that helps. Isn't this slick?
update 9-11-2017 blanket.js project is not actively maintained, you can see on their github repository.


Q:

Transformation of Confidence Interval = Confidence Interval of Transformation?

I am wondering about the following situation: I have a confidence interval estimator $\delta(x)=[lb, ub]$, which returns valid a%-confidence intervals for a value $\theta \in \mathbb{R}$ (not necessarily a parameter). How can I obtain a confidence interval for a value $f(\theta)$? In particular, i am interested in

f(x)=2*x-1
f(x)=x/(1-x)

The naive approach of simply transforming the bounds using $f$, that is, $\delta_f(x)=[f(lb), f(ub)]$ seems to produce confidence intervals with the correct $a\%$ coverage. However, given the existence of more complex procedures, like the delta method, this seems too good to be true.

A:

Assuming $f$ is strictly monotone, this method works:
$$lb < \theta < ub \implies f(lb) < f(\theta) < f(ub)$$
$$\theta \in [lb, ub] \implies f(\theta) \in [f(lb), f(ub)]$$
$$P(\theta \in [lb, ub]) \leq P(f(\theta) \in [f(lb), f(ub)])$$
Your second example is monotone when restricted to either x>1 or x<1, so if your CI doesn't cross 1, then you're good. If it crosses 1, then LOL, let's talk.


Q:

Application can't find settings or image files after windows boot

I have an application which boots after the windows boot. That works well, however the application can't seem to find the necessary csv file with settings or the necessary resources which result in a crash. However application works fine if I manually open it after I log in into my Windows account.
I tried to do a check if the csv file really exists, but as said above, the application can't find it. Since the csv file contains some settings and language data the application cannot run if the file isn't found
Before I read out the csv file, I check if the file exists by doing the following:
     try {
        string langFile = Path.Combine(Settings.Default.WorkingDirectory, "languageSupport.csv"); //Get language file
        // Read out the file
    } catch {
        MessageBox.Show("Could not load settings data!");
        Console.WriteLine("Error occured: " + e.Message);
    }

Also, I think it is important no note the following: This error only happens when the computer has been turned off for atleast a few hours. A reboot or shutting the pc down and turning it  back on after a few minutes doesn't give me the error.
What can I do to improve this? Why does it crash when it boots automatically and not when I boot it manually?

A:

It is because when it load automatically the working directory is different than when you open it manually from the .exe, try using AppDomain.CurrentDomain.BaseDirectory to make sure that paths are relative to your application, also you can use it to specify the .csv file path, assuming that the file is in the same directory as your application:
try {
        string langFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "languageSupport.csv"); //Get language file
        // Read out the file
    } catch {
        MessageBox.Show("Could not load settings data!");
        Console.WriteLine("Error occured: " + e.Message);
    }


Q:

Flask Run Function on button click

I am looking to make a web page to enable triggering few processes on network. I have decided to use flask as the research i did online overwhelming suggest flask being better for beginners.
I have written the following code as a sample and to test my knowledge. I want to trigger a process on button click. However it doesn't seem to render the next page on click. Any help would be appreciated.
from flask import Flask, render_template
import testt
app = Flask(__name__)
@app.route('/',methods=['GET', 'POST'])
def hello_world():
    return render_template('index.html')
@app.route('/my-link/',methods=['GET','POST'])
def my_link():
    testt.trial()
    work  = 'working'
    return render_template('process-complete.html',work= work)
if __name__ == '__main__':
    app.run()

process-complete.html
{% extends 'base.html' %}

{% block head %}
<title>Task Master</title>
{% endblock %}

{% block body %}

Flask Trial

 Process Completed {{work}}.

{% endblock %}

A:

The code below helped me execute the action i wanted to perform.

Click Below to Start the Process

Flask Trial


Q:

How to free a control in its own event?

I have a list of TPanels in a FMX application and I want to free a panel if I click on it.
To free them directly in the Onclick-handler is not the right way, because I get an access-violation. And I don't want to use windowsmessages (recommended in How to free control inside its event handler? and Why does my program crash when I destroy a button in its own OnClick handler?) because it is a firemonkey application and I do not know how these messages work on android and mac.
Is there another solution?

A:

Use myObject.Release:

Marks this TFmxObject object for delayed deletion.

Immediate actions in this method:

set Parent = nil
insert object into delayed delete list

Delayed action:

free object from list (vPurgatory).

Remember, that method Free (and procedure FreeAndNil) does not remove the object itself in mobile platforms:

// under ARC, this method isn't actually called since the compiler translates
  // the call to be a mere nil assignment to the instance variable, which then calls _InstClear


Q:

Spring Security Oauth2 Group

My current set of permissions in Spring supports users with a permission level in a group, so the following is true:
A User (implementing UserDetails) has a Permission (joining User + Group, giving GrantedAuthority) in a Group. For HTTP authentication, a user can perform actions in their group and switch between groups.
For api access, I am trying to allow a user to grant a particular client (with an id + secret) to access different scopes data. With standard Spring Security OAuth2, if I do this, they will be able to access all Group objects with a user's credentials. Is there a way that a user can authorize on a per Group basis in Spring Security / Spring Security Oauth2?

A:

You can add any kind of information (such as your group) to the access token's 'additional information', by implementing your own custom TokenEnhancer. It will be stored with the access token, and will be available in the resource server.


Q:

Most awesomely bad hack

As I sit watching one of my latest dirty dirty hacks run, I started wondering what kind of dirty hacks you have created that are so bad they are awesome.
We all have a few of them in our past - and they are probably still running in production somewhere, chugging along somehow still working.
Which reminds me of the hack we had to put into place when we were moving data centers. Our IVRs had to keep running, as the data center we were moving from was the primary DC, and the new Primary wasn't quite ready to take traffic. So what do we do. Well we answer the calls in DC1, then ship the sip stream over the internet to DC2 1900 miles away ... that just felt oh so wrong.
So the question is, what is one (or more) of your awesomely bad hacks?

A:

A company I worked at a quite a few years ago had restricted network access on all our computers. You could access 1 terminal server, and any page on 1 domain (the intranet). That was it. This was well before I started my work in IT and I was considered lower than low by the IT department.
This, infact, made it impossible for us to do our jobs and after months of complaining to management (I love beaurocracy) they finally gave us ONE computer with unrestricted access, that all 12 of us had to share on the "rare occasion" we needed to go off-domain (which was almost all the time).
So, I brought in a spare 24-port switch, plugged the network cable from that machine into the switch and then bought dozens of dual-port NICs, and silently cabled everyones machines onto the 2nd switch and set up custom routes on each machine so that people could still access the segregated network. I then hid all the cables and the switches so nobody would find out.
I was everyones hero for 6 months, they could finally have internet access just as long as the boss wasn't looking.
Of course, as this is Server Fault everyone will be looking at this post, HORRIFIED that I could do such a thing. Well, if it makes you feel any better when they found out I was promptly fired, but I think that's when I decided to go to Uni and get a better education so that I could be in a position to ensure that other people don't have to go through that.
(And if I found that anyone had done this on any of my networks, I would strongly be pushing for an official reprimand. Hey, I was young).

A:

Probably not the kind of thing you're looking for but back a little bit I had a couple of Commodore 264 series machines. Specifically the Plus/4 and C16. Needing an assembler but being unable to find one for those machines I set about to create one. How do you compile an assembler when you don't already have one? Write a simple one in BASIC first, then translate it line by line into assembly once it's working and compile it with itself.

A:

I sold dozens of HP ProLiant ML370 G3 servers between 2003 and 2005. The failure mode of this hardware was quite interesting, as the fan sensors on the system board would eventually fail after 5 years. The system wouldn't detect fan presence or spin/speed status at POST, so one would need a shop-vac (vacuum) to force the system fans to spin at a high enough rate during boot in order to keep the server on past POST. After that, cooling was achieved with an external fan... Availability of replacement boards from HP was poor and there was a shortage among parts resellers, too.
The setup had to hold for 5 days while I tried to make arrangements to fly to the customer site 2000 miles away with new hardware during the December holiday season. We made it, though!


Q:

Interface 'Psr\Log\LoggerInterface' not found in /opt/lampp/vhosts/development.com/htdocs/test/Monolog/Logger.php

I am trying to execute basic example of monolog. I have tried follwing code.
My index.php file is
 <?php
        include_once __DIR__ . '/Psr/Log/LoggerInterface';
        include_once __DIR__ . '/Psr/Log/AbstractLogger';
        include_once __DIR__ . '/Psr/Log/LogLevel';
        include_once __DIR__ . '/Psr/Log/InvalidArgumentException';
        include_once __DIR__ . '/Monolog/Logger.php';
        include_once __DIR__ . '/Monolog/Handler/HandlerInterface.php';
        include_once __DIR__ . '/Monolog/Handler/AbstractHandler.php';
        include_once __DIR__ . '/Monolog/Handler/AbstractProcessingHandler.php';
        include_once __DIR__ . '/Monolog/Handler/StreamHandler.php';

        include_once __DIR__ . '/Monolog/Formatter/FormatterInterface.php';
        include_once __DIR__ . '/Monolog/Formatter/NormalizerFormatter.php';
        include_once __DIR__ . '/Monolog/Formatter/LineFormatter.php';
        use Monolog\Logger;
        use Monolog\Handler\StreamHandler;

        $logger = new Logger("my_name");
        $logger->pushHandler(new StreamHandler("test_log.log", Logger::DEBUG));

        $log->addWarning('Foo');
        $log->addError('Bar');
    ?>

I am getting following error
Fatal error: Interface 'Psr\Log\LoggerInterface' not found in /opt/lampp/vhosts/development.com/htdocs/test/Monolog/Logger.php on line 28

My folder structure is
/opt/lampp/vhosts/development.com/htdocs/test
/opt/lampp/vhosts/development.com/htdocs/test/Monolog
/opt/lampp/vhosts/development.com/htdocs/test/Psr
/opt/lampp/vhosts/development.com/htdocs/test/index.php

Could you please suggest me about this. Thanks in advance.

A:

Installed the composer.phar file in the main folder.
$php composer.phar install


Q:

ora-1658: unable to creat initial extent for segment in tablespace

i'm getting the error "ora-1658: unable to create initial extent for segment in tablespace MYTBS" when trying to import a dump using imp command.i'm using oracle XE 11.2 in a standalone windows machine. database backup is around 200MB. following is my table space setup.
how can i correct this error? schema that i'm trying to import has tables defined for tables space MYTBS.

A:

The error should

ora-01658 unable to create initial extent for segment in tablespace  ????

to solve the problem:
You will need an account with DBA privileges to do one of two things , and link

extend the datafile to add space (ALTER DATABASE DATAFILE  RESIZE ) , or autoextend (ALTER DATABASE DATAFILE  autoextend on)
Changing Datafile Size
add a new datafile to the tablespace (ALTER TABLESPACE  ADD DATAFILE
ALTER TABLESPACE

And if your datafile has been reached 32GB , please refer to this answer.


Q:

How to load a java.util.Set with snakeYAML

I try to load the following yaml sequence :
- Person(paul):
firstName: Paul
lastName: Lumbergh
children :
    - Person(bill)
    - Person(jane)

which i tried to load in the following bean :
public class Person {

private long id;
private String firstName;
private String lastName;
private Person father;
private Set<Person> children;
}

I got this error which is due to the fact that snakeYaml load my sequence in a java.util.List instead of java.util.Set.
Is it a way to force snakeYAML to load a sequence in a java.util.Set ?
org.yaml.snakeyaml.error.YAMLException: org.yaml.snakeyaml.error.YAMLException: Cannot set property='children' with value='[Person [firstName=Bill, secondName=Lumbergh], Person [firstName=Jane, secondName=Lumbergh]]' (class java.util.ArrayList) in Person [firstName=Paul, secondName=Lumbergh]
at org.yaml.snakeyaml.extensions.compactnotation.CompactConstructor$ConstructCompactObject.construct(CompactConstructor.java:163)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:183)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructSequenceStep2(BaseConstructor.java:277)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructSequence(BaseConstructor.java:248)
at org.yaml.snakeyaml.constructor.SafeConstructor$ConstructYamlSeq.construct(SafeConstructor.java:440)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:183)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructDocument(BaseConstructor.java:142)
at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:128)
at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:480)
at org.yaml.snakeyaml.Yaml.load(Yaml.java:411)
at com.pearson.fixy.Fixy.loadEntities(Fixy.java:105)
at com.pearson.fixy.Fixy.load(Fixy.java:126)
at com.dvidea.TestFixy.test(TestFixy.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

A:

According to the yaml specification the set syntax is the following one :
- Person(paul):
  firstName: Paul
  lastName: Lumbergh
  children : !!set ? Person(bill) ? Person(jane) –


Q:

Problems Submit Button

I'm new to web programing. I'm trying to learn PHP and HTML. I created an Home Page (index.html) with a navigation bar. I put there an href to a form called register_form.php, it goes to the page but after I type all the information and click in the register button, it goes to the source page. I tried to find some answers, searching, but i can't solve the problem. I use a program to send my files and have PHP, it is XAMP. I activated all modules expcept tomcat, because i'm not able.
Register_form.php

<link rel="stylesheet" type="text/css" a href="web_style.css"/>

    <form action="register.php" method="POST">
    First Name: <input type="text" name="name" />

    Last Name: <input type="text" name="lname" />

    Username: <input type="text" name="uname" />

    Email:
<input type="text" name="email1" />

    Confirm Email: <input type="text" name="email2" />

    Password: <input type="password" name="pass1" />

    Confirm Password: <input type="password" name="pass2" />

        <input class="reg" type="submit" value="Register" name="submit" />

    </form>

register.php
<?PHP
require('config.php');

$erro = '';

if(isset($_POST['submit'])){

//Verificacao
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$pass1=$_POST['pass1'];
$pass2=$_POST['pass2'];

if($email1==$email2){
    if($pass1==$pass2){
        //Continuar

        $name=mysql_escape_string($_POST['name']);
        $lname=mysql_escape_string($_POST['lname']);
        $uname=mysql_escape_string($_POST['uname']);
        $email1=mysql_escape_string($_POST['email1']);
        $email1=mysql_escape_string($email1);
        $email2=mysql_escape_string($email2);
        $pass1=mysql_escape_string($pass1);
        $pass2=mysql_escape_string($pass2);

        mysql_query("INSERT INTO login_data (name, lname, uname, email, pass) VALUES ('".$name."','".$lname."','".$uname."','".$email1."','".$pass1."')");
        header("Location: index.html");
    }else{

        echo $erro;

        exit();
    }
}else{
    echo 'Sorry, your emails do not match.
';
}}
?>

If you need more information please tell me. Thanks in advance

A:

The only problem that can imagine is that your web pages are not inside c:\xampp\htdocs\ or you not running your pages from localhost.
So move your files there (if they are not there) and run from localhost (if you not running your webpages from there). Your url should be like this localhost/path/to/register_form.php and not like this file:///C:/xampp/htdocs/path/to/register_form.php


Q:

How to make MySQL Database calls in Tornado for an application with highly scalable infrastructure which makes a high number of database queries?

So which will be a better method to make database calls in Tornado for a high performance application with highly scalable infrastructure which makes a high number of database queries?
Method 1 : So I have come across async database drivers/clients like TorMySQL, Tornado-Mysql, asynctorndb,etc which can perform async database calls.
Method 2 : Use the general and common MySQLdb or mysqlclient (by PyMySQL) drivers and make the database calls to separate backend services and load-balance the calls with nginx.
Similar to what the original Friendfeed guys did which they mentioned in one of the groups,
Bret Taylor, one of the original authors, writes :

groups.google.com/group/python-tornado/browse_thread/thread/9a08f5f08cdab108
We experimented with different async DB approaches, but settled on
  synchronous at FriendFeed because generally if our DB queries were
  backlogging our requests, our backends couldn't scale to the load
  anyway. Things that were slow enough were abstracted to separate
  backend services which we fetched asynchronously via the async HTTP
  module.

Other supporting links for Method 2 for better understanding what I am trying to say are:

StackOverFlow Answer

Method 3 : By making use of threads and IOLoop and using the general sync libraries.
Supporting example links to explain what I mean,

What the Tornado wiki says, https://github.com/tornadoweb/tornado/wiki/Threading-and-concurrency

Do it synchronously and block the IOLoop. This is most appropriate for
  things like memcache and database queries that are under your control
  and should always be fast. If it's not fast, make it fast by adding
  the appropriate indexes to the database, etc.

Another sample Method :
For sync database(mysqldb), we can
executor = ThreadPoolExecutor(4)
result = yield executor.submit(mysqldb_operation)

Method 4 : Just use sync drivers like MySQLdb and start enough Tornado Instances and load balance using nginx that the application remains asynchronous on a broader level with some calls being blocked but other requests benefit the asynchronous nature via the large number of tornado instances.
'Explanation' :
For details follow this link - www.jjinux.com/2009/12/python-asynchronous-networking-apis-and.html, which says :

They allow MySQL queries to block the entire process. However, they
  compensate in two ways. They lean heavily on their asynchronous web
  client wherever possible. They also make use of multiple Python
  processes. Hence, if you're handling 500 simultaneous request, you
  might use nginx to split them among 10 different Tornado Web
  processes. Each process is handling 50 simultaneous requests. If one
  of those requests needs to make a call to the database, only 50
  (instead of 500) requests are blocked.

A:

FriendFeed used what you call "method 4": there was no separate backend service; the process was just blocked during the database call.
Using a completely asynchronous driver ("method 1") is generally best. However, this means that you can't use synchronous libraries that wrap the database operations like SQLAlchemy. In this case you may have to use threads ("method 3"), which is almost as good (and easier than "method 2").
The advantage of "method 4" is that it is easy. In the past this was enough to recommend it because introducing callbacks everywhere was tedious; with the advent of coroutines method 3 is almost as easy so it is usually better to use threads than to block the process.


Q:

covering subsets

Let $A=\left\{ {1, 2,  \ldots, n}\right\}$.
Let $B$ be the set of all size $m$ subsets of $A$.  $B=\left\{{B_1,B_2, \ldots , B_{\binom{n}{m}} } \right\}$, $  |B_i|=m$
then we want to find $k$ subsets of $A$, each of size $r$, (let call them  $C=\left\{{C_1,C_2,\ldots,C_k}\right\}$, $|C_i|=r$ ), so that for any $B_i$, there exists at least one $C_j$ in $C$ so that the intersection of $B_i$ and $C_j$ is empty.
Example,
if $n=7$, $m=3$, $r=2$,
then with $k=7$ subsets we can build $C$ as follows:
$C=\left\{
{\left\{ {1, 2}\right\},
\left\{ {2, 3}\right\},
\left\{ {3, 4}\right\},
\left\{ {4, 5}\right\},
\left\{ {5, 6}\right\},
\left\{ {6, 7}\right\},
\left\{ {7, 1}\right\}}\right\}$
which has the property that for any subset of $A$ of size $m=3$, denoted by $B_i=\left\{{b1,b2,b3}\right\}$,  there is at least one $C_j$ in $C$, that has no intersection with $B_i$.
The question is given $n$,$m$, and $r$, what is the minimum $k$ for which a corresponding $C$ exists?

A:

If you replace the sets $C_j$ by their complements $C_j'$, then each $B_i$ must be contained in some $C_j'$.  This is called a covering design.  The La Jolla Covering Repository is a great place to look.


Q:

Calculus of rank three tensor

Let $A(\alpha)$ be a matrix that depends to vector parameter $\alpha$. I want to approximate $A(\alpha+\Delta\alpha)$ using Taylor expansion.
My work:
$$
A(\alpha+\Delta\alpha) \approx A(\alpha)+\frac{dA}{d\alpha}\Delta\alpha
$$
Since $A$ is a matrix and $\alpha$ is a vector, I know that $\frac{dA}{d\alpha}$ is a rank three tensor. I'm not familiar with tensor and tensor calculus. I just know it looks like a 3-dimensional array.
My questions:
1) How I should calculate $\frac{dA}{d\alpha}$?
2) How I should calculate $\frac{dA}{d\alpha}\Delta\alpha$?
Thanks.

A:

Easiest is to use indices:
$$\left(\frac{dA}{d\alpha}\Delta \alpha\right)_{ij} = \sum_k \frac{\partial A_{ij}}{\partial \alpha_k} \Delta \alpha_k.$$
If you really want to store $\frac{dA}{d\alpha}$ separately, as you say you can do so in a three-dimensional array, where the $ijk$ entry is e.g. $\frac{\partial A_{ij}}{\partial k}$. Multiplying by vector $\Delta \alpha$ then corresponds to taking a linear combination of "matrices slices" of $\frac{dA}{d\alpha}$, just as matrix-vector multiplication corresponds to taking a linear combination of column vectors.


Q:

Sockets on a private network

I'm developing a two part product. One part is a C# app on a single board computer running Windows Embedded Standard. The other piece is an embedded device running an RTOS with a TCP/IP stack. The two devices need to communicate via an Ethernet cable. It's a point to point connection. Nothing is connected to any outside network.
I'm a bit of a network programming novice, so I'm looking for best practices. I'm making the assumption that TCP sockets is the most straightforward approach. I figured I'd get some advice before writing any code and getting lost.
The one thing that is guaranteed is that the embedded device will maintain a static IP address of 169.254.1.1. That's about all I know. So what do I need to know to get these guys connected? I know there are issues with subnets... but that's where my knowledge is falling short. Which should be the client, which is the server, port numbers etc.
Little more info per request: The two ends are going to be exchanging a pretty simple binary protocol. That part is already defined and it working over an RS-232 link. But the RS-232 port is going away. I want to use TCP to basically carry this information, plus give me all the the good stuff like retries and error checking. Either end of the system can initiate a transfer.

A:

You might want to look into some introduction to socket programming, like http://beej.us/guide/bgnet.
The windows node will have to configure a network interface in the same
subnet as the rtos device and choose a (different) ip address from that
subnet.
Which device is the server and waits for a connection depends on your
application, maybe also on the boot order of the two nodes. For example,
if the RTOS device has booted first, it might wait for a TCP connection
until the other side is ready.
Of course, you'll need some protocol inside the tcp stream. Possibly UDP
might also be an option, if you don't need the features TCP provides. This
might also reduce the memory footprint on the RTOS side.
If the two sides can reboot (or crash :-) indenpedently from each other without
some hardware watchdog taking note, be sure that the other side recognizes the
reboot (e.g. with the tcp keepalive feature), so that you can reestablish the
connection.
With TCP you'll get the reliable connection, but depending on you application,
you might discover that the Nagle algorithm keeps your message latency higher
than what the RS232 setup had. Use the NO_DELAY option on the socket to avoid
this.


Q:

imagemagick cropped images to pdf: pdf maintains cropped dimensions

I have a few large pngs. I'm cropping them with convert and then creating a pdf from them.
find . -name 'test_*.png' -exec convert -crop 600x1000+400+50 {} {} \; -exec echo {} \;
convert `ls -v test_*.png` test.pdf

It all works well enough. The images are cropped fine. The pdf is generally fine. The problem is that each page of the resulting pdf has white padding which matches the pre-cropped image size.
Am I missing a step to reset the image size metadata or something?

A:

I think this might be better:
find . -name 'test_*.png'  -print -exec convert {} -crop 600x1000+400+50 +repage {} \;
convert test_*.png test.pdf

I think -print amounts more succinctly to -exec echo {} \;
The preferred order of ImageMagick commands is:
convert input.png ... output.png

The +repage makes an image forget its previous canvas size.


Q:

How to get the name of a channel and role from an id in a discord bot python

I have the id of roles but I need to find a way to get their names. I have tried using ctx.guild.get_role("roleid").name but it seems that it dose not give the good datatype. The same goes for text channels and users.

A:

You can use discord.utils.get:
from discord.ext import commands
from discord.utils import get

def getter(iterables, id: int):
    data = get(iterables, id=id)
    return data

@bot.command()
async def display_data(ctx):
    #Get roles
    role = getter(ctx.guild.roles, id)
    #Get channels
    channel = getter(ctx.guild.channels, id)
    #Get users
    user = getter(ctx.guild.members, id)

    await ctx.send(f"Data found:\nRole:{role.name}\nChannel:{channel.name}\nUser:{user.name}")

Data types:

User → Member object
Role → Role object
Channel → TextChannel or VoiceChannel object

Reference: discord.py documentation


Q:

Better alternatives to assert(false) in C/C++

Currently, I write
assert(false);

at places that my code is never supposed to reach. One example, in a very C-ish style, is:
int findzero( int length, int * array ) {
  for( int i = 0; i < length; i++ )
    if( array[i] == 0 )
      return i;
  assert(false);
}

My compiler recognizes that the program finishes once assert(false) has been reached. However, whenever I compile with -DNDEBUG for performance reasons, the last assertion vanishes and the compiler warns that the execution finishes the function without a return statement.
What are better alternatives of finishing off a program if a supposedly unreachable part of the code has been reached? The solution should

be recognized by the compiler and not produce warnings (like the ones above or others)
perhaps even allow for a custom error message.

I am explicitly interested in solutions no matter whether it's modern C++ or like 90s C.

A:

Replacing your assert(false) is exactly what "unreachable" built-ins are for.
They are a semantic equivalent to your use of assert(false). In fact, VS's is spelt very similarly.
GCC/Clang/Intel:
__builtin_unreachable()

MSVS:
 __assume(false)

These have effect regardless of NDEBUG (unlike assert) or optimisation levels.
Your compiler, particularly with the above built-ins but also possibly with your assert(false), nods its head in understanding that you're promising that part of the function will never be reached. It can use this to perform some optimisations on certain code paths, and it will silence warnings about missing returns because you've already promised that it was deliberate.
The trade-off is that the statement itself has undefined behaviour (much like going forth and flowing off the end of the function was already). In some situations, you may instead wish to consider throwing an exception (or returning some "error code" value instead), or calling std::abort() (in C++) if you want to just terminate the program.

There's a proposal (P0627R0), to add this to C++ as a standard attribute.

From the GCC docs on Builtins:

If control flow reaches the point of the __builtin_unreachable, the program is undefined. It is useful in situations where the compiler cannot deduce the unreachability of the code. [..]

A:

As a fully portable solution, consider this:
template<typename T>
[[ noreturn ]] void unreachable(const T& msg = "<No Message>") {
    std::cerr << "Unreachable code reached. Message: " << msg << std::endl;
    std::abort();
}

The message part is, of course, optional.


Q:

mysql group by column error when alias specified

Following mysql query gives an error: 'email.id' isn't in GROUP BY, 1055
SELECT contact_a.id as contact_id,
  contact_a.sort_name  as `sort_name`,
  contact_a.display_name  as `display_name`,
  phone.id as phone_id,
  phone.phone_type_id as phone_type_id,
  phone.phone as `phone`,
  email.id as `email_id`,
  email.email as `email`,

FROM contact_table contact_a
  LEFT JOIN email ON (contact_a.id = email.contact_id)
  LEFT JOIN phone ON (contact_a.id = phone.contact_id)

 GROUP BY contact_a.id,
  `sort_name`,
  `display_name`,
  `phone_id`,
  `phone_type_id`,
  `phone`,
  `email_id`,
  `email`";

eventhough I've specified the alias of email.id in GROUP BY.
If I replace the alias email_id in GROUP BY with email.id, it works.
But why can't I use the alias in GROUP BY and how can it work for other alias like phone_id, phone_type_id, email etc ?

A:

Since mysql extends the mysql standard and allows you to use column aliases in the group by clause, the only think you need to pay attention to is not to use the same alias as an existing field name in any of the tables referenced in the from clause.
In case you use the same alias as an existing field, then mysql will interpret the group by clause as if it refferred to the existing field, not to the aliased one. This causes the above error message.


Q:

Accidentally sent a work-in-progress to a stranger

I was sending files between two email accounts and accidentally sent the first 8k words of a work-in-progress to a stranger. I'm not published, should I be worried or am I being arrogant? Is there anyway for me to protect myself legally?

A:

I'd send the person an email apologizing for accidentally sending them the document and requesting them to ignore it and throw it away.
The probability that a random stranger is going to be interested in stealing your work is pretty close to zero. Unless he's a writer himself, odds are he doesn't have the faintest idea how to go about publishing it. He probably has no idea how copyright law works, or what steps if any you may have taken to protect your rights, so he'd have no idea if he could get away with stealing your work.
And in any case, advice I give to new writers all the time: Many new writers worry way too much about someone stealing their work. Don't waste a lot of time protecting yourself from thieves. Spend your time writing and polishing your work to get it to the point where it would be worth stealing.
Yes, there are people out there who steal others' work. But it's not like there are millions of them just waiting to pounce. You take reasonable precautions and don't worry about it. There are a lot more people who will steal your television than will steal your writing. But if you're like most people, that doesn't mean that you cower in the corner clutching your television to your chest and holding a shotgun. You take a few reasonable steps, like locking your doors and not advertising to the world a list of all the valuables in your house, and get on with your life. Likewise, if you hope to ultimately be paid for your work, I wouldn't make a habit of emailing it to random strangers, or posting it on the Internet. I'd certainly register the copyright when you're ready to publish. And that's about it.
Realistically, the thieves are more likely to steal from famous authors, not little people like you and me.
BTW: I have had my work stolen, sort of. I found an article I posted on my web site being sold on one of those "we'll write your term paper for you" sites. But as I was publishing on the web where anyone could get it for free anyway, I didn't much care.


Q:

Java 8 LocalDate: Determine What Monday of the Month its (1st, 2nd, 3rd, etc)

I'm trying to figure out how to determine whether a particular Monday is the first, second, third or fourth Monday of a given month. I've figured out how to get the next Monday and the Week of the of month that resides in using the LocalDate class.
LocalDate now = LocalDate.of(2018, 2, 1);
LocalDate nextMonday = now.with(next(DayOfWeek.MONDAY));
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int week = nextMonday.get(weekFields.weekOfMonth());

Case in the example above, the code gets the next Monday and the week it resides in. Week is the second week of Feb, but that Monday is not the second Monday, it's the first. Any help with this would be greatly appreciated.

A:

You should not use your own arithmetic for this. Use the built-in functionality:
    int week = nextMonday.get(ChronoField.ALIGNED_WEEK_OF_MONTH);

With the date from your code this yields:
1

Which means that the Monday you got (February 5) is the 1st Monday of the month. Also you don’t need any WeekFields because the first Monday of the month is the first Monday of the month no matter which day is the first day of week, or how weeks of the year are numbered.
Date arithmetic is often complicated and easy to get wrong. Which also means that even if you finally get your calculation right, it is hard for a reader to convince herself/himself that your code is correct. So it is always better to use the built-in functionality that we trust to be tested and which uses explanatory names rather than numbers like 1 and 7.
You may be surprised that the field to use is called ALIGNED_WEEK_OF_MONTH. Think of aligned weeks as a week that begins on the 1st of the month no matter the day-of-week, and the following weeks right after each other. In February 2018, the first aligned week goes from Thursday, Feb 1 to Wednesday, Feb 7. The following aligned weeks begin on Thursdays Feb 8, Feb 15 and Feb 22. Obviously the first Monday of the month falls in aligned week 1, the 2nd Monday in aligned week 2, etc. Therefore it works to use ALIGNED_WEEK_OF_MONTH.

A:

Edit: You should take Ole V. V's answer (ChronoField.ALIGNED_WEEK_OF_MONTH) instead of this answer.
You could figure out what day of the month it is, divide by 7, and add 1:
LocalDate nextMonday = now.with(next(DayOfWeek.MONDAY));
int weekNo = ((nextMonday.getDayOfMonth()-1) / 7) +1;

For example, this code:
LocalDate now = LocalDate.of(2018, 2, 1);
for(int i = 0; i < 10; i++) {
    now = now.with(next(DayOfWeek.MONDAY));
    int weekNo = ((now.getDayOfMonth()-1) / 7) +1;
    System.out.println("Date : " + now + " == " + weekNo);
}

Prints out the following, which is what I believe you want...
Date : 2018-02-05 == 1
Date : 2018-02-12 == 2
Date : 2018-02-19 == 3
Date : 2018-02-26 == 4
Date : 2018-03-05 == 1
Date : 2018-03-12 == 2
Date : 2018-03-19 == 3
Date : 2018-03-26 == 4
Date : 2018-04-02 == 1
Date : 2018-04-09 == 2


Q:

Global.asax Error handling: Quirks of server.transfer

In my global.asax, I am checking for a 404, and transferring to the 404 error page as per the below:
    If HTTPExceptionInstance.GetHttpCode = 404 Then

        Server.ClearError()

        Response.TrySkipIisCustomErrors = True
        Response.Status = "404 Not Found"

        Server.Transfer("~/Invalid-Page.aspx")

    End If

The problem is, my Invalid-page.aspx uses some session code (Session("somevariable")), which throws an exception "Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. " because I am using a server.transfer (I believe this is a known issue?).
If I use a Response.Redirect, there is no problem. However, this would mean that the header of the error page is a 200, not a 404.
What would be the best workaround for this?

A:

Weird! Server.TransferRequest does exactly what I want without losing the session state!


Q:

MVC3 uploadify Jquery plugin error HTTP 404 and IO error

I am using Uploadify v3.1 for MVC3 C#.
My cshtml code is
<div class="container_24">
    <input type="file" name="file_upload" id="file_upload" />
</div>

My js code is
$(document).ready(function () {
    $('#file_upload').uploadify({
        'method': 'post',
        'swf': '../../Scripts/uploadify-v3.1/uploadify.swf',
        'uploader': 'DashBoard/UploadFile'
    });
});

And the controller code is
[HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
                file.SaveAs(path);
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index", "Home");
        }

Now when i click the upload button it show two errors, sometime it show IO error and sometime it show HTTP 404 error for some file. what is wrong ? help me please ?

A:

What size files are you uploading? Everything over 1MB or anything under?
Also what sort of 404 are you getting? If it's a 404.13 (file size error) then you're having the same problem I had. Good news. Because I fixed my problem. :)
If you're not sure what type the 404 is (Firebug will tell you), check your Windows event log and look in the "Application" log for a warning that looks like this:

Event code: 3004
Event message: Post size exceeded allowed limits.

If you've got both of these, then the problem is that IIS (which I'm assuming you're using) is not set up to allow big enough content requests.
Firstly, put this in your web config:
 <system.webServer>
    <security>
      <requestFiltering>
        <!-- maxAllowedContentLength = bytes -->
        <requestLimits maxAllowedContentLength="100000000" />
      </requestFiltering>
    </security>
  </system.webServer>

Then this, in "system.web":
<!-- maxRequestLength = kilobytes. this value should be smaller than maxAllowedContentLength for the sake of error capture -->
<httpRuntime maxRequestLength="153600" executionTimeout="900" />

Please pay attention to the notes provided - maxAllowedContentLength is in BYTES and maxRequestLength in KILOBYTES - big difference.
The maxAllowedContentLength value I provided will let you up load anything upto around 95MB.
This solved my version of this problem anyway.


Q:

css separator of two float divs

http://jsfiddle.net/dx6m9/

          Ahoj

            Nazdar

            Ahoj

             Nazdar

            Ahoj

how to force the right border to be always long as longer of these two float divs?
That border should acts just like a separator.

A:

Try:
.floated {display:table-cell;}
.container {width: 100%;display:table}

Fiddle here.

A:

I would approach this by adding a 3rd seperator div Fiddle and set this to 40% left.
.sep {
    position: absolute;
    left:40%;
    top:0;
    bottom:0;
    border-left: 1px dotted #ddd;
}
.container {
    width: 100%;
    position:relative
}


Q:

Change onclick action to an automatic action

I have the following JavaScript code:
onclick = function(){ infocontainer.appendChild(info); }

But that works only when I click somewhere else on my page. How can I change the onclick action to an automatic action without the need to click?

A:

According to your explanation
You can use this:
window.onload = function() {
  yourFunction(param1, param2);
};

This will load yourFunction when the page is done loading


Q:

How to change `ReflectionIT.Mvc.Paging` package style in asp.net core

I am working on a Asp.net core 2.2 project and use ReflectionIT.Mvc.Paging package for paging.
Every thing is ok but i want to change paging style in my view.
Here is code to use Pager view component

        @await this.Component.InvokeAsync("Pager", new { PagingList = this.Model })

And here is paging pic :

I want to write First And Last instead of 1 And 15 in above pic and want to change some css styles.

A:

You can also create your own Pager view if you want to. You store it in the folder Views\Shared\Components\Pager :

You can for instance call the AddPaging method which you can use to set the PagingOptions. This allows you to specify which View is used for the Pager ViewComponent , in ConfigureServicesfunction :
// Register ViewComponent using an EmbeddedFileProvider & setting some options
services.AddPaging(options => {
    options.ViewName = "Bootstrap5";
    options.HtmlIndicatorDown = " ↓";
    options.HtmlIndicatorUp = " ↑";
});

Modify the Bootstrap5.cshtml to fit your requirement :
@model  ReflectionIT.Mvc.Paging.IPagingList

@* Fake Boostrap 5 based pager *@

@{
    var start = this.Model.StartPageIndex;
    var stop = this.Model.StopPageIndex;
}

@if (this.Model.PageCount > 1) {

        @if (start > 1) {

                    First

        }

        @if (this.Model.PageIndex > 1) {

                    «

        }

        @for (int i = start; i <= stop; i++) {

            @if (i == 1)
                {
                    @Html.ActionLink("First", Model.Action, Model.GetRouteValueForPage(i), new { @class = "page-link" })
                }
                else{
                    @Html.ActionLink(i.ToString(), Model.Action, Model.GetRouteValueForPage(i), new { @class = "page-link" })
                }

        }

        @if (this.Model.PageIndex < this.Model.PageCount) {

                    »

        }

        @if (stop < this.Model.PageCount) {

                    Last

        }

}

Output :


Q:

Audit trail code not picking up combobox list changes

I have looked at this post: Saving changes to a multivalued ComboBox via AuditTrail
And tried to take tidbits and put it into my code, but it just didn't work! I am not really great at SQL but I need to get this done. Here is my code and it works for textboxes, but can someone tell me exactly where and exactly what to put what I need for my combobox dropdown list changes?
Thanks in advance!!
Function LogChanges(lngID As Long, Optional strField As String = "")
    Dim dbs As DAO.Database
    Dim rst As DAO.Recordset
    Dim varOld As Variant
    Dim varNew As Variant
    Dim strFormName As String
    Dim strControlName As String

    varOld = Screen.ActiveControl.OldValue
    varNew = Screen.ActiveControl.Value
    strFormName = Screen.ActiveForm.NAME
    strControlName = Screen.ActiveControl.NAME
    Set dbs = CurrentDb()
    Set rst = dbs.TableDefs("ztblDataChanges").OpenRecordset

    With rst
        .AddNew
        !FormName = strFormName
        !ControlName = strControlName
        If strField = "" Then
            !FieldName = strControlName
        Else
            !FieldName = strField
        End If
        !RecordID = lngID
        !UserName = Environ("username")
        If Not IsNull(varOld) Then
            !OldValue = CStr(varOld)
        End If
        !NewValue = CStr(varNew)
        .Update
    End With
    'clean up
    rst.Close
    Set rst = Nothing
    dbs.Close
    Set dbs = Nothing
End Function

A:

You can't  get the values of multi-valued fields using .Value and .OldValue. These properties always return Null. As far as I know, there's no reliable way to get the old value (also, a proper audit trail doesn't need an old value, since the old value is the previously added new value if everything gets audited properly).
When only saving the new values, and if you're saving them into a text field and not a multivalued field, you could use the following:
Use this function to get a string value for all selected items:
Public Function JoinMVF(MVFControl As Control, Optional Delimiter As String) As String
    Dim i As Variant
    For Each i In MVFControl.ItemsSelected
        JoinMVF = JoinMVF & MVFControl.ItemData(i) & Delimiter
    Next i
End Function

And then, adjust your recordset piece to the following:
With rst
    .AddNew
    !FormName = strFormName
    !ControlName = strControlName
    If strField = "" Then
        !FieldName = strControlName
    Else
        !FieldName = strField
    End If
    !RecordID = lngID
    !UserName = Environ("username")
    If Not IsNull(varOld) Then 'varOld will always be Null for a multi-valued field
        !OldValue = CStr(varOld) 'Thus this will never get called
    End If
    'Add some If multivalued field then
    !NewValue = JoinMVF(Screen.ActiveControl, "; ")
    .Update
End With


Q:

Push notification to android from ASP.NET webservices

Please help me, I have a problem to push notification for android from ASP.NET webservice (VB.NET).
this is my code.
Public sApplicationID As String = "YYY....ZZZ"
Public sSENDER_ID As String = "222...555"

<WebMethod()> _
Public Function SendMessage(ByVal RegistrationID As String, ByVal Message As String) As String
    Dim regid As String = RegistrationID
    Dim tRequest As WebRequest
    tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send")
    tRequest.Method = "post"
    'tRequest.ContentType = " application/json"
    tRequest.ContentType = " application/x-www-form-urlencoded"
    tRequest.Headers.Add(String.Format("Authorization: key={0}", sApplicationID))

    tRequest.Headers.Add(String.Format("Sender: id={0}", sSENDER_ID))

    Dim postData As String = "{""collapse_key"":""score_update"",""time_to_live"":108,""delay_while_idle"":1,""data"":{""message"":""" & Convert.ToString(Message) & """,""time"":""" & System.DateTime.Now.ToString() & """},""registration_ids"":" & regid & "}"
    Console.WriteLine(postData)
    Dim byteArray As [Byte]() = Encoding.UTF8.GetBytes(postData)
    tRequest.ContentLength = byteArray.Length

    Dim dataStream As Stream = tRequest.GetRequestStream()
    dataStream.Write(byteArray, 0, byteArray.Length)
    dataStream.Close()

    Dim tResponse As WebResponse = tRequest.GetResponse()

    dataStream = tResponse.GetResponseStream()

    Dim tReader As New StreamReader(dataStream)

    Dim sResponseFromServer As [String] = tReader.ReadToEnd()

    tReader.Close()
    dataStream.Close()
    tResponse.Close()

    Return sResponseFromServer
End Function

I was testing this service but I always getting error message
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.GetResponse()

A:

Seems as if something with the authentication did not work. According to the guide, your API key is not valid:

If you receive a 401 HTTP status code, your API key is not valid

See also this answer for possible causes for 401 when using GCM: https://stackoverflow.com/a/11903863. It refers to a link that does not exist anymore, but seems very comprehensive.


Q:

Pyramid invoking a sub request

I'm trying to implement a batch request method in pyramid.  I see in the docs that it's done with
subrequest = Request.blank('/relative/url')
request.invoke_subrequest(subrequest)

I'm just wondering how do you pass along the headers and cookies? Is it already done for you or is it
request.invoke_subrequest(subrequest, cookies=request.cookies, headers=request.headers)

What about parameters for different methods?  The docs only have a POST keyword arg.
I feel like the docs are a little vague, or I can't find the correct docs on how to do this. Thanks

A:

I'm just wondering how do you pass along the headers and cookies?
From http://docs.pylonsproject.org/projects/pyramid/en/1.5-branch/narr/subrequest.html#subrequest-chapter :

The pyramid.request.Request.invoke_subrequest() API accepts two
  arguments: a positional argument request that must be provided, and
  use_tweens keyword argument that is optional; it defaults to False.

This tells us that the constructor only wants a Request object, and optionally a value for use_tweens, so no, this
request.invoke_subrequest(subrequest, cookies=request.cookies, headers=request.headers)

will not work.
Then, from http://docs.pylonsproject.org/projects/pyramid/en/1.5-branch/narr/subrequest.html

It's a poor idea to use the original request object as an argument to
  invoke_subrequest(). You should construct a new request instead as
  demonstrated in the above example, using
  pyramid.request.Request.blank(). Once you've constructed a request
  object, you'll need to massage it to match the view callable you'd
  like to be executed during the subrequest. This can be done by
  adjusting the subrequest's URL, its headers, its request method, and
  other attributes. The documentation for pyramid.request.Request
  exposes the methods you should call and attributes you should set on
  the request you create to massage it into something that will actually
  match the view you'd like to call via a subrequest.

So basically, you need to configure your request before you pass it to invoke_subrequest().
Luckily there is an entire page that documents the Request class. There we can find a whole lot options to configure it, etc.

What about parameters for different methods? The docs only have a POST keyword arg.
Also on the Request class documentation page, there is this

method
Gets and sets the REQUEST_METHOD key in the environment.

And on http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/viewconfig.html I found

request_method This value can be a string (typically "GET", "POST",
  "PUT", "DELETE", or "HEAD") representing an HTTP REQUEST_METHOD

I must agree with you that the documentation is a little vague here and there, but I assume you can use it like this
request.method = 'POST'
# Or
request.method = 'GET'
# Etc.

Summary
You'll want to do it like this
subrequest = Request.blank('/relative/url')
# Configure the subrequest object
# set headers and other options you need.
request.invoke_subrequest(subrequest)

Note
I am aware this is not a 100% complete answer with some code that you can copy paste and it'll just work (especially regarding configuring the request object), but I think this answer contains some information that, at the very least, will get you on the right track and I hope it will be of some help to you.

A:

The following code worked for me. It copies all (headers, cookies, query string, post parameters, etc.):
def subrequest(request, path):
    subreq = request.copy()
    subreq.path_info = path
    response = request.invoke_subrequest(subreq)
    return response