text:
Q: OutOfMemoryError android m Okay, I'm new to Android and have this little problem that I can't seen to find an answer to. I know that this is a common error but all the other threads that I found aren't helpful to me, so I had to create my own.
I'm simply using a listview, and have an Adaptor. The error occurs suddenly when scrolling up and down through the listview items, without even clicking on the items.
Here are some of the logs:

D/OpenGLRenderer: Enabling debug mode 0
D/dalvikvm: GC_FOR_ALLOC freed 173K, 36% free 17008K/26172K, paused 15ms, total 15ms
I/dalvikvm-heap: Grow heap (frag case) to 31.092MB for 10760416-byte allocation
D/AbsListView: unregisterIRListener() is called
D/AbsListView: unregisterIRListener() is called
D/AbsListView: unregisterIRListener() is called
I/dalvikvm-heap: Grow heap (frag case) to 61.836MB for 33177616-byte allocation
D/dalvikvm: GC_FOR_ALLOC freed 52K, 14% free 59979K/69088K, paused 14ms, total 14ms
I/dalvikvm-heap: Grow heap (frag case) to 79.593MB for 18662416-byte allocation
D/dalvikvm: GC_FOR_ALLOC freed 7K, 11% free 78200K/87316K, paused 15ms, total 15ms
I/dalvikvm-heap: Grow heap (frag case) to 111.230MB for 33177616-byte allocation
D/dalvikvm: GC_FOR_ALLOC freed 10515K, 15% free 101867K/119720K, paused 17ms, total 17ms
I/dalvikvm-heap: Forcing collection of SoftReferences for 16104976-byte allocation
D/dalvikvm: GC_BEFORE_OOM freed 15K, 15% free 101851K/119720K, paused 28ms, total 28ms
E/dalvikvm-heap: Out of memory on a 16104976-byte allocation.

.

Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x418ceda0)
E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.hesham.assignment2, PID: 24883
  java.lang.OutOfMemoryError
  at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
  at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:677)
  at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:507)
  at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:872)
  at android.content.res.Resources.loadDrawable(Resources.java:3024)
  at android.content.res.Resources.getDrawable(Resources.java:1586)
  at android.view.View.setBackgroundResource(View.java:16144)
  at com.example.hesham.assignment2.myAdaptor.getView(myAdaptor.java:47)
  at android.widget.AbsListView.obtainView(AbsListView.java:2694)
  at android.widget.ListView.makeAndAddView(ListView.java:1811)
  at android.widget.ListView.fillDown(ListView.java:697)
  at android.widget.ListView.fillGap(ListView.java:661)
  at android.widget.AbsListView.trackMotionScroll(AbsListView.java:6686)
  at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3946)
  at android.widget.AbsListView.onTouchMove(AbsListView.java:4789)
  at android.widget.AbsListView.onTouchEvent(AbsListView.java:4617)
  at android.view.View.dispatchTouchEvent(View.java:8107)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2129)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2411)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2144)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2411)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2144)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2411)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2144)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2411)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2144)
  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2411)
  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2144)
  at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2280)
  at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1615)
  at android.app.Activity.dispatchTouchEvent(Activity.java:2544)
  at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.dispatchTouchEvent(ActionBarActivityDelegateICS.java:268)
  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2228)
  at android.view.View.dispatchPointerEvent(View.java:8315)
  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4598)
  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4466)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4024)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4078)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4047)
  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4158)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4055)
  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4215)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4024)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4078)
  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4047)
  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4055)
  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4024)
  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6416)
  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6320)
  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6291)
  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6256)
  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:649

And there's a an highlighted line, which refers to a line in my Adaptor.

y2.setBackgroundResource(items[i].img);

And here's my whole Adaptor
public class myAdaptor extends BaseAdapter{
Data items[];
Context context;
TextView y;
ImageView y2;
myAdaptor(Data items[], Context context)
{
    this.items=items;
    this.context=context;
}

@Override
public int getCount() {
    return items.length;
}

@Override
public Object getItem(int i) {
    return i;
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View x=view;
    if(x==null)
    {
        x=View.inflate(context,R.layout.item,null);
    }
    y=(TextView) x.findViewById(R.id.textView);
    y2=(ImageView) x.findViewById(R.id.imageView);
    y.setText(items[i].str1);
    y2.setBackgroundResource(items[i].img);

    return x;
}}

So I can't find why I keep getting this error, and I'm not using a bitmap which I found all the other threads are using. So any ideas on how to fix this?
Please let me know if I need to update the thread with any of my code.
Sorry for the long post, and thank you.

A: Try this
Create a folder named drawable-nodpi inside your res folder . Put all of your images there .


text:
Q: flutter. Mock api call in widget test I'm trying to create widget test for login screen in application.
So i want to test several things:
1. That i can find all needed widgets on screen
2. Empty fields validation
3. Wrong login or password scenario
4. Successfull login scenario
But i stuck with items 3 and 4. As i found out on widget tests flutter doesn't allow api calls - so responce is 400 in every case.
I found a way to write test using mockHtmlClient. Inspired by this topic https://groups.google.com/forum/#!msg/flutter-dev/AnqDqgQ6vus/8BoHfxoNBwAJ
 HttpOverrides.runZoned(() async {
  // All code inside here will use the HttpClient returned below.
  await tester.pumpWidget(buildTestableWidget(LoginScreen()));
  Finder emailField = find.byKey(new Key('email'));
  await tester.enterText(emailField, 'some@some.some');

  Finder passwordField = find.byKey(Key("password"));
  await tester.enterText(passwordField, 'some');

  // tap on the login button

  Finder loginButton = find.byKey(new Key('login'));
  await tester.tap(loginButton);

  // 'pump' the tester again. This causes the widget to rebuild
  await tester.pump();
  //sleep(const Duration(seconds:2));
  // await tester.pump();

  //find validation text on SnackBar
  expect(find.text("Invalid email or password"), findsOneWidget);

}, createHttpClient: createMockHttpClient);

My question is - How can i implement MockHttpClient so i could send correct API responce for 3 and 4 scenarious. I can get json answer from real api on this scenarious.
There is implementation of createMockHttpClient for case of NetworkImage in the dicsussion from the linked i posted above.

A: I also wasn't able to make runZoned with createHttpClient work.
I use
setUp(() {
  HttpOverrides.global = TestHttpOverrides({
    'www.example.com/dummy.png':
        dummyAvatarImageData,
    imageThumbUrl: dummyPngImageData,
  });
});

with
class TestHttpOverrides extends HttpOverrides {
  TestHttpOverrides(this.data);

  final Map<Uri, List<int>> data;

  @override
  HttpClient createHttpClient(SecurityContext context) =>
      createMockImageHttpClient(context, data);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python - Detect (spammy) URLS in string So, I've been doing some research for a while now and I could't find anything about detecting a URL in a string. The problem is that most results are about detecting whether a string IS a URL, and not if it contains a URL. The 2 results that look best to me are
Regex to find urls in string in Python
and
Detecting a (naughty or nice) URL or link in a text string
but the first requires http://, which is not something spammers would use (:P) and the second one isn't in regex - and my limited knowledge does not know how to translate any of these. Something I have considered doing is using something dull like
spamlist = [".com",".co.uk","etc"]
for word in string:
    if word in spamlist:
        Do().stuff()

But that would honestly do more bad than good, and I am 100% sure there is a better way using regex or anything!
So if anyone knows anything that could help me I'd be very grateful! I've only been doing python for 1-2 months and not very intensively during this period but I feel like I'm making great progress and this one thing is all that's in the way, really.
EDIT: Sorry for not specifying earlier, I am looking to use this locally, not website (apache) based or anything similar. More trying to clean out any links from files I've got hanging around.

A: As I said in the comments,

*

*Detecting a (naughty or nice) URL or link in a text string 's solution is a regex and you should probably make it a raw string or escape backslashes in it when using it in Python

*You really shouldn't reinvent the square wheel here, especially since spam filtering is an arms race domain (couldn't remember the exact English phrase for this)


text:
Q: How do i map nested objects public class SecurityAccess : IdentityUser    {
    public string LName { get; set; }
    public string FName { get; set; }
    public string MName { get; set; }
    public DateTime NameDate { get; set; }
    public DateTime DOB { get; set; }
    public string Spouse { get; set; }
    public string Comments { get; set; }
    public Address Address { get; set; }
}

public class Address {
    public int Id { get; set; }
    public int OwnerId { get; set; }
    public DateTime CreationDate { get; set; }
    public Company Company { get; set; }
    public string Department { get; set; }
    public string Title { get; set; }
    public string Location{ get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    public string Country { get; set; }
    public string Salutation { get; set; }
    public bool Active { get; set; }
}

public class Company {
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CompanyDate { get; set; }
}

public class ContactRegisterViewModel {
        public byte Id { get; set; }
        public String FName { get; set; }
        public String LName { get; set; }
        public String CompanyName { get; set; }
        public String AddressesTitle { get; set; }
        public String AddressesLocation { get; set; }
        public String AddressesCity { get; set; }
        public String AddressesState { get; set; }
        public String AddressesZip { get; set; }
        public String AddressesCountry { get; set; }
        public String AddressesPhone { get; set; }
        public String AddressesEmail { get; set; }
}

I have the following mappings set in Automapper
CreateMap<ContactRegisterViewModel, SecurityAccess>()
            .ForMember(dest => dest.Address,
                       opts => opts.MapFrom(
                            src => new Address
                            {
                                Address1 = src.AddressesAddress1,
                                Title = src.AddressesTitle,
                                City = src.AddressesCity,
                                State = src.AddressesState,
                                Zip = src.AddressesState,
                                Country = src.AddressesCountry,
                                Email = src.AddressesEmail,
                                Phone = src.AddressesPhone,

                            })).ReverseMap();

I am trying to convert the ContactRegisterViewModel to SecurityAccess. The conversion partially works. I am able to get the relevant properties filled in SecurityAccess including the Address property field that is in  SecurityAccess model however I am struck trying to further map the ContactRegisterViewModel property CompanyName to the property in Address.Company.Name.
Any suggestions how i can map the entire object tree?.

A: So one possible solution would go something like this:
CreateMap<ContactRegisterViewModel, SecurityAccess>()
    .ForMember(d => d.Address, o => o.MapFrom(s => s));

CreateMap<ContactRegisterViewModel, Address>()
    .ForMember(d => d.Title, o => o.MapFrom(s => s.AddressesTitle))
    .ForMember(d => d.Company, o => o.MapFrom(s => s));

CreateMap<ContactRegisterViewModel, Company>()
    .ForMember(d => d.Name, o => o.MapFrom(s => s.CompanyName));

This should get the job done, although it's probably not the most elegant. Might be worth a shot looking into those ConstructUsing / ConvertUsing methods (see here).


text:
Q: MySQL query running really slow for large database I am trying to extract duplicate rows from my database. I have a listings table and a listings_meta table which holds additional information. The listings_meta table has over 16,000 rows. When I run the query below it runs REALLY slow.
I don't understand why. Is there something wrong with my code?
SELECT l.id FROM listings AS l
   LEFT JOIN listings_meta AS lm ON lm.listing_id = l.id AND lm.meta_key = 'email'
   LEFT JOIN listings_meta AS lm2 ON lm2.listing_id = l.id AND lm2.meta_key = 'submitter_email'
   WHERE lm.meta_value = 'test@test.com' OR lm2.meta_value = 'test@test.com' OR l.listing_title RLIKE 'Test'
   GROUP BY l.id LIMIT 1

Are there certain things I can do to improve load time of large tables in general?

A: Do you have indexes on listing_id and meta_key? You should have an index on any field you are going to sort by or match on, because otherwise mysql has to go through the whole table to find each row.
You can also prepend EXPLAIN to the statement to see how mysql is doing the lookups.

A: Indexes
Do you have any indexes - particularly on LISTINGS_META.listing_id?
I re-wrote your query as:
   SELECT l.id
     FROM listings AS l
LEFT JOIN listings_meta AS lm ON lm.listing_id = l.id
                             AND lm.meta_key = 'email'
                             AND lm.meta_value = 'test@test.com'
LEFT JOIN listings_meta AS lm2 ON lm2.listing_id = l.id
                              AND lm2.meta_key = 'submitter_email'
                              AND lm2.meta_value = 'test@test.com'
    WHERE l.listing_title RLIKE 'Test'
 GROUP BY l.id LIMIT 1

WHERE clause
RLIKE (any of the MySQL regex functionality for that matter) is on par with:
WHERE l.listing_title LIKE '%Test%'

Neither can make use of an index on the LISTING.listing_title column...
The best way to improve the listing_title search would be if the LISTING table is MyISAM, so you could add a Full Text Index to the LISTING.listing_title column in order to use:
WHERE MATCH(l.listing_title) AGAINST ('Test')

...but mind that the minimum word length is 3 characters for Full Text Searching (FTS)....


text:
Q: Convert integer date format to human readable format I have a date time format where dates are represented as integers from 1/1/1900 .
For example: 1 is 1/1/1900 and 42998 is 20/9/2017.
How can I convert this format to a human readable format like dd/mm/yyyy ? I checked datetime documentation but I did not find any way to do this. I want to do this either on python 3 or 2.7.
Thanks for any suggestion.

A: You can define your dates as offsets from your basetime and construct a datetime:
In[22]:
import datetime as dt
dt.datetime(1900,1,1) + dt.timedelta(42998)

Out[22]: datetime.datetime(2017, 9, 22, 0, 0)

Once it's a datetime object you can convert this to a str via strftime using whatever format you desire:
In[24]:
(dt.datetime(1900,1,1) + dt.timedelta(42998-1)).strftime('%d/%m/%Y')

Out[24]: '21/09/2017'

So you can define a user func to do this:
In[27]:
def dtToStr(val):
    base = dt.datetime(1900,1,1)
    return (base + dt.timedelta(val-1)).strftime('%d/%m/%Y')
dtToStr(42998)

Out[27]: '21/09/2017'

A: import datetime

base_date = datetime.datetime(1900, 1, 1)
convert = lambda x: base_date + datetime.timedelta(days=x-1)
>>> convert(42998)
datetime.datetime(2017, 9, 21, 0, 0)

A: You can use a datetime object to do that.
import datetime
d = datetime.datetime(1900, 1, 1, 0, 0)
d + datetime.timedelta(days = 42998)
>> datetime.datetime(2017, 9, 22, 0, 0)


text:
Q: how can i use datapager with datalist? i have a datalist and a datapager but when i run my program it have error.
Control 'DataList1' does not implement IPageableItemContainer.

what is problem?
    <asp:DataList ID="DataList1" runat="server" DataKeyField="id"
        DataSourceID="SqlDataSource1">
        <ItemTemplate>
            id:
            <asp:Label ID="idLabel" runat="server" Text='<%# Eval("id") %>' />

            name:
            <asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />

            tedad:
            <asp:Label ID="tedadLabel" runat="server" Text='<%# Eval("tedad") %>' />

            group_id:
            <asp:Label ID="group_idLabel" runat="server" Text='<%# Eval("group_id") %>' />

            VDate:
            <asp:Label ID="VDateLabel" runat="server" Text='<%# Eval("VDate") %>' />

            KDate:
            <asp:Label ID="KDateLabel" runat="server" Text='<%# Eval("KDate") %>' />

            gheimat:
            <asp:Label ID="gheimatLabel" runat="server" Text='<%# Eval("gheimat") %>' />

            details:
            <asp:Label ID="detailsLabel" runat="server" Text='<%# Eval("details") %>' />

            imgae:
            <asp:Label ID="imgaeLabel" runat="server" Text='<%# Eval("imgae") %>' />

        "
            SelectCommand="SELECT * FROM [Tbl_Kala_Group_No]">

    <asp:DataPager ID="DataPager1" runat="server" PagedControlID = "DataList1" PageSize = "4"  QueryStringField = "page" >

        <Fields>

            <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
                ShowLastPageButton="True" />
        </Fields>
    </asp:DataPager>

A: Datapager control does not support for DataList. it works with ListView.
so, Paging for DataList, you have create paging dynamically.
Just give in google : paging for Datalist, you will find lots of resource. Thank you.


text:
Q: How to 'move' babel-runtime into a webpack vendors DLL? I'm creating two webpack bundles: vendors.dll.js and client.js.
Vendors is created with webpack.DllPlugin. It includes all front-end modules in node_modules/. This is working great.
Client includes my app code. It uses the webpack.DllReferencePlugin to delegate to the DLL for vendors. This is working great.
Client runs all javascript through babel-loader. I'm using the babel-plugin-transform-runtime plugin, which causes a whole mess of core-js stuff to be compiled into my client bundle. I'd prefer to move that stuff into the DLL, since it won't change as frequently as the app.
AFAIK you cannot just include babel-runtime in the DLL (I tried this). From what I can tell the core-js stuff is loaded more directly, and babel-runtime doesn't even have a main from what I can tell.
Babel: 6.x
Webpack: 1.x
Happy to provide actual config if its needed to solve the problem.

A: You could scan the required directories and include all files like this.
const readDir = dir => {
  const result = [];
  fs.readdirSync(dir).map(file => {
    if (file.match(/\.js$/)) result.push(`${dir.replace('./node_modules/', '')}/${file}`);
    else if (fs.lstatSync(dir + '/' + file).isDirectory()) result.push(...readDir(dir + '/' + file));
  });
  return result
}
const babelRuntimeHelpers = readDir('./node_modules/babel-runtime/helpers');
const babelRuntimeCoreJs = readDir('./node_modules/babel-runtime/core-js');

And then add those to your vendor array:
vendor: [
    ...babelRuntimeHelpers,
    ...babelRuntimeCoreJs,
    ...rest
]


text:
Q: Can't update DataBase with checkbox data I have a list of 4 images of an item.
One of them should show up in another page as a link from that page to the item page.
I want to be able to check a box so that this one will be the main pic and will show up in the category page.
this is the code of the form:
$all_pics_of_item = fetch_all_pics_of_item($item_id);
//print_r($all_pics_of_item);
if(is_array($all_pics_of_item))
{
    echo '
';
    foreach($all_pics_of_item as $key=>$val)
    {
        if ($val['pics_main']=='yes')
        {
         $set_checked = "checked";
         $action = true;
        }
        else
        {
        $set_checked = "";
        $action = false;
        }
        echo '
';
        echo '';
        echo '
'.$val['pics_name'];
        echo '

x
';
        echo '
<form method="post" action="update_main_pic.php" enctype="text/plain" >
              Show in cat. page<input type="checkbox" class="myCheckbox" name="main" value="no"'.$set_checked.'&action='.$action.' data-picid="'.$val['pics_id'].'" data-itemid="'.$item_id.'" />
              </form>';
        echo '
';
    }
    echo '
';
}

Here is the AJAX and script:
 $(document).ready(function(){

$(':checkbox').click(function() {
     $(':checkbox').not(this).removeAttr('checked');

    var picid = $(this).attr('data-picid');
    var itemid = $(this).attr('data-itemid');
    var action = $(this).is(':checked');
    //if((this).attr('checked',true))
    //{
    //  var action = true;
    //}
    //else
    //  {
    //      var action = false;
    //  }

    $.ajax({
        url: "ajax_update_main_pic.php",
        type: "POST",
        data: "itemid=" + itemid + "&picid=" + picid + "&action=" + action,
        timeout:5000,
        dataType: "html",
        beforeSend:function(){

        },
        error: function(){
            alert('Problem !');
        },
        success: function(msg){
            if(msg == 'no')
            {

            }
            else
            {

            }

        },
        complete: function(){

        }
    })

});

}); //END READY

Here is the update function:
<?php

require_once "../../db.php";
require_once "../../functions.php";

if(isset($_POST['itemid']) && isset($_POST['picid']) && isset($_POST['action']))
{
$item_id = $_POST['itemid'];
$pic_id = $_POST['picid'];
$action = $_POST['action'];
}
else
{
header('location: upload_image.php');
    die();
}

if($action == 'true')
{
$pic_show = 'yes';
}
else
{
$pic_show = 'no';
}
//print_r($pic_show);
function update_main_pic($item_id, $pic_id, $pic_show )

{
    global $db;

    try
    {
        $sql = "
                UPDATE pics SET
                pics_main = :pic_show
                WHERE pics_id = :pic_id AND pics_items_id = :item_id

               ";

        $stmt = $db->prepare($sql);
        $stmt->bindParam(':pics_id', $pic_id, PDO::PARAM_INT);
        $stmt->bindParam(':pics_items_id', $item_id, PDO::PARAM_INT);
        $stmt->bindParam(':pics_main', $pic_show, PDO::PARAM_STR);
        $stmt->execute();

        return true;
    }
    catch(Exception $e)
    {
       return false;
    }
}

$result = update_main_pic($item_id, $pic_id, $pic_show );

if($result == false)
{
    die('Problem updating pics');
}
else
{
    header('location: upload_image.php?iid='.$item_id);
    die();
}

?>

I always get 'Problem updating pics'
It looks like only the checked checkbox is transmitted, while I want that the column PIC_MAIN will show "yes" if this is the one chosen and "no" foe all other pics

A: The issue lies with your binding.
You sql has the following name variables :pic_show , :pic_id and :item_id but you are binding :pics_main', :pics_items_id and :pics_id.
Change your binding to:
$sql = "
        UPDATE pics SET
        pics_main = :pic_show
        WHERE pics_id = :pic_id AND pics_items_id = :item_id

       ";

    $stmt = $db->prepare($sql);
    $stmt->bindParam(':pic_id', $pic_id, PDO::PARAM_INT);
    $stmt->bindParam(':item_id', $item_id, PDO::PARAM_INT);
    $stmt->bindParam(':pic_show', $pic_show, PDO::PARAM_STR);


text:
Q: Strip html tags - lxml.html.clean.clean_html doesn't work as expected I want to strip all html tags from a string except some I specify.
If I call the constructor with default values everything works fine:
>>> cleaner = lxml.html.clean.Cleaner()
>>> cleaner.clean_html('''italic''')
'italic'

But when I try to specify some tags, things doesn't work anymore:
>>> allowed_tags = ['i','s']
>>> cleaner = lxml.html.clean.Cleaner(remove_unknown_tags=False,allow_tags=allowed_tags)
>>> cleaner.clean_html('''italic<s>strike</s>''')
''

So what am i doing wrong?

A: As a workaround, you can add span and div tags to allowed_tags.
UPD
lxml.html.Cleaner tries to convert string to html tree by calling fromstring, which checks if document have some root node, and adds it if necessary. So you need to allow span and div tags

A: It seems like a bug. I don't see it in lxml==2.3.3 version:
>>> from lxml.html import clean
>>> clean.clean_html('''italic''')
'italic'
>>> c = clean.Cleaner(allow_tags='is', remove_unknown_tags=False)
>>> c.clean_html('''italic<s>strike</s>''')
'
italic<s>strike</s>
'


text:
Q: Is a circle action on M_n necessarily inner? An action $\alpha$ of a locally compact topological group G on a unital $C^*$-algebra $A$ is called inner if there exists a continuous group homomorphism $u\colon G\to U(A)$ such that $\alpha_g(a)=u_gau_g^*$ for all $g\in G$ and all $a\in A$.
Question: let $\alpha\colon S^1\to Aut(M_n)$ be a continuous action. Does it follow that $\alpha$ is inner?
For every $\zeta\in S^1$, the automorphism $\alpha_\zeta$ is inner, say $\alpha_\zeta=Ad(u_\zeta)$ for some unitary $u_\zeta$ in $M_n$. This unitary is unique up to multiplication by elements of $S^1\cdot 1_n\subseteq M_n$ (the unitaries in the center of $M_n$). Is it known whether one can choose the map $\zeta\mapsto u_\zeta$ to be a continuous group homomorphism?
I suppose this may be known to some people but I could not find any references.


text:
Q: Sending data from Dart to PHP using POST method I am trying to send some data from Dart to PHP...
This is the code i am using to send the data from Dart:
button.onClick.listen((e) {
  var req = new HttpRequest();

  req.onReadyStateChange.listen((HttpRequestProgressEvent e) {
    if (req.readyState == HttpRequest.DONE) {
      print('Data submitted!');
    }
  });

  req.open('POST', form.action);
  req.send('hello from dart');

});

In my PHP file I am trying to use the string i have send from dart, but count($_POST) returns 0. $_POST seems to be empty...
Dart code DOES trigger the php script and 'Data submitted' is printed...

A: This is actually related to your PHP configuration. You can access the POST'd data with PHP's reserved variable: $HTTP_RAW_POST_DATA However the preferred method is to use php://input

A: I am very new to Dart, but you can use FormData in the send. So a quick and dirty way could be.
    var data_form = new FormData(query('#My_form'));

    button.onClick.listen((e){
           var request = new HttpRequest():
           request.open('POST', 'http://Localhost/form_data.php');
           request.send(data_form);


text:
Q: Is there something like TypeToken for AnnotatedTypes Since there's no type literals in Java, TypeToken trick is commonly used instead.
Say, you want to get a Type instance representing List<String>, you'd do:
new TypeToken<List<String>>(){}.getType()

Now, I wonder if similar trickery is possible to get an instance of an AnnotatedType. For example, to represent List<@NonNull String> or even @NonNull List<@NonNull String>.
EDIT:
Here's a full AnnotatedType-enabled TypeToken implementation, provided by GeAnTyRef.
The gist:
public abstract class TypeToken<T> {
    private final AnnotatedType type;

    /**
     * Constructs a type token.
     */
    protected TypeToken() {
        this.type = extractType();
    }

    private TypeToken(AnnotatedType type) {
        this.type = type;
    }

    public Type getType() {
        return type.getType();
    }

    public AnnotatedType getAnnotatedType() {
        return type;
    }

    private AnnotatedType extractType() {
        AnnotatedType t = getClass().getAnnotatedSuperclass();
        if (!(t instanceof AnnotatedParameterizedType)) {
            throw new RuntimeException("Invalid TypeToken; must specify type parameters");
        }
        AnnotatedParameterizedType pt = (AnnotatedParameterizedType) t;
        if (((ParameterizedType) pt.getType()).getRawType() != TypeToken.class) {
            throw new RuntimeException("Invalid TypeToken; must directly extend TypeToken");
        }
        return pt.getAnnotatedActualTypeArguments()[0];
    }
}

A: Just create a type token - or any anonymous subclass with annotated type parameters - with the annotations and then use reflection to extract the annotated types.
Note that this only works for annotations with runtime retention.
Using the fullType() method from the linked answer:
    List<?> token = new ArrayList<@NonNull String>() {};
    fullType("", token.getClass().getAnnotatedSuperclass());

prints
java.util.ArrayList
<
    @org.checkerframework.checker.nullness.qual.NonNull()
    java.lang.String
>


text:
Q: How to Shorten Package Name? I have imported a project in android studio now I want to change the package name and also shorten it.
This is the current package name:
package com.google.android.gms.location.sample.locationupdates;
I want to rename it into:
com.example.app
How can i do this?

A: You can do this:

*

*Change the package name manually in the manifest file.

*Click on your R.java class and the press F6 (Refactor->Move...). It will allow you to move the class to another package, and all references to that class will be updated

Reference: Answer


text:
Q: How do I stop a sort at a certain point in the column? I have a spreadsheet that automatically sorts itself by the date in column D.
If Not Intersect(Target, Range("D:D")) Is Nothing Then
    MsgBox ("sorting col D")
'    Application.EnableEvents = False

    Range("D1").Sort Key1:=Range("D2"), _
    Order1:=xlAscending, Header:=xlYes, _
    OrderCustom:=1, MatchCase:=False, _
    Orientation:=xlTopToBottom

'    Application.EnableEvents = True

End If

This code works fine.
What I want to do is limit the sorting to the first N rows.  Unfortunately, N is not a fixed number.  Basically there will be information in column K for SOME of the rows (and all of the rows with column K will be at the bottom of the sheet).  So I only want the sort to be performed for the rows in which there is no data in column K.

So in this picture, supposing there are dates in column D for all the green rows too, if I added a new row with a date in column D, it would sort it BUT ONLY AMONG ROWS 2-10, leaving rows 11+ alone.  I do not want the green rows resorted by column D, as they are sorted by something else.  Sorry for the vague photo!


text:
Q: Drag and drop, wxEVT_DROP_FILES event not received Using wxWidgets wxWidgets-3.0.2 and MSVC 2012 (building with 2008)
I try to add file drag n drop event on wxListView control. When I drag file on control I can see icon change, but when it is released nothing happens, my event handler function is never called.
Code:
m_listAllStrings = new wxListView(this, ID_LV_ALLSTRINGS);
m_listAllStrings->DragAcceptFiles(true);
m_listAllStrings->Bind(wxEVT_DROP_FILES, &MainFrame::OnDropFiles, this);
// also tried these
// m_listAllStrings->Connect(wxEVT_DROP_FILES, wxDropFilesEventHandler(MainFrame::OnDropFiles), NULL, this);
// Connect(wxEVT_DROP_FILES, wxDropFilesEventHandler(MainFrame::OnDropFiles));

// even handler function
void MainFrame::OnDropFiles(wxDropFilesEvent& event)
{
    // I put breakpoint here, it never enters
    if(event.GetNumberOfFiles() > 0)
    {
         // ...
    }
}

I also tried doing this on button and it did not work, though click event handling works:
 Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(MainFrame::OnBtClick));


text:
Q: strange set bug in python with big text file I'm importing a very big list of names with each line having a name, and i'm adding it to a set, as follows:
 g = open('names.txt', 'r')
 for line in g:
    self.nameset.add(line)

However, I can't seem to run the most basic command on it, the if "name" in self.nameset. As in, it can't seem to ever find any name even though I know for sure the name i'm checking is in there. If I make the text file very small, however, it works fine. Am I doing something incorrectly by passing in a very large text file this way?
Thank you very much!

A: line contains "\n", so before you add it to the set, maybe:
self.nameset.add(line.strip())


text:
Q: Is there a way to iterate through a vector two items at a time in C++? Imagine I have an ordered std::vector A = {x1, x2, ..., xn} and I want to perform an operation on every subsequent pair of items, e.g. f(x1, x2); f(x2, x3); ... f(xn-1, xn); f(xn, x1).
I could iterate like I normally would, while tracking the previous item:
for (auto x : A) {
    ...
    f(previous_x, x);
    previous_x = x;
}

f(previous_x, first_x);

But is there a better way to iterate through this vector? Are there features in the language that can streamline this?
Tried the solution provided. It works, but curious to know if there is a cleaner and more concise way.

A: Here you are
    std::vector<int> v = { 1, 2, 3, 4, 5 };

    for (std::vector<int>::size_type i = 0, n = std::size( v ); i < n; i++)
    {
        std::cout << v[i] + v[( i + 1 ) % n] << ' ';
    }
    std::cout << '\n';

the output of this code snippet is
3 5 7 9 6

You can use a similar approach.
Before the for loop you can check whether a vector contains at least two elements.

A: Ranges provide a beautiful solution for this case:

*

*get the input vector,[1, 2, 3, 4, 5]

*repeat it indefinitely with repeat,[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], ...]

*flatten the new view out with join,[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...]

*take as many elements as the vector size plus one with take, and[1, 2, 3, 4, 5, 1]

*apply a transformation to each adjacent pair with adjacent_transform<2>.[[1, 2], [2, 3], ...] -> [f(1,2), f(2,3), ...]
Notice repeat and adjacent_transform will be available in C++23.join and take should be available in C++20.
[Demo]
#include <fmt/ranges.h>
#include <functional>  // multiplies, plus
#include <ranges>
#include <vector>

template <typename C, typename F>
auto my_adjacent_transform(C&& c, F&& f) {
    return std::views::repeat(std::forward<C>(c))
        | std::views::join
        | std::views::take(c.size() + 1)
        | std::views::adjacent_transform<2>(f);
}

int main() {
    std::vector<int> v{ 1, 2, 3, 4, 5 };
    fmt::print("v: {}\n", v);
    fmt::print("Adding pairs: {}\n", my_adjacent_transform(v, std::plus<>{}));
    fmt::print("Multiplying pairs: {}\n", my_adjacent_transform(
        std::vector<int>{ 1, 2, 3, 4, 5 }, std::multiplies<>{}));
}

// Outputs:
//
//   v: [1, 2, 3, 4, 5]
//   Adding pairs: [3, 5, 7, 9, 6]
//   Multiplying pairs: [2, 6, 12, 20, 5]

Alternatively, you could already use Eric Niebler's range-v3 library, and the solution would be quite similar:

*

*get the input vector,[1, 2, 3, 4, 5]

*repeat its contents indefinitely with cycle,[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...]

*take as many elements as the vector size plus one with take, [1, 2, 3, 4, 5, 1]

*create a view of adjacent pairs with sliding(2), and[[1, 2], [2, 3], ...]

*apply a transformation to each pair with transform.[t(1, 2), t(2, 3), ...]
Notice from the example below that range-v3 library lets you construct a container from a view via ranges::to. This conversion function will also be part of C++23.
[Demo]
#include <fmt/ranges.h>
#include <functional>  // multiplies, plus
#include <range/v3/all.hpp>
#include <vector>

template <typename C, typename F>
auto my_adjacent_transform(C&& c, F&& f) {
    auto t = [&f](auto&& p) { return std::forward<F>(f)(p[0], p[1]); };
    return std::forward<C>(c)
        | ranges::views::cycle
        | ranges::views::take(c.size() + 1)
        | ranges::views::sliding(2)
        | ranges::views::transform(t);
}

int main() {
    std::vector<int> v{ 1, 2, 3, 4, 5 };
    fmt::print("v: {}\n", v);
    fmt::print("Adding pairs: {}\n", my_adjacent_transform(v, std::plus<>{}));
    auto w{ my_adjacent_transform(v, std::multiplies<>{})
        | ranges::to<std::vector<int>>() };
    fmt::print("Multiplying pairs: {}\n", w);
}

A: You could use an old-school non range based for-loop and dereference the current + next modulus A.size() iterator:
#include <iostream>
#include <vector>

void foo(int a, int b) { std::cout << a << ',' << b << '\n'; }

int main() {
    std::vector<int> A{1, 2, 3};

    if (A.size() >= 2) {
        for (auto it = A.begin(); it != A.end(); ++it) {
            foo(*it, *std::next(A.begin(),
                                (std::distance(A.begin(), it) + 1) % A.size()));
        }
    }
}

Output:
1,2
2,3
3,1

Or... use indices to do the same thing, like @Vlad showed.

Another option that would work with any type of container and iterators could be to save the first value that you get from dereferencing the initial iterator and reuse that when the loop ends.
Example:
#include <iostream>
#include <vector>

template <class It, class Func>
void do_pairwise(It first, It last, Func&& func) {
    if (first == last) return;

    auto curr = *first;
    auto save = curr;  // save the value for later
    for (++first; first != last; curr = *first, ++first) {
        func(curr, *first);
    }
    func(curr, save);  // reuse the first value
}

int main() {
    std::vector<int> A{1, 2, 3};

    if (A.size() >= 2) {
        do_pairwise(A.begin(), A.end(),
                    [](int a, int b) { std::cout << a << ',' << b << '\n'; });
    }
}

A: Just do it:
A.push_back(A[0]); // copy first element to end
for (int j = 0; j < A.size() - 1; ++j)
    f(A[j], A[j+1]);


text:
Q: Avoid points on edges of plots when the last x-value equals the tick Every time I try to plot some points the last point ends up right on the edge of the plot:

Note the point circled in red. Is it possible to avoid this? I'd like to have some space between the last point plotted and the right plot edge.
My desired output would be:

Which I obtained increasing the last x value by a tiny amount. I'd like to find a way of plotting that automatically handles this and that doesn't depend on the size of the values(e.g. if I was plotting really small float values then even the smallest change would be significant and the output wouldn't reflect the data)
I'm plotting using:
figure(1)
#X[-1] += 0.0001    #ugly way of obtaining some space at the right
errorbar(X, Y, yerr=error, fmt='bo')

A: (copied almost directly from How to autoscale y axis in matplotlib?)
You want margins doc
ex
ax.margins(y=.1, x=.1)

Also see Add margin when plots run against the edge of the graph


text:
Q: ModuleNotFoundError: No module named 'my_app', app already in INSTALLED_APPS I'm trying to deploy my Django app through Heroku but I'm getting a ModuleNotFound error after running a production environment with gunicorn wsgi path. My app is included in settings.py and it was working fine while in the development environment. But now I'm getting errors for deployment.
I have problems with how my project is structured, thus Procfile does not leave in the same directory as manage.py, and I believe this could be the issue. Any hint or help is more than appreciated.
Directory structure
 >FINALPROJECT(root)
    > .vscode
    > project5
        > brainSkills
           > migrations
           > static
           > templates
           apps.py
           models.py
           urls.py
           views.py
        > project5
           _init_.py
           settings.py
           wsgi.py
        _init_.py
        manage.py
    > venv
    .env
    .gitignore
    Procfile
    README.md
    requirements.txt

Procfile
web: gunicorn project5.project5.wsgi

wsgi.py
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project5.project5.settings')

application = get_wsgi_application()

setting.py
import os
from pathlib import Path
from dotenv import load_dotenv

INSTALLED_APPS = [
   'brainSkills',
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
]

ROOT_URLCONF = 'project5.urls'

WSGI_APPLICATION = 'project5.wsgi.application'

Error after gunicorn project5.project5.wsgi or Heroku local
5:32:28 PM web.1 |    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
5:32:28 PM web.1 |      return _bootstrap._gcd_import(name[level:], package, level)
5:32:28 PM web.1 |    File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
5:32:28 PM web.1 |    File "<frozen importlib._bootstrap>", line 991, in _find_and_load
5:32:28 PM web.1 |    File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
5:32:28 PM web.1 |  ModuleNotFoundError: No module named 'brainSkills'
5:32:28 PM web.1 |  [2020-10-12 21:32:28 +0000] [57691] [INFO] Worker exiting (pid: 57691)
5:32:28 PM web.1 |  [2020-10-12 17:32:28 -0400] [57689] [INFO] Shutting down: Master
5:32:28 PM web.1 |  [2020-10-12 17:32:28 -0400] [57689] [INFO] Reason: Worker failed to boot.
[DONE] Killing all processes with signal  SIGINT
5:32:28 PM web.1 Exited with exit code null

A: Try changing the way you are adding it to INSTALLED_APPS:
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'brainSkills.apps.BrainSkillsConfig',
]

More about this here. While doing the research for this question I learned that prior to Django 1.7 your approach would be correct if you also used default_app_config = 'brainSkills.apps.BrainSkillsConfig' in your app's __init__.py. However Django now recommends the approach I show above.


text:
Q: In Java, why are nextInt() and nextDouble() instance methods of Random objects? In Java, why are nextInt() and nextDouble() instance methods of Random objects?
I feel that these methods should be static methods of the Random class. What is the purpose of having to instantiate a Random object to generate random integers or double values?

A: Java's Random class uses an initial seed value and a linear congruential generator as a part of its internal state to generate a sequence of random numbers.  If the nextInt() and nextDouble() methods were static, they wouldn't have access to this internal storage.
From the docs:

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

Note that this also means that if two instances of Random are created with different seeds, they'll generate two different sequences.

A: The constructor for Random lets you input a seed value, so you'd want to be able to use that with your nextFoo methods.

A: because each Random object has it's own seed that you can set
this allows each thread to have it's own Random without having to worry about efficiency issues caused by synchronization
also Math.random() lets you get a random double in the [0,1) range


text:
Q: O meu código é orientado a objeto? Tenho um código e gostaria de saber se o mesmo é um código orientado a objetos. Segue a estrutura. Trabalho com 3 arquivos.
1º chama save.php, segue o código:
include_once('dao.php');
include_once('modelo.php');
$post = new Post();
$post->setDescricao($_POST['custo_descricao_html']);
$post->setMes($_POST['custo_mes_atual']);
$post->setLocal($_POST['custo_local_html']);
$post->setPreco($_POST['custo_custo_html']);
$post->setObservacao($_POST['custo_observacao_html']);
$post->setColaborador_id($_POST['colaborador_logado_custo']);

$dao = new DaoCusto();

if ($_POST['custo_controle_html'] == 0) {
 $post->setId(rand(0, time()));
 $resultado = $dao->insert($post);
 echo($resultado == 'salvo') ? '0' : $resultado;
} else {
 $post->setId($_POST['custo_idUpdate_html']);
 $resultado = $dao->update($post);
 echo($resultado == 'salvo') ? '0' : $resultado;
}

2ª arquivo que faço os gets e sets, modelo.php:
<?php

    class Post {

    private $id;
    private $descricao;
    private $mes;
    private $local;
    private $preco;
    private $observacao;
    private $colaborador_id;

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
        return $this;
    }

    public function getDescricao() {
        return $this->descricao;
    }

    public function setDescricao($descricao) {
        $this->descricao = $descricao;
        return $this;
    }

    public function getMes() {
        return $this->mes;
    }

    public function setMes($mes) {
        $this->mes = $mes;
        return $this;
    }

    public function getLocal() {
        return $this->local;
    }

    public function setLocal($local) {
        $this->local = $local;
        return $this;
    }

    public function getPreco() {
        return $this->preco;
    }

    public function setPreco($preco) {
        $this->preco = $preco;
        return $this;
    }

    public function getObservacao() {
        return $this->observacao;
    }

    public function setObservacao($observacao) {
        $this->observacao = $observacao;
        return $this;
    }

    public function getColaborador_id() {
        return $this->colaborador_id;
    }

    public function setColaborador_id($colaborador_id) {
        $this->colaborador_id = $colaborador_id;
        return $this;
    }

    }

E o terceiro arquivo que é onde realizo meu CRUD , dao.php
     <?php

     require_once '../../../conexao/conexao.php';
     require_once 'modelo.php';

    class DaoCusto {

    public static $instance;

    public function __construct() {

    }

    public function insert(Post $custo) {
        try {

            $sql = "INSERT INTO  tb_custo (custo_id , custo_descricao , custo_mes , custo_local , custo_preco , custo_observacao , colaborador_colaborador_id)   values (:custo_id , :custo_descricao , :custo_mes , :custo_local , :custo_preco , :custo_observacao  , :colaborador_colaborador_id)";

            $p_sql = Conexao::getInstance()->prepare($sql);

            $p_sql->bindValue(':custo_id', $custo->getId());
            $p_sql->bindValue(':custo_descricao', $custo->getDescricao());
            $p_sql->bindValue(':custo_mes', $custo->getMes());
            $p_sql->bindValue(':custo_local', $custo->getLocal());
            $p_sql->bindValue(':custo_preco', $custo->getPreco());
            $p_sql->bindValue(':custo_observacao', $custo->getObservacao());
            $p_sql->bindValue(':colaborador_colaborador_id', $custo->getColaborador_id());

            return ($p_sql->execute()) ? 'salvo' : false;
        } catch (PDOException $e) {
            return 'Erro, contate o suporte!Código:' . $e->getCode() . 'Mensagem:' . $e->getMessage();
        }
    }

    public function Update(Post $custo) {
        try {

            $sql = "UPDATE tb_custo SET   custo_descricao= :custo_descricao , custo_mes= :custo_mes , custo_local= :custo_local , custo_preco= :custo_preco , custo_observacao= :custo_observacao , colaborador_colaborador_id= :colaborador_colaborador_id WHERE custo_id= :custo_id ";
            $p_sql = Conexao::getInstance()->prepare($sql);

            $p_sql->bindValue(':custo_descricao', $custo->getDescricao());
            $p_sql->bindValue(':custo_mes', $custo->getMes());
            $p_sql->bindValue(':custo_local', $custo->getLocal());
            $p_sql->bindValue(':custo_preco', $custo->getPreco());
            $p_sql->bindValue(':custo_observacao', $custo->getObservacao());
            $p_sql->bindValue(':colaborador_colaborador_id', $custo->getColaborador_id());
            $p_sql->bindValue(':custo_id', $custo->getId());

            return ($p_sql->execute()) ? 'salvo' : false;
        } catch (PDOException $e) {
            return 'Erro, contate o suporte!Código:' . $e->getCode() . 'Mensagem:' . $e->getMessage();
        }
    }

   }

Essa estrutura é orientada a objetos?

A: Na medida do que é possível fazer orientação a objeto em PHP, a classe Post é bem OOP, só não é mais porque não está usando herança e polimorfismo, ainda bem. Há encapsulamento e alguma abstração. O ganho de ter feito desta forma me parece próximo de zero, mas não dá para dizer que tem algo errado. Um array associativo teria sido muito mais simples, o que me faz pensar que o ganho possa ser considerado negativo.
DaoCusto é um pouco menos. Tudo que é estático é menos orientado a objeto, mas é um pouco. Teria sido muito mais simples criar uma função simples. Está forçando o uso de um mecanismo que não cabe aí. Funciona, tem gente que gosta de fazer assim, mas não há ganho, pelo contrário.
A questão é: qual a relevância disto? O objetivo é seguir uma fórmula sem entender bem porque ou fazer algo que ajude o código ficar melhor? OOP não faz o código ficar melhor por mágica e há casos que ele pode piorar o que está fazendo. Não parece ser tanto o seu caso, quando precisou ser pragmático, até foi, pelo menos em partes.
Veja: O que é "Orientado a objeto" e quais outros métodos?
Entenda que orientação a objeto é algo secundário para a programação. Em PHP mais ainda.


text:
Q: Dropdown menu doesn't work on mobile I have a simple dropdown menu and having trouble making it work on mobile devices.
It works fine on desktop, when I hover it slides down the menu and when I mouse out it hides, however in IOS or android when I tap on menu item it shows the sub menu, but it just stays that way even if I tap on the parent item again.
Ideally it should: tap open menu, tap again on the parent item - to close menu.
html:

    Account

Link 1

Link 2

Link 3

Link 4

Link 5

css:
.acc-menu {
  margin-top: -6px;
  padding: 0;
  list-style: none;
}

.parent span {
  letter-spacing: 3px;
}

.acc-menu li {
  float: left;
  display: block;
  background: #fff;
  position: relative;
  z-index: 500;
  margin: 0 1px;
}

.acc-menu li a {
  display: block;
  line-height: 18px;
  color: #333;
  text-align: left;
}

.acc-menu ul {
  position: absolute;
  left: -14px;
  display: none;
  margin: 0 0 0 -1px;
  padding: 0;
  list-style: none;
  text-indent: 10px;
}

.acc-menu ul li {
  width: 150px;
  float: left;
}

.acc-menu ul a {
  display: block;
  padding: 8px 5px;
}

.acc-menu ul a:hover {
  text-decoration: underline;
}

jq:
jQuery('.acc-menu li').hover(
  function() {
    jQuery('ul', this).stop().slideDown(100);
  },
  function() {
    jQuery('ul', this).stop().slideUp(100);
  }
);

Here is the codepen link

A: Hover doesn't play nice on mobile. You could try adding a click listener with a toggleClass() event for mobile and leave the conventional hover on desktop:

*

*Add .display class to your CSS with display: block;

*Attach .on("click") listener with toggleClass("display"); on ul only if viewport width is equal or below 414px (feel free to adjust viewport width value to your benefit).

EDIT (comment based):

*

*Set :hover through @media query only for desktop, and left click listener for mobile via jQuery.

Test it resizing viewport here. First resize it, then run the code and try to either hover or click.(UPDATED)

var viewport = $(window).width();
if (viewport <= 414) {
  jQuery('.acc-menu').on("click", function() {
    jQuery('ul').toggleClass("display");
  });
}
.acc-menu {
  margin-top: -6px;
  padding: 0;
  list-style: none;
}
.parent span {
  letter-spacing: 3px;
}
.acc-menu li {
  float: left;
  display: block;
  background: #fff;
  position: relative;
  z-index: 500;
  margin: 0 1px;
}
.acc-menu li a {
  display: block;
  line-height: 18px;
  color: #333;
  text-align: left;
}
.acc-menu ul {
  position: absolute;
  left: -14px;
  display: none;
  margin: 0 0 0 -1px;
  padding: 0;
  list-style: none;
  text-indent: 10px;
}
.acc-menu ul.display {
  display: block;
}
.acc-menu ul li {
  width: 150px;
  float: left;
}
.acc-menu ul a {
  display: block;
  padding: 8px 5px;
}
.acc-menu ul a:hover {
  text-decoration: underline;
}
@media (min-width: 415px) {
    .acc-menu li:hover ul {
        display: block;
    }
}

    Account

Link 1

Link 2

Link 3

Link 4

Link 5

A: You can do this purely with CSS using :hover.

.acc-menu {
  margin-top: -6px;
  padding: 0;
  list-style: none;
}

.parent span {
  letter-spacing: 3px;
}

.acc-menu li {
  float: left;
  display: block;
  background: #fff;
  position: relative;
  z-index: 500;
  margin: 0 1px;
}

.acc-menu li a {
  display: block;
  line-height: 18px;
  color: #333;
  text-align: left;
}

.acc-menu ul {
  position: absolute;
  left: -14px;
  display: none;
  margin: 0 0 0 -1px;
  padding: 0;
  list-style: none;
  text-indent: 10px;
}

.acc-menu ul li {
  width: 150px;
  float: left;
}

.acc-menu ul a {
  display: block;
  padding: 8px 5px;
}

.acc-menu ul a:hover {
  text-decoration: underline;
}

li:hover ul {
  display: block;
}

    Account

Link 1

Link 2

Link 3

Link 4

Link 5

A: Why don't you simply add a click event besides the hover one
jQuery('.acc-menu li').on('click',
  function() {
    jQuery('ul', this).stop().slideToggle(100);
  }
);

Pen


text:
Q: Why is image not showing? and how to put an image on top of the background image? html, css I'm struggling with understanding css/html at this point. The background-image is only showing when I put it into body in css, but I would prefer to have it in a div. Also even when it's working I can't put any other image on top of it, it is just simply not showing... I checked the path and everything and it's fine, I tried to put the img in html, tried the z-index values and still nothing. I have no clue what is going on
Any one can give me a hand with this?
My html code
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet">
    <title>ONLINE FILM FESTIVAL</title>

Online Film Festival

Home

About

FAQ

Contact

My css code
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

nav {
  display: flex;
  justify-content: space-around;
  align-items: center;
  min-height: 8vh;
  background-color: #241825;
  font-family: 'Poppins', sans-serif;
}

.logo {
  color: rgb(226, 226, 226);
  text-transform: uppercase;
  letter-spacing: 5px;
  font-size: 20px;
}

.nav-links {
  display: flex;
  width: 30%;
  justify-content: space-around;
}

.nav-links li {
  list-style: none;
}

.nav-links a {
  color: rgb(226, 226, 226);
  text-decoration: none;
  letter-spacing: 3px;
  font-weight: bold;
  font-size: 14px;
}

.burger {
  display: none;
  cursor: pointer;
}

.burger div {
  width: 25px;
  height: 3px;
  background-color: rgb(226, 226, 226);
  margin: 5px;
  transition: all 0.5s ease;

}

/* Tablet zone */
@media screen and (max-width:1024px) {
  .nav-links {
    width: 100%;
  }
}

/* Mobile phone zone */
@media screen and (max-width:768px) {
  body {
    overflow-x: hidden;
  }

  .nav-links {
    position: absolute;
    right: 0px;
    height: 92vh;
    top: 8vh;
    background-color: #241825;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 50%;
    transform: translateX(100%);
    transition: transform 0.5s ease-in;
  }

  .nav-links a {
    font-size: 20px;
    line-height: 3.5;

  }

  .nav-links li {
    opacity: 0;
  }

  .burger {
    display: block;
  }
}

.nav-active {
  transform: translateX(0%);
}

@keyframes navLinkFade {
  from {
    opacity: 0;
    transform: translateX(50px);
  }

  to {
    opacity: 1;
    transform: translateX(0px);
  }
}

.toggle .line1 {
  transform: rotate(-45deg) translate(-5px, 6px);
}

.toggle .line2 {
  opacity: 0;
}

.toggle .line3 {
  transform: rotate(45deg) translate(-5px, -6px);
}

.background-image {
  background-image: linear-gradient(to bottom,
      rgba(0, 0, 0, 0) 0%,
      rgba(17, 17, 17, 0.6) 100%),
    url(images/picc1.jpg);
  background-size: cover;
  color: #fff;
  background-repeat: no-repeat;
  z-index: 0;
  height: 100%;
  width: 100%;

}

/* .main__img--container {
  text-align: center;
  height: 100%;
  width: 100%;
}

#main__img {
  height: 100%;
  width: 100%;
} */

/*
body {
  background-image: linear-gradient(to bottom,
      rgba(0, 0, 0, 0) 0%,
      rgba(17, 17, 17, 0.6) 100%),
    url(images/picc1.jpg);
  background-size: cover;
  color: #fff;
  background-repeat: no-repeat;
  z-index: 0;

}

.img1 {
  background-image: url(/images/pic1.png);
  z-index: 999;
  width: 300px;
  height: 500px;

} */

The last few lines starting from .main__img--container are commented, it is just simply what I've tried and didn't work, except from "body {}"... :(

A: a) There is no  tag in your code (?).
b) Your background-image element has no content, so its height will be zero by default, i.e. the background image will also have height zero and will therefore remain invisible. To make it visible, you need to set a height for that element. BTW, percentage heights are only relevant if the parent element's height is defined or if here is content that "creates" height.

A: Your .background-image class is specifying 100% height of what? Try adding height 100vh on your body element if you want to fill up the screen.
Alternatively just add a min-height on the element e.g 400px.
Works for me
edit:


text:
Q: How to deal with custom nginx.conf files in Amazon ECS? I basically have two docker images: nginx image and a php image, that I want to upload to ECS. Both are run by a docker-compose.
The nginx has a myapp.conf file that I want to copy from somewhere into the container's /etc/nginx/conf.d folder.
Whats the best way to deal with this?

A: Prepare your own nginx image and use the COPY command.
FROM nginx

COPY myapp.conf /etc/nginx/conf.d

Build it:
docker build -t mynginximg .

and use it in your compose files.


text: Q: Hyperledger Fabric: "The clientContext has not been properly initialized, missing userContext" error I am trying to send multiple transactions concurrently and I received an error saying "The clientContext has not been properly initialized, missing userContext" from time to time. No matter I am sending as one client or two clients, the same problem occurs. I have attached a screenshot to display the problem. Thank you very much error image


text:
Q: Redisson: Is there a way to use different codec for classes in specific packages instead of the globally configured one? In my current project, Redisson is used for caching many different classes using the JsonJacksonCodec. This works as intended but I want to have classes only in a certain package serialized using MsgPack instead while leaving the rest serialized as they already are.
From what I found, this is possible by either configuring the RObject (https://github.com/redisson/redisson/wiki/16.-FAQ#q-can-i-use-different-encoderdecoders-for-different-tasks) or by using CompositeCodec but in the first case, it seems to me I can still only supply one codec to redisson configuration and would need multiple instances configured differently to achieve my goal, while in the second case, the CompositeCodec is used for chaining several codecs together, one after another, instead of using different codecs for different classes. Unfortunately, both documentation and examples of advanced Redisson usage are minimal so I'm not sure if I'm right on any of these conclusions.
Is there an easy way to achieve this and what would be the best way to do so?

A: Every redisson object could be supplied with own codec.
Code example for Map object:
RMap<String, String> map = redisson.getMap("myMap", new MyCodec());


text:
Q: How can I get the name of a C# static class property using reflection? I want to make a C# Dictionary in which the key is the string name of a static property in a class and the value is the value of the property.  Given a static property in the class called MyResources.TOKEN_ONE, how can I get the at the name of the property rather than its value?  I only care about the end part of the property name (e.g. "TOKEN_ONE").
I've edited this to mention that I don't want to map all property values in the Dictionary, just a small subset of everything that's in the class. So assume that I want to get the name for a single property.  Given MyResources.TOKEN_ONE, I want to get back "MyResources.TOKEN_ONE" or just "TOKEN_ONE".
Here's some sample code that shows what I'm trying to do.  I need the property name because I'm trying to generate a javascript variable in which I map the property name to the variable name and the property value to the variable value.  For example, I want the C# Dictionary to generate lines like the one below:
var TOKEN_ONE = "One";
using System;
using System.Collections.Generic;

namespace MyConsoleApp
{
   class Program
   {
      static void Main(string[] args)
      {
         Dictionary<String, String> kvp = new Dictionary<String, String>();

         // How can I use the name of static property in a class as the key for the dictionary?
         // For example, I'd like to do something like the following where 'PropertyNameFromReflection'
         // is a mechanism that would return "MyResources.TOKEN_ONE"
         kvp.Add(MyResources.TOKEN_ONE.PropertyNameFromReflection, MyResources.TOKEN_ONE);
         kvp.Add(MyResources.TOKEN_TWO.PropertyNameFromReflection, MyResources.TOKEN_TWO);

         Console.ReadLine();
      }
   }

   public static class MyResources
   {
      public static string TOKEN_ONE
      {
         get { return "One"; }
      }

      public static string TOKEN_TWO
      {
         get { return "Two"; }
      }
   }
}

A: If all you want is just to be able to refer to a single, specific property in one place in the code without having to refer to it by a literal string, then you can use an expression tree. For example, the following code declares a method that turns such an expression tree into a PropertyInfo object:
public static PropertyInfo GetProperty(Expression<Func<string>> expr)
{
    var member = expr.Body as MemberExpression;
    if (member == null)
        throw new InvalidOperationException("Expression is not a member access expression.");
    var property = member.Member as PropertyInfo;
    if (property == null)
        throw new InvalidOperationException("Member in expression is not a property.");
    return property;
}

Now you can do something like this:
public void AddJavaScriptToken(Expression<Func<string>> propertyExpression)
{
    var p = GetProperty(propertyExpression);
    _javaScriptTokens.Add(p.Name, (string) p.GetValue(null, null));
}

public void RegisterJavaScriptTokens()
{
    AddJavaScriptToken(() => Tokens.TOKEN_ONE);
    AddJavaScriptToken(() => Tokens.TOKEN_TWO);
}

A: Here is a function that will get you the names of all static properties in a given type.
public static IEnumerable<string> GetStaticPropertyNames(Type t) {
  foreach ( var prop in t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ) {
    yield return prop.Name;
  }
}

If you want to build up the map of all property names to their values you can do the following
public static Dictionary<string,object> GetStaticPropertyBag(Type t) {
  var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
  var map = new Dictionary<string,object>();
  foreach ( var prop in t.GetProperties(flags) ) {
    map[prop.Name] = prop.GetValue(null,null);
  }
  return map;
}

Now you can call it with the following
var bag = GetStaticPropertyBag(typeof(MyResources));

A: You can accomplish this with reflection. The easiest way to get the property names is to loop over all of them.
foreach(var propInfo in this.GetType().GetProperties()) {
    var name = propInfo.Name;
    var value = propInfo.GetValue(this, null);
}

See GetProperties() and GetValue() for more specifics.

A: Well, I'm reluctantly answering my own question because I don't think it's possible to do this for a single static property.  Ultimately, I ended up hard-coding the key in the Dictionary using a cut-and-paste of the property name.  Here's what I ended up with:
  public void RegisterJavaScriptTokens()
  {
     AddJavaScriptToken(Token.FOOBAR_TITLE, "FOOBAR_TITLE");
  }

And here's the rest of the code:
  protected Dictionary<String, String> _javaScriptTokens = new Dictionary<String, String>();

  public void AddJavaScriptToken(string tokenValue, string propertyName)
  {
     _javaScriptTokens.Add(propertyName, tokenValue);
  }

  protected override void OnPreRender(EventArgs e)
  {
     if (_javaScriptTokens.Count > 0)
     {
        StringBuilder sb = new StringBuilder();

        foreach (KeyValuePair<String, String> kvp in _javaScriptTokens)
        {
           sb.AppendLine(String.Format("var TOKEN_{0} = unescape('{1}');", kvp.Key, PUtilities.Escape(kvp.Value)));
        }

        ClientScript.RegisterStartupScript(this.GetType(), "PAGE_TOKENS", sb.ToString(), true);
     }

     base.OnPreRender(e);
  }

I hate having to use cut-and-paste hard-coding to keep the property name and the key in sync...Oh well...

A: Other answers have already explained how you can get a list of the static properties via Reflection. You said you don't want all of them, only a subset of them. It seems, therefore, that you need a way to distinguish the properties you want from the ones you don't want. One way to do this is using custom attributes.
Declare a custom attribute class:
[AttributeUsage(AttributeTargets.Property)]
public class WantThisAttribute : Attribute { }

Add this custom attribute to the properties you want:
public static class MyResources
{
    [WantThis]
    public static string TOKEN_ONE { get { return "One"; } }

    [WantThis]
    public static string TOKEN_TWO { get { return "Two"; } }

    public static string DontWantThis { get { return "Nope"; } }
}

Iterate over the properties to find the ones you want:
public static Dictionary<string, object> GetStaticPropertyBag(Type t)
{
    var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
    var map = new Dictionary<string, object>();
    foreach (var prop in t.GetProperties(flags))
        if (prop.IsDefined(typeof(WantThisAttribute), true))
            map[prop.Name] = prop.GetValue(null,null);
    return map;
}


text:
Q: How to return content to two separate tabbable ID's upon one tab click using Twitter Bootstrap's Tabbable Tabs in a Rails 3.2 App Using Twitter Bootstrap's bootstrap-tab.js, I have:

about

education

experience

verified skills

 video

Content 1

...

...

...

How can I get it so if I put:

Content 2

... two places in the profile (once above and once below a navbar) and with different content in each, it would work? As of now, the content appears, but once its clicked, it disappears. Can there be two "active" li's at the same time?
Edit:
Since I'm using this in a Rails 3.2 App, I currently have the following in bootstrap-tab.js:
 $('#myTab a').click(function (e) {
   e.preventDefault();
  $(this).tab('show');
})

 $('#myTab a[href="#home"]').tab('show');
 $('#myTab a[href="#tab2"]').tab('show');
 $('#myTab a[href="#tab3"]').tab('show');
 $('#myTab a[href="#tab4"]').tab('show');
 $('#myTab a[href="#tab5"]').tab('show');
 $('#myTab a[href="#home2"]').tab('show');
 $('#myTab a[href="#tab22"]').tab('show');

and after putting the following in user_body.html.erb:

A: Here is one solution without extra javascript, and compatible with the plugin API.
The principle is to use 2 .tab-content and take advantage of the data-target selector attribute.
HTML
The first .tab-content contains your normal .tab-pane

home

class home

profile

messages

settings

and the second .tab-content contains the extra .tab-panes that are optionnal - plus an empty one (#notab_else here)

home_else

class home

Then you have your tabs with one extra attribute, data-target :

Home

Class Home

Profile

Messages

Settings

This attribute data-target defines the .tab-pane(s) associated with it. The magic is that you can use #ids or .classes or any valid jQuery selector.
JavaScript
All you need to activate everything is the default code :
$('#myTab a').click(function (e) {
    e.preventDefault();
    $(this).tab('show');
});

And you can also use your own actions to trigger the tabs as defined by the API.
You do not need that if you keep the default behavior for tabs.
$('#myTab a:first').tab('show');

EXTRA

*

*You can be free of any javascript if you set data-toggle="tab" to the a elements

*There is a fade effect available if you add the fade class to the .tab-pane (and fade in for the .active one)

DEMOS
Here is the demo (jsfiddle) and the demo with extra (jsfiddle)

A:

Home

Profile

Messages

Settings

Tab-1

Tab-2

Tab-3

Tab-4

Content 2

                                        OR

Home

Profile

Messages

Settings

Tab-1

Tab-2

Tab-3

Tab-4


text:
Q: Showing an alert message for WebService URL Connection Timeout Android I am invoking a webservice url and getting response Successfully in Andriod
here my Code:
protected String doInBackground(String... params) {
    HttpResponse response = null;
    // TODO Auto-generated method stub
    // String url=params[0];
    try {

    final HttpParams httpParams = new BasicHttpParams();
    HttpClient httpclient = new DefaultHttpClient(httpParams);

    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
    int timeoutSocket = 60*1000;
    HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);

    HttpGet request = new HttpGet("WebServiceURL");
        response = httpclient.execute(request);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d("Exaception1>>>","Exaception1>>");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.d("Exaception2>>>","Exaception1>>");

        e.printStackTrace();
    }
    statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
            // Whatever you wanna do with the response
            // Log.d("response", responseString);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.d("Exaception3>>>","Exaception1>>");

            e.printStackTrace();

        }

    } else {
        // Close the connection.
        try {
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    return responseString;
}

But Some times the WebService URL will not be in Active,My requirement is to Show an alert message to the user for Connection TimeOut ,Could any one help?

A: You can catch ConnectTimeoutException() in doInBackground so that you can show alert in onPostExecute() of your async task

A: Create one interface having methods such as success, error and timeout.
catch ConnectTimeoutException into async task and call interface's timeout method.
Handle this timeout method in asyncTask postexecute() or where you executed async task.

A: Catch the ConnectTimeOutException in your doInBackground and handle the error their
catch (ConnectTimeoutException e) {
            // handle exception
        }


text:
Q: HQL - Remember that ordinal parameters are 1-based? I'm trying to match a hibernate entity via by DAO class, the first method works but the second 'findByMatchingName()' fails with the exception below. What's wrong with this clause '%?%'> ?
public class RunnerDaoImpl extends GenericDaoImpl implements RunnerDao
{
    protected Class<Runner> getEntityClass() {
        return Runner.class;
    }

    // Works
    public List<Runner> findByExactName(String name)
    {
        return super.getHibernateTemplate().find("from Runner r where concat(r.firstname,' ',r.surname) LIKE =",new String[]{name});
    }

    // Fails
    public List<Runner> findByMatchingName(String name)
    {
        return super.getHibernateTemplate().find("from Runner r where concat(r.firstname,' ',r.surname) LIKE '%?%'",new String[]{name});
    }
}

The exception
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
    at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:79)
    at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:85)
    at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:421)
    at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:393)
    at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:918)
    at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912)
    at ie.bhaa.dao.RunnerDaoImpl.findByName(RunnerDaoImpl.java:15)
    at ie.bhaa.dao.RunnerDaoTest.findRunnerByName(RunnerDaoTest.java:36)
    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)

A: You need to add the wildchar(%) to the parameter and not the query. So modify your second query as below.
// This will work!
public List<Runner> findByMatchingName(String name)
{
    return super.getHibernateTemplate().find(
    "from Runner r where concat(r.firstname,' ',r.surname)
     LIKE ?",new String[]{"%"+name+"%"});
}

A: Put the % in the query parameter rather than in the query itself, so the parameter would become "%" + name + "%".


text:
Q: Limit on pinned tiles in TFS Team Project Overview page Is there a limit to how many pinned tiles or work item charts you can have on the Team Project Overview page in TFS 2013 Update 4? If so, what is that limit?

A: There is no specific restrictions of this in MSDN link. So, you may create it as many as you wish.
However, it's also unlikely to be infinity. It should meet some hardware bottlenecks of your local machine, such as there is no enough memory to load the TFS Team Project Overview page.


text:
Q: Twitter bootstrap white gap on right side of page I am having an issue with my responsive stylesheet with Twitter Bootstrap. The site shows up fine with no issues but for whatever reason the responsive tablet and phone have this huge white gap to the right of the page. Its not the scroll bar issue its a huge white gap
http://i.imgur.com/JeRRRqq.png
I dont believe I have changed to much at all here. Nothing with width or anything. Inspected the objects in Chrome and couldnt see anything overflowing over width wise

A: This might be a little late but I found the other answers to be misleading.
It is true that the row class is what is causing the issue, but that is because it is always supposed to be placed inside a container element.
from http://getbootstrap.com/css/ :

Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.

The container element usually has a -15px padding on both right and left and the row class has a 15px padding on right and left. The two cancel each other out. If one of the two is not present you will see extra space.

A: I am having the same problem. I discovered the object that was causing the padding to be created was Bootstrap's "row" class.
If you add
.row {
  padding-right: 0px;
  margin-right: 0px;
}

to your CSS file/row objects this should fix at least one of items causing padding on your page.

A: Have you tried:
html, body { overflow-x: hidden; }

Can you post a fiddle?

A: I had this problem, no one of this answers, did not help me, i solved my problem with this way:
body { overflow-x: hidden; width: 100vw;}

A: Add the following meta tag to your HTML
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=320, height=device-height, target-densitydpi=medium-dpi" />

Also try setting
html, body. div{
    margin: 0 !important;
    padding: 0 !important;
    width: 100%;
}

on the html and body

A: Generally this happens because you have a div breaking the boundaries of your set container width,could be a div or sections padding, margin, positioning.. you can use the inspector arrow or overflow:hidden on the container tag to see what section you might have breaking the width.

A: I had a very similar issue recently which took me quite sometime to figure out. For me, it was not the usual row/container issue. I was using a form-control to render checkboxes manually. In Bootstrap, all textual elements with form-control have width:100% by default. Having many checkboxes online was causing them to spill over (invisibly) and causing this large white gap on the right. Surprisingly, it wasn't easy to debug this using Chrome Dev tools either.
I am now using the following solution to set the width to auto; (this answer helped):
<input class="form-control form-control-inline" type="checkbox"  ... ... .. />
and
.form-control-inline {
  width: auto;
}

Hope it helps someone

A: Also, check to see how you're using containers. They can't be nested, they will cause problems.

You may choose one of two containers to use in your projects. Note that, due to padding and more, neither container is nestable.

Source: http://getbootstrap.com/css/#overview-container

A: I just had a very similar problem, and after spending some time, I realized I had applied CSS styling adding padding of 0px on both left and right of a container-fluid class, and therefore the styling overrode the default -15px padding needed on container-fluid to hold rows in their proper place.

A: I've had a similar issue on mobile devices. The problem was that I had hidden an element on smaller screen sizes, but forgot its parent container. This container was still being rendered even though its content was empty, which lead to a big white gap on the right site. Hiding the parent element instead of the child solved this for me.

A: My answer is an extension to @scott Shelby's answer.
I was able to get rid of the annoying white bar in the right by changing the meta of my file:
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=320, height=device-height, target-densitydpi=medium-dpi" />

Even after changing the meta, I was getting the white bar on my table as it was overflowing in mobile devices.
To fix this, I made sure to make all elements like images, forms, etc. responsive.
For images, you can use class: "img-fluid"
and for tables, you can use class: table-responsive in the parent div.

A: I also have this issue with a gap on one side. After long time I found out I didn't follow the Bootstrap structure. You have to be careful. row cannot contain a container; this will also cause a gap issue.
So:
container cannot be nested.
row cannot nest a container.
row has to be in a container.

A: /* Hide horizontal scrollbar */
.body, .head, .row, .col {
  overflow-x: hidden;
}

Doing this allows you to have a sticky navbar but still get rid of the whitespace!


text:
Q: censored data estimation Suppose $X_1, \cdots ,X_n$ are independent and identically distributed random variables with
probability density function
$$f(x|θ) = θ\, \exp(−θx),\quad \text{ for } x ≥ 0\,.$$
Each variable is censored if it exceeds $C$, a known constant.
Then we have: then
$$Pr(X > C) = \exp(−θC)\,.$$
Do anybody know why $$Pr(X > C) = \exp(−θC)?$$

A: If $f(x|θ) = θ e^{−θx}$ then $F(x|θ) = 1- e^{−θx}$ (by integration).
Hence $P(X>C) = 1-P(X\leq C) = 1-F(C) = 1-(1-e^{-\theta C}) = e^{-\theta C}$.


text:
Q: Passing environment variables from fastlane to Xcode build phase script Is it possible (and if so, how) to pass an environment variable from the script that runs fastlane down to an Xcode Run Script Phase?
My end goal is to read the current git branch name in the Run Script Phase. Our CI is ran by Team Foundation Server which does a git checkout of explicit commits, not branches, so the current branch always shows as HEAD.
TFS -> fastlane -> gym -> xcodebuild -> script that needs the branch

It is possible to get the branch that triggered the build only via an environment variable set by TFS. My plan is to get that value down to the Xcode script to do what I need.
I would prefer not to use this as it passes all enviornment variables to the build process, if I understand it correctly.
defaults write com.apple.dt.Xcode UseSanitizedBuildSystemEnvironment -bool NO

A: To pass env-variables to BuildPhases use xcargs in Fastfile:
build_app(workspace: ..., scheme: ..., xcargs: "SOMEVAR1='one' SOMEVAR2='two'")

This command generates xcodebuild ... SOMEVAR1='one' SOMEVAR2='two', and then these variables will become available in Build Phases.


text:
Q: Sqlalchemy gives 'Function sequence error (0) (SQLFetch)') I am connecting to sql database and it used to work fine just last month.
However the job produced an error and I cannot figure out what does it want?
from statistics import variance
from tkinter import Variable
import pandas as pd
import shutil
import os
import sqlalchemy as sa
import openpyxl

import urllib
params = urllib.parse.quote_plus("Driver={ODBC Driver 17 for SQL Server};"
                                  "SERVER=101010;"
                                  "DATABASE=MyDb;"
                                  "UID=MyUid;"
                                  "PWD=1234")

engine = sa.create_engine("mssql+pyodbc:///?odbc_connect={}".format(params))

# read .sql file
sql01 = open('SP_ParamsTest.sql', 'r')
sqlFile = sql01.read()
sql01.close()

# this lines generates an error:
df_params = pd.read_sql(sqlFile, con=engine)

full error message:
Traceback (most recent call last):
  File "C:\Users\MyPath\.venv\lib\site-packages\sqlalchemy\engine\cursor.py", line 977, in fetchall
    rows = dbapi_cursor.fetchall()
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC Driver 17 for SQL Server]Function sequence error (0) (SQLFetch)')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
    rows = self._fetchall_impl()
  File "C:\Users\MyPath\.venv\lib\site-packages\sqlalchemy\engine\cursor.py", line 1805, in _fetchall_impl
    return self.cursor_strategy.fetchall(self, self.cursor)
  File "C:\Users\MyPath\.venv\lib\site-packages\sqlalchemy\engine\cursor.py", line 981, in fetchall
    self.handle_exception(result, dbapi_cursor, e)
  File "C:\Users\MyPath\.venv\lib\site-packages\sqlalchemy\engine\cursor.py", line 941, in handle_exception
    result.connection._handle_dbapi_exception(
  File "C:\MyPath\.venv\lib\site-packages\sqlalchemy\engine\base.py", line 2124, in _handle_dbapi_exception
    util.raise_(
  File "C:\Users\MyPath\.venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
    raise exception
  File "C:\Users\MyPath\.venv\lib\site-packages\sqlalchemy\engine\cursor.py", line 977, in fetchall
    rows = dbapi_cursor.fetchall()
sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('HY010', '[HY010] [Microsoft][ODBC Driver 17 for SQL Server]Function sequence error (0) (SQLFetch)')
(Background on this error at: https://sqlalche.me/e/14/dbapi)

A: I see you've got this working already, but there is another problem I want to mention since sqlalchemy has been updated.
Since sqlalchemy 2.0 passing a string to Connection.execute() has been removed, we need to use the text() construct, or the Connection.exec_driver_sql() method to use a SQL string
What this means is simply to use:
from sqlalchemy import text
...
df_params = pd.read_sql(text(sqlFile), con=engine)

With this text() function you can also put the sql parameters into the SQL query like this (Tables from AX 2012 database):
SELECT ITEMID
FROM INVENTTABLE
WHERE ITEMID = :id

And use those parameters safely from the program with
df_params = pd.read_sql(text(sqlFile), con=engine, params= {'id': '100001'})


text:
Q: Cabal Install trouble resolving dependencies I'm following this tutorial trying to set up a Haskell project: http://shuklan.com/haskell/lec10.html#/0/9
I've had this issue before with 'cabal install'.
I get the message below. I read to try 'rm -rf ~/.ghc ~/.cabal'. I tried that and 'cabal install' again, along with 'cabal new-build' but I still get the same message.
How can I fix this? I'm on Mac OS X 10.11.4. I can make and run .hs files and us ghci. I've never created a "file structure" or anything like that with other programming languages, so I'm not familiar with what's involved.
Thank you!!

Please switch to using either the new project style and the new-install
command or the legacy v1-install alias as new-style projects will become the
default in the next version of cabal-install. Please file a bug if you cannot
replicate a working v1- use case with the new-style commands.

For more information, see: https://wiki.haskell.org/Cabal/NewBuild

Resolving dependencies...
cabal: Could not resolve dependencies:
[__0] trying: FirstCabalInit-0.1.0.0 (user goal)
[__1] next goal: base (dependency of FirstCabalInit)
[__1] rejecting: base-4.12.0.0/installed-4.1... (conflict: FirstCabalInit =>
base==4.6.*)
[__1] rejecting: base-4.12.0.0, base-4.11.1.0, base-4.11.0.0, base-4.10.1.0,
base-4.10.0.0, base-4.9.1.0, base-4.9.0.0, base-4.8.2.0, base-4.8.1.0,
base-4.8.0.0, base-4.7.0.2, base-4.7.0.1, base-4.7.0.0, base-4.6.0.1,
base-4.6.0.0, base-4.5.1.0, base-4.5.0.0, base-4.4.1.0, base-4.4.0.0,
base-4.3.1.0, base-4.3.0.0, base-4.2.0.2, base-4.2.0.1, base-4.2.0.0,
base-4.1.0.0, base-4.0.0.0, base-3.0.3.2, base-3.0.3.1 (constraint from
non-upgradeable package requires installed instance)
[__1] fail (backjumping, conflict set: FirstCabalInit, base)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: base, FirstCabalInit ```

A: You can find the following guide to build tools in Haskell useful:

*

*https://kowainik.github.io/posts/2018-06-21-haskell-build-tools
According the error message, it looks like in your .cabal file you have a line like
build-depends: base == 4.6.*

This version of the standard library base is very old, it corresponds to GHC-7.6, however, according to the error message, you have GHC-8.6.5 installed. Since base versions are bundled with GHC, you can't use base for GHC you didn't install. See the following list of matching base and GHC versions:

*

*https://wiki.haskell.org/Base_package
It looks like your error can be resolved by the following fix:
build-depends: base == 4.12.*

For the future, I can recommend using ghcup tool to manage GHC and cabal-install versions on macOS:

*

*https://www.haskell.org/ghcup/
Alternatively, you can use stack build tool, it manages GHC versions for you in a sandboxed location.

A:
Famous "cabal hell".

You're better use newest package manager https://docs.haskellstack.org/en/stable/README/ .


text:
Q: Preserve scroll position on DOM update in vue.js I have a chat application which loads the recent chat messages and store them in messages array. Previous chat history is loaded on scroll and will be added to the beginning of messages array. I need to preserve the scroll position when history is loaded
//chat.vue

        {{item.body}}

In fetchHistory method, I add the old messages to beginning of messages array
fetchHistory(){
    if(this.$refs.messageHistory.scrollTop == 0){
        var vm = this
        this.currentPage.prevPage().then(paginator => {
            vm.messages.unshift(...paginator.messages)
        });
    }
}

A: Subtract initial height from final height in nextTick() function and update scroll position
fetchHistory(){
    if(this.$refs.messageHistory.scrollTop == 0){
        var initialHeight = this.$refs.messageHistory.scrollHeight
        var vm = this
        this.currentPage.prevPage().then(paginator => {
            vm.messages.unshift(...paginator.messages)
            vm.$nextTick(() => {
              vm.$refs.messageHistory.scrollTop = vm.$refs.messageHistory.scrollHeight - initialHeight
            })
        });
    }
}


text:
Q: apply effects to a recorded audio using web audio api I'm using the recording voice demo found in the web audio demos.Anyway I want to add an effects to the obtained audio once finished recording.
here is my effect:
function createDelay() {
var delayNode = null;
if (window.location.search.substring(1) == "webkit")
    delayNode = audioContext.createDelay();
else
    delayNode = audioContext.createDelay();
delayNode.delayTime.value = parseFloat( document.getElementById("dtime").value );
dtime = delayNode;

var gainNode = audioContext.createGain();
gainNode.gain.value = parseFloat( document.getElementById("dregen").value );
dregen = gainNode;

gainNode.connect( delayNode );
delayNode.connect( gainNode );
delayNode.connect( wetGain );

return delayNode;
}

and here is my success function when recording where the nodes are connected to the destination:
function gotStream(stream) {
inputPoint = audioContext.createGain();

// Create an AudioNode from the stream.
realAudioInput = audioContext.createMediaStreamSource(stream);
audioInput = realAudioInput;
audioInput.connect(inputPoint);
analyserNode = audioContext.createAnalyser();
analyserNode.fftSize = 2048;
inputPoint.connect( analyserNode );

audioRecorder = new Recorder( inputPoint );

zeroGain = audioContext.createGain();
zeroGain.gain.value = 0.0;
inputPoint.connect( zeroGain );
zeroGain.connect( audioContext.destination );
updateAnalysers();
}

so how can I connect the effect to the obtained audio file after recording?in other words how do I connect the wet gain in the gotStream function?
my question might seem little clumsy but I'm very new to javascript especially to web audio

A: OK. So the demo creates such a graph.
realAudioInput -> inputPoint -> audioRecorder -> recorderJSNode -> destination

                       ||    -> zeroGain -> destination

                       ||    -> analyserNode

So if you want to add your effect to just the recording, you have to insert it between the inputPoint and the 'recorderJSNode'.
The best way of doing that would be something along these lines.
var delayNode = createDelay();
inputPoint.connect( delayNode );
audioRecorder = new Recorder( delayNode );

instead of just
audioRecorder = new Recorder( inputPoint );

So your graph would look like this.
realAudioInput -> inputPoint -> audioRecorder -> delayNode -> recorderJSNode -> destination

                       ||    -> zeroGain -> destination

                       ||    -> analyserNode

A: If you want to apply effects to the audio after recording, you can use Web Audio API's Offline Context.
//after the recording is finished

var offlineContext = new webkitOfflineAudioContext();
var source = offlineContext.createBufferSource();
source.buffer = buffer; //here you set the recording as the buffer
var delay = offlineContext.createDelay();
delay.delayTime.value = 0.2; // set the delay time
source.connect(delay);
delay.connect(offlineContext.destination);

//the success callback
offlineContext.onComplete = function(e){
    //it returns the rendered buffer
    var result = e.renderedBuffer;
};

offlineContext.startRendering(); // start the offline rendering process

Since you are using Recorder.js in your question, you can get the recorded audio as Float32Array using recorder.getBuffer method.
But If you want to record the "wet" signal in real-time, you can just set Recorder's source to be the DelayNode rather than input or the "dry" signal.


text:
Q: Why webpack adding comments I'm confused about that, why webpack adding comments to the bundle file like this:
/******/ function blabla() {
/******/ }

A: It does this to help with debugging etc. -- the comments tell you what source file the function came from, and what module # it's being loaded by (at runtime). If you use the Uglify plugin, it will strip out the comments.


text:
Q: autohotkey word com obj add multiple tables I try to create a word document with two tables with Autohotkey. I could successfully add one table and type some text. Now I try to create another table in the same document below old table.
oWord := ComObjCreate("Word.Application")       ; create MS Word object
Document := oWord.Documents.Add             ; create new document
oWord.Visible := 1                  ; Make winword visible
range := oWord.ActiveDocument.Range(0, 0)       ; Set Range
oWord.ActiveDocument.tables.Add(range,1,2)      ; Add table in range
oWord.Selection.Tables(1).Style := "Table Grid"     ; set style
oWord.Selection.Tables(1).Cell(1,2).Range.Select    ; select a cell
oWord.Selection.TypeText("Hi hi")           ; type a text in selected cell
oWord.Selection.EndKey                  ; from here I couldn't able to create a new table
oWord.Selection.TypeParagraph
range := oWord.ActiveDocument.Range(0, 0)
oWord.ActiveDocument.tables.Add(range,10,5)
oWord.Selection.Tables(1).Style := "Table Grid"
oWord.Selection.Tables(1).Cell(1,3).Range.Select    ; get error 0x800A1735 and it mentions 'Cell' The requested member of the collection does not exist
;oWord.Selection.TypeText("Hi di")
oWord.Quit

What wrong I am doing here?

A: Thank you for everyone for trying to give solution for this question. I could able to figure out one idea two hours after posting this question. I had to add
oWord.Selection.MoveDown(5,1)
before
oWord.Selection.EndKey
and modify
oWord.ActiveDocument.tables.Add(oWord.Selection.Range,5,5)
instead
oWord.ActiveDocument.tables.Add(range,5,5)
and removed second
range := oWord.ActiveDocument.Range(0, 0)

A: ;OP reports being unable to add a second table.
;The following AutoHotkey code demonstrates the use of Selection.Range to properly place the additional table.

full_command_line := DllCall("GetCommandLine", "str")

if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
    try ; leads to having the script re-launching itself as administrator
    {
        if A_IsCompiled
            Run *RunAs "%A_ScriptFullPath%" /restart
        else
            Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
    }
    ExitApp
}

oWord := ComObjCreate("Word.Application")
; create MS Word object
Document := oWord.Documents.Add
; create new document
oWord.Visible := 1                  ; Make winword visible
range := oWord.Selection.Range
; Set Range - this was at the heart of the problem
; reported by OP
oWord.ActiveDocument.tables.Add(range,11,5)
; Add table in range with 11 rows and 5 columns
oWord.Selection.Tables(1).Style := "Table Grid"
; set style to Table Grid
oWord.Selection.Tables(1).Cell(1,1).Range.Select
; select a cell ("A1" in Excel parlance)
oWord.Selection.TypeText("A1")
; type identifying text in selected cell
oWord.Selection.MoveDown(5, 12, 0)
; wdLine := 5, Count has no constant. wdMove is 0, wdExtend is 1
oWord.Selection.TypeText("Ending first table.")
oWord.Selection.TypeParagraph
oWord.Selection.TypeText("Starting second table.") ; Just what is to be expected.
oWord.Selection.TypeParagraph
range2 := oWord.Selection.Range
; Set Range - this was at the heart of the problem
; reported by OP
oWord.ActiveDocument.tables.Add(range2,11,5)
; Add another table in range
oWord.Selection.Tables(1).Style := "Table Grid"
; set style
oWord.Selection.Tables(1).Cell(2,2).Range.Select
; select a cell (would be "B2" if this were Excel)
oWord.Selection.TypeText("B2")
; type identifying text in selected cell
oWord.Selection.MoveDown(5, 12, 0)
; wdLine := 5, Count has no constant. wdMove is 0, wdExtend is 1
oWord.Selection.TypeText("End of table demonstration")