text:
Q: How do I test for button press on pause command in batch? I am writing a batch script, in which a user reads a disclaimer, then they press any key to continue, or "E" to exit. It looks something like this:
@echo off
echo (some disclaimer text here)
echo.
echo once you fully understand this message, press any key to continue, or press "E" to exit.
::I know that pause doesn't take input, I'm just using it as a placeholder for something
pause>nul
cls
echo Welcome!
pause

Is there any way to accomplish this? Thanks!
To clarify, I want to exit the second they press the E key. I have seen it done before, but I forgot where it saw it.

A: Choice.exe does what you describe, though it doesn't have an option for "any key".  You can specify a specific key such as "Y" below.
echo once you fully understand this message, press "Y" to continue, or press "E" to exit.
choice /c ey
if errorlevel 2 goto :welcome
if errorlevel 1 goto :canceled

rem User pressed Ctrl+C

:canceled
rem User pressed E.  Do cancel stuff.
goto :eof

:welcome
rem User pressed Y.  Do welcome stuff
echo Welcome!


text:
Q: How to select Multiple Item in Dropdown and bind in textbox I am having dropdownlist with some values. If i choose multiple items in dropdown it has to bind in textbox in the format of
ex:
'xxxx','xxxx','xxxx'
Please do the needful
Thanks

A: I dont think you can choose multiple items in a dropdownlist. Lets suppose that you meant listbox. Your selected index changed event function must be like:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    for (int i = 0; i < ListBox1.Items.Count; i++)
    {
        if (ListBox1.Items[i].Selected)
        {
            TextBox1.Text =TextBox1.Text + "'" + ListBox1.Items[i].Text + "' ";
        }
    }
}

Update for comma :
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    for (int i = 0; i < ListBox1.Items.Count; i++)
    {
        if (ListBox1.Items[i].Selected)
        {
             if (TextBox1.Text == "")
             {
                 TextBox1.Text = TextBox1.Text + "'" + ListBox1.Items[i].Text + "'";
             }
             else
             {
                 TextBox1.Text =TextBox1.Text + ",'" + ListBox1.Items[i].Text + "'";
             }
        }
    }
}

A: I am not sure, I think this can help you with your requirement
http://www.obout.com/combobox/aspnet_selection_multi.aspx
When ever you select multiple items the items are displayed in the combobox itself exactly in the format you specified

A: I suggest you server side server .net server side control
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

client side HTML control
<select multiple="multiple">
   <option value="value">text</option>
   <option value="value">text</option>
</select>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap 4 different popover & tooltip styles for each elements I want give different styles to tooltip and popover elements for each sections on Bootstrap 4 For example:
A color and other css options for this element:

And another css options for this element:

Bootstrap 3x adding the popover codes into the element. And i can give styles easily with element's classes. But Bootstrap 4 adding the popover codes to body. How i can solve this?

A: Via js:
$(document).ready(function(){
    $('[data-toggle="popover"]').popover({
        trigger: 'click',
        template: '

'
    });
});


text:
Q: Allow user to cancel adding of an entry in C# WinForms DataGridView I have decided to use DataGridView in-place editing in my C# WinForms application. I want to let the user add a new row and when he moves away, store that row in the database. In this current situation, there is only one column. Also, each entry should be unique.
If he enters some unique value in there, the row gets validated and all works well. If he enters a duplicate value, in the RowValidating event I would set e.Cancel = true and show an error MessageBox.
The problem is that if he starts adding, but then changes his mind and doesn't want to add anymore, there's no way for him to cancel it other than closing the form.
I tried adding this to the RowValidating event, but it doesn't allow clicking anywhere else other than the current row:
if (dgv_Industries[e.ColumnIndex, e.RowIndex].Value == null || string.IsNullOrEmpty(dgv_Industries[e.ColumnIndex, e.RowIndex].Value.ToString()))
{
    e.Cancel = true;
    return;
}

If I don't set e.Cancel = true, but just return, it moves on to trigger the RowValidated event. I could abort the database operation here but I would be stuck with an empty row (aside from the standard empty add row) in the DataGridView, as below, which not only looks wrong, it also makes my functionality crash (unless I implement more checks).

Then I tried doing this in the RowValidated event but it yielded an Operation cannot be performed in this event handler. exception:
dgv_Industries.Rows.RemoveAt(e.RowIndex);

What would be the correct way of allowing the user to cancel the addition of a new row, while also removing the row it created?


text:
Q: How to approach to this design - iOS My App is Navigation based Application for iPad.
First Screen is Home Screen. On Clicking button on Home Screen, it pushes to Map Screen. On the Map Screen, i have left Panel (view controller) over the map view controller which occupies 1/4 of the screen.
Left Panel is a View Controller which has Table View. On clicking cell, it should push new viewcontroller to left panel leaving the map view controller behind.
             Push
Home Screen -------- Map Screen
                  |(Added over map screen)         Push
                  |----- Left Panel (Table View) -------- Detail View

I can't use Split View Controller because there is a navigation in left panel as well as in Home Screen. Some times i need to animate/hide left panel. I can customise left panel.
How to implement this structure. Is it good to use Nested Navigation Controller or is there any library available. My App supports both Portrait and Landscape. I am using Swift.

A: I'm sorry, I don't know Swift as well. However, I think you have to declare a base layout:
you will have a MainViewController that will include a LeftPanelViewController and a FrontViewController. In the MainViewController nib, you will create the main layout using AutoLayout: add a UIView at the left of the screen and another UIView for the frontpage.
Then, link outlets and you will have the layout done! Then you have only to add/remove subviews to leftPanelView and to FrontView.
Now, I think that the right logic is that MainViewController is the NavigationController, so you have to implement the protocol of LeftPanelViewController and FrontViewController, so Main will know how and when add/remove subviews.
The important things is that no one object have to know the existence of MainViewController to preserve the logic. So you have to notify MainViewController for something, to use delegation pattern or something else as NSNotification (be aware, it could be much weight...)
I hope it will bel helpful. Bye

A: I would solve this by adding a ContainerView as your Left Panel. As you want to do pushes here, you can make the container view controller a navigation controller with the table view as its root view controller.
You'll still be able to animate/hide the container view just like any other view.

A: This extension for the UIViewController creates the side panel to the left.
private var temp_view:UIView?
private var temp_width:CGFloat?
private weak var temp_sidebar:UIViewController?

 extension UIViewController {

func configureSideBar(StoryBoard:String,SideBarIdentifier:String,View:UIView){

    var storyboard = UIStoryboard(name: StoryBoard, bundle: nil)
    weak var sidebar = storyboard.instantiateViewControllerWithIdentifier(SideBarIdentifier) as? UIViewController
    let width:CGFloat = 250//sidebar!.view.frame.size.width
    let height = UIScreen.mainScreen().bounds.height
    let frame = CGRectMake(0, 0, width, height)

    temp_view = View
    temp_width = width
    temp_sidebar = sidebar

    sidebar!.view.frame = frame
    addChildViewController(sidebar!)
    view.addSubview(sidebar!.view)
    view.sendSubviewToBack(sidebar!.view)
    toogleSideBarWithAnimation(0.2,Open:false)

}

func getSidebar() -> UIViewController?{

    if let sdbar = temp_sidebar {
        return sdbar
    }
    else {
       println("Warning:You have tou configure sidebar first")
        return nil
    }

}

func toogleSideBarWithAnimation(Duration:NSTimeInterval,Open:Bool) {

    if let view = temp_view {
        UIView.animateWithDuration(Duration, delay: 0, options: UIViewAnimationOptions.TransitionFlipFromLeft, animations: {
            var Frame = view.frame

            if !Open{

                Frame.origin.x = 0
            }
            else {
                Frame.origin.x = temp_width!
            }

            view.frame = Frame
            }, completion: { finished in

        })
    }
    else {
        println("Warning:You have tou configure sidebar first")

    }
}

}
Let me explain how to use it.
First create a view controller scene and set the storyboard id. In this examples i used "sidebar"
Then add this instruction to the map view controller to the viewDidLoad like this
    override func viewDidLoad() {
    super.viewDidLoad()
    self.configureSideBar("Main", SideBarIdentifier: "sidebar", View: Subview)
}

I suggest adding a UIView with all your view in it in the map view controller
To open and close it use this instruction
self.toogleSideBarWithAnimation(0.2,Open:OpenSidebar)


text:
Q: hiding content when variable is not present I am using php to publish news articles from my mysql database. The articles have images placed within their text. The images are stored as variables, each its own path. The problem is I don't always use the full complement of images for each article, and the way I've written it, a broken image displays.
In short, how can I keep broken images from showing up if say '$image_ii' or '$image_iii' does not exist for a specific ID.
The way I have it written out is as follows:
            <?php
            include ('connect.php');

            $friendly_url=$_GET['friendly_url'];
            $query = "SELECT * FROM entries WHERE friendly_url='$friendly_url'";
            $entries = mysql_query($query);

            while($row = mysql_fetch_array($entries, MYSQL_ASSOC))
            {
              $title = $row['title'];
              $author = $row['author'];
              $pub_date = $row['pub_date'];
              $content_i = $row['content_i'];
              $content_ii = $row['content_ii'];
              $content_iii = $row['content_iii'];
              $content_iv = $row['content_iv'];
              $image_i = $row['image_i'];
              $image_ii = $row['image_ii'];
              $image_iii = $row['image_iii'];
              $image_caption_i = $row['image_caption_i'];
              $image_caption_ii = $row['image_caption_ii'];
              $image_caption_iii = $row['image_caption_iii'];
              $pre_link = $row['pre_link'];
              $post_link = $row ['post-link'];
              $id = $row['id'];
              $friendly_url = $row['friendly_url'];
              $american_date = date("F d, Y", strtotime($pub_date));
              $friendly_content_i = nl2br($content_i);
              $friendly_content_ii = nl2br($content_ii);
              $friendly_content_iii = nl2br($content_iii);
              $friendly_content_iv = nl2br($content_iv);

              echo "

$title

                <div id='post-content'

                $friendly_content_i

 $image_caption_i

                $friendly_content_ii

 $image_caption_ii

                $friendly_content_iii

 $image_caption_iii

                $friendly_content_iv

  by $author
 $american_date

 ";

            } mysql_close($connection); ?>

Apologies if this is terrible, it's my first dynamic website.

A: Try using the following snippet
if (file_exists("../".$image_iii)) {
    echo "";
} else {
    echo "";
}

A: You already told us the solution to your problem:

if say '$image_ii' or '$image_iii' does not exist for a specific ID.

Use if file_exists() to check that your image exists, and don't output it, if it doesn't.
Furthermore I see you're using mysql_query - This is deprecated and very unsafe. You should use mysqli or PDO instead

A: I ended up finding a solution that worked using:
                 if (!empty($image_iii)) { echo ""; }
                                    else { echo "";}

That said, clearly you kind folks are right about me needing to swap over to mysqli...found this website as a good resource for migrating code to mysqli. Thanks to everyone who responded, everyones comments were helpful.


text:
Q: Entity object : Cloning and Inserting I am trying to clone/copy an entity object and insert it to the DB. I am using Entity Framework.
I found several similar question here and over other forums. Though the exact issue, None of the solution worked for me.
Application orginalApp = new Application().GetById(origAppId);
Application clonedApp = orginalApp.Clone<Application>(); //uses DataContractSerializer
DataBaseContext.Current.Detach(orginalApp); // Current is a property which returns Database context which is stored in httpcontext.current.items

clonedApp.EntityKey = null; // tried with and without this

clonedApp.Application_Id = 0; // tried with and without this. This is the primary key
clonedApp.Application_Name += " (clone)";

clonedApp.Create();   //The usual Addobject and SaveChange()

This throws the following error:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I tried to check for existance of the object in object state manager.
DataBaseContext.Current.ObjectStateManager.GetObjectStateEntry(clonedApp)

It give me Null.
* Though, I couldnt find a solution, got to a workaround for the requirement using reflection.*

A: This error says that you have the same primary key for your new object as you did for your old one, if you are cloning rows, you will need a new PK for the cloned row


text:
Q: Layout constraints inside NSBox force objects outside box I'm having problems putting constraints on objects inside an NSBox.  The top-to-top constraint which I expect to position an object inside the NSBox actually forces it below the NSBox.
To demonstrate:

*

*I've added a Box (NSBox).

*Place a Check Box Button (NSButton) inside it

*With the check box selected, Add New Constraint 8 px to the top

This creates a Vertical Space Constraint that is Check.Top to Superview.Top, and I expect it to place the Check inside the NSBox 8 pixels below the top.  However, it gets repositioned 8 px below the box, but hidden from view (because of clipping).

The warning is about the NSButton's X position, which I simply haven't set yet.  Adding leading and trailing constraints will make the warning go away, but doesn't fix the main problem, which is the misplacement in the Y position.
Am I doing something wrong here?


text:
Q: AngularJS bootstrapUI : Typehead multiple select directive I'm very new to AngularJS and i have some troubles understanding how the select directive work (Official doc).
I used the bootstrap UI example at http://angular-ui.github.io/bootstrap/ (bottom of the page) to create a live search.
Here is my code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">

            <input type="text" ng-model="customSelected" placeholder="Custom template" typeahead="quote.symbol as quote.name for quote in json | filter:{$: $viewValue} | limitTo:8" typeahead-template-url="quotes_local.html" class="form-control">

See in plunker too
Currently, when i start typing, it searches for company name and when i select a company it writes its symbol in the field.
What i would like to do is that it searches in company name and symbol name. In the template it should display : Symbol - Company Name and highlight whenever it needs both on the symbol and the company name.

A: You just need to add symbol string to the template and typehead
The symbol in the drop down list:

becomes:
{{ match.model.symbol }} -

and to add the symbol to typehead:
typeahead="quote.symbol as quote.name for quote in json | filter:{$: $viewValue} | limitTo:8"

becomes:
typeahead="quote.symbol + ' - ' + quote.name as quote.name  for quote in json | filter:{$: $viewValue} | limitTo:8"

heres the plunker

A: All you need to do is specify a string concatenation of symbol and name separated with a dash in your input's typeahead directive:
typeahead="quote.symbol as quote.symbol + ' - ' + quote.name for quote in json | filter:{$: $viewValue} | limitTo:8" typeahead-template-url="quotes_local.html" class="form-control">
                           |_______________________________|

So, the first section of typehead:
quote.symbol as quote.name for quote in json

becomes:
quote.symbol as quote.symbol + ' - ' + quote.name for quote in json

See the complete code sample here... (Same plunker link as above.)


text:
Q: Android: Null object reference error on adding exoplayer I am trying to stream a video and show the subtitles in an app.
I have the following methods:
 private void initializePlayer() {

    Uri uri = Uri.parse("http://www.storiesinflight.com/js_videosub/jellies.mp4");
    //subtitle http://www.storiesinflight.com/js_videosub/jellies.srt
    MediaSource mediaSource = buildMediaSource(uri);
    player.prepare(mediaSource, true, false);
}
private MediaSource buildMediaSource(Uri uri) {
    return new ProgressiveMediaSource.Factory(
            new DefaultHttpDataSourceFactory("exoplayer-codelab")).
            createMediaSource(uri);
}
@SuppressLint("InlinedApi")
private void hideSystemUi() {
    playerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}

 private void releasePlayer() {
        if (player != null) {
            playWhenReady = player.getPlayWhenReady();
            player.release();
            player = null;
        }
    }

and I am calling them as follows:
  @Override
    public void onStart() {
        super.onStart();
        if (Util.SDK_INT > 23) {
            initializePlayer();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        hideSystemUi();
        if ((Util.SDK_INT <= 23 || player == null)) {
            initializePlayer();
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        if (Util.SDK_INT <= 23) {
            releasePlayer();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (Util.SDK_INT > 23) {
            releasePlayer();
        }
    }

I am getting the following error on starting my app:
 java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.widget.ActionBarContainer.setAlpha(float)' on a null object reference
        at androidx.appcompat.app.WindowDecorActionBar.doHide(WindowDecorActionBar.java:842)
        at androidx.appcompat.app.WindowDecorActionBar.updateVisibility(WindowDecorActionBar.java:782)
        at androidx.appcompat.app.WindowDecorActionBar.hideForSystem(WindowDecorActionBar.java:725)
        at androidx.appcompat.widget.ActionBarOverlayLayout.onWindowSystemUiVisibilityChanged(ActionBarOverlayLayout.java:244)
        at androidx.appcompat.widget.ActionBarOverlayLayout.setActionBarVisibilityCallback(ActionBarOverlayLayout.java:174)

The error seems to be related to the actionbar but I am not using it nor I am changing its alpha. Why is this happening? Please help
upadte:
added ui xml and buildMediaSource issue
 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/player"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </com.google.android.exoplayer2.ui.PlayerView>
<com.google.android.exoplayer2.ui.SubtitleView
    android:id="@+id/subtitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_marginBottom="64dp"/>
</FrameLayout>

Also while adding the subtitles I am having trouble merging the media source of the video and the subtitle:
 private MediaSource buildMediaSource(Uri uri) {
      MediaSource mediaSource =  new ProgressiveMediaSource.Factory(
                new DefaultHttpDataSourceFactory("exoplayer-codelab")).
                createMediaSource(uri);
        if((srt_link==null|| srt_link.equals("false") || srt_link.isEmpty())){

            return mediaSource;
        }
        Format textFormat = Format.createTextSampleFormat(null, MimeTypes.APPLICATION_SUBRIP,
                Format.NO_VALUE,"hi");

        Uri uriSubtitle = Uri.parse(srt_link);
        MediaSource subtitleSource =new SingleSampleMediaSource(uriSubtitle, new DefaultHttpDataSourceFactory("exoplayer_video"), textFormat, C.TIME_UNSET);

        MergingMediaSource mergedSource = new MergingMediaSource(mediaSource, subtitleSource);

        return mergedSource;

    }

SingleSampleMediaSource is deprecated. How do I merge the two.


text:
Q: Rails using global constants in environment.rb I'm trying to access global constants that I define in environment.rb from my controller. I don't think I'm doing it right because they end up being uninitialized in my controller. What would be the correct way of doing so? Thank you.
# Load the rails application
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Apis::Application.initialize!

KEY_1 = "aghtbjki"
SHARED_SECRET_1 = "plkjuvfe"
KEY_2 = "ljfebjyf"

If I'm trying to use KEY_1 in my controller for example, how should I do it?

A: In general, I don't like putting things in environment.rb and put instead in initializers/my_initializers.rb like:
KEY_1 = "aghtbjki"

putting it environment.rb seems wrong


text:
Q: How to prepare query parameters in java Coming from a background in PHP/CodeIgniter where running queries is as simple as...
$this->db->query('SELECT * FROM users WHERE id = ?', array(
    $userId
));

I'm trying to accomplish something similar with Java.  I know running straight queries can be as simple as...
    TypedQuery<Guest> query = em.createQuery(
        "SELECT g FROM Guest g ORDER BY g.id", Guest.class);
    return query.getResultList();

But how do I inject parameters into the queries?

A: You use either named parameters or positional parameters.
Named parameter
SELECT g FROM Guest g WHERE g.name = :name
Then you can write this on your query reference:
query.setParameter("name", aName)
Positional parameter
SELECT g FROM Guest g WHERE g.name = ?1
Then you can write this on your query reference:
query.setParameter(1, aName);


text:
Q: How to initialize List in empty class constructor? The following code obviously doesn't work because List<E> is abstract:
public class MyList {
    private List<E> list;

    public MyList() {
        this.list = new List<E>();
    }
}

How can I initialize MyList class with an empty constructor if I need the list variable to be a LinkedList or a ArrayList depending on my needs?

A: I'm not sure whether this is what you're asking...
public class MyList {
    private List<E> list;

    public MyList() {
        if (myNeeds)
            this.list = new LinkedList<E>();
        else
            this.list = new ArrayList<E>();
    }
}

A: There are better alternatives for what you are trying to achieve:

*

*Create a base class (abstract?) and override it twice, once for ArrayList and one for LinkedList

*Inject the appropriate list to your class (dependency injection)

A: Why not use a protected (and possibly abstract method) like:
public abstract class MyList<T> {

    protected final List<T> list;

    public MyList() {
        list = createList();
    }

    public MyList(boolean preferLinked) {
        list = preferLinked? new LinkedList<T>() : new ArrayList<T>();
    }

    // Allows client code which subclasses from MyList to override the
    // default behaviour

    protected List<T> createList() {
        return new ArrayList<T>();
    }
}

A: boolean shouldThisBeAnArrayList=true; // Set to false to use LinkedList
if(shouldThisBeAnArrayList) {
   this.list = new ArrayList<E>();

}
else {
   this.list=new LinkedList<E>();
}

A: You need to determine what "your needs" are in the default case - LinkedList or ArrayList.  If you can't - say, if the need changes depending on something that happens over the object's lifetime, then the list needs to change, too.

A: List is an interface and as such, cannot be constructed. Only implementations of said interface can be constructed (e.g. ArrayList). Also, you need to know the type (E) at construction.
This should work:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MyList<E> {
    private List<E> list;

    public MyList(boolean linked) {
        if (linked) {
            list = new LinkedList<E>();
        } else {
            list = new ArrayList<E>();
        }
    }
}

A: I would think you could do the following:
public class MyList<T> {
    private List<T> list;

    public MyList() {
        this.list = new ArrayList<T>();
    }
}

A: As I understand, you cannot use just a empty constructor, because you have a decision node in your model, when you need to choose between the type of the list, so, you will have to tell the program any way what kind of list will be.
This seems to be the best solution in my opinion:
public class MyList {
    private List<E> list;

    public MyList() {
        this.list = new LinkedList<E>();
    }

    //an overload for another type,
    public MyList(bool INeedArray) {
      if (INeedArray)
        this.list = new ArrayList<E>();
    }
}

A: public class MyList<T> {
    private List<T> list = new ArrayList<T>();
}

This is what I use in classes.. I have for a long initialized what I could when defining the private variable it self.


text:
Q: How to addClass to the first td in every tr inside a table using jQuery I'm trying to add a class to the first td inside a tr within a specific class.  But for some reason it adds this class only to the first td in the first tr -not the first td in each tr
$("#appendTD").find("#gridFormInformation").children(0).children().each(
                function() {
                    if ($("#appendTD").find('tr').filter(function() { return $(this).attr('class') == 'ui-widget-content ui-subtblcell'; }).children("td:eq(0)").addClass("leftbord"));
                }
            );

But when I alter the above by removing the ""td:eq(0)" it adds this class to each td in each tr ... so what am I doing wrong?
Example of the markup below

1	2	3

1	2	3

1	2	3

1	2	3

A: It looks to me like you're using a complicated manual way to find the tds you want to add the class to. I believe it would be easier to use jQuery selectors to find your tds.
Replace
$("#appendTD").find("#gridFormInformation").children(0).children().each(
            function() {
                if ($("#appendTD").find('tr').filter(function() { return $(this).attr('class') == 'ui-widget-content ui-subtblcell'; }).children("td:eq(0)").addClass("leftbord"));
            }
        );

with
$("#gridFormInformation tr.ui-widget-content.ui-subtblcell").find("td:first").addClass("leftbord");

This would find all the trs and for each tr find the first td and add the class to that.

A: Change 'td:eq(0) to 'td:first'.

A: This method is to add leftbord to the first  in each row of the table gridFormInformation:
$('#gridFormInformation tr td:first-child').addClass('leftbord');


text:
Q: Axios interceptors runs more than once I have this interceptors that logs the user out if unauthorized. I do, however, get more than a 401 response, and the interceptors does therefore run for as many times as the responses I get (4). Is there a way to make it run only for the first one?
This is my code:
api.interceptors.response.use(
(response) => response,
(err) => {
  if (err.response.status === 401 && isLoggedIn) {
    api
      .delete("auth/sign_out")
      .then((resp) => {
        clearLocalStorage();
      })
      .catch((err) => {
        clearLocalStorage();
      });
  } else {
    return Promise.reject(err);
  }
  return err;
}

);

A: You might want something like this to "lock out" the possible re-entrant calls:
let isLoggingOut = false; // global

// ...

api.interceptors.response.use(
  (response) => response,
  async (err) => {
    if (err.response.status === 401 && isLoggedIn) {
      if(!isLoggingOut) {
        isLoggingOut = true;  // disallow re-entrant calls
        try {
          await api.delete('auth/sign_out');
        } catch (deletionError) {
          // throw errors away
        } finally {
          clearLocalStorage();
          isLoggingOut = false;
          isLoggedIn = false; // if the variable is assignable
        }
      }
    }
    return err;
  },
);


text:
Q: Why %x and %o are treated as unsigned int? ram@ram:~/Desktop$ cc sample.c

sample.c: In function 'main':

sample.c:7: warning: format '%o' expects type 'unsigned int', but argument 2 has type 'long int'

A: Because they are specified as taking an unsigned int.
(No, really.)


text:
Q: Post soap envelope from bash script How would I post the following soap envelope via a bash script.
In PHP I would post using cURL but don't know how to translate into bash?
<?xml version="1.0" encoding="utf-8" ?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
  <env:Header>
    <n:Request xmlns:n="http://www.****.com/iprs/soap" env:role="http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver" env:mustUnderstand="true">UserMod</n:Request>
  </env:Header>
  <env:Body>
    <n:RequestUserMod xmlns:n="http://www.****.com/iprs/soap">
      <n:UserID>****</n:UserID>
      <n:UserData >
        <n:SystemName>****</n:SystemName>
        <n:AdminState>enabled</n:AdminState>
        <n:CategoryTypeID>****</n:CategoryTypeID>
        <n:Permissions>****</n:Permissions>
        <n:BillingProgID>****</n:BillingProgID>
        <n:DefaultGroupID>****</n:DefaultGroupID>
        <n:PrimarySiteID>****</n:PrimarySiteID>
        <n:SecondarySiteID>****</n:SecondarySiteID>
        <n:ContactInfo></n:ContactInfo>
        <n:Password>****</n:Password>
      </n:UserData>
    </n:RequestUserMod>
  </env:Body>
</env:Envelope>

If possible I would also like to detect the response, which should be:
HTTP/1.1 200 OK
Content-Type:application/soap+xml; charset="utf-8"
Content-Length:509

<?xml version="1.0" encoding="UTF-8"?><env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Header>
<n:Response xmlns:n="http://www.*****.com/iprs/soap" env:role="http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver" env:mustUnderstand="true">UserMod</n:Response>
</env:Header>
<env:Body>
<n:ResponseUserMod xmlns:n="http://www.*****.com/iprs/soap">
<n:StatusReport>
<n:Code>ok</n:Code>
<n:SubCode>0</n:SubCode>
</n:StatusReport>
</n:ResponseUserMod>
</env:Body>
</env:Envelope>

A: Perhaps like this?
curl --data - --request "POST" "http://www.somesite.com" <<EOF

<?xml version="1.0" encoding="utf-8" ?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
  <env:Header>
    <n:Request xmlns:n="http://www.****.com/iprs/soap" env:role="http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver" env:mustUnderstand="true">UserMod</n:Request>
  </env:Header>
  <env:Body>
    <n:RequestUserMod xmlns:n="http://www.****.com/iprs/soap">
      <n:UserID>****</n:UserID>
      <n:UserData >
        <n:SystemName>****</n:SystemName>
        <n:AdminState>enabled</n:AdminState>
        <n:CategoryTypeID>****</n:CategoryTypeID>
        <n:Permissions>****</n:Permissions>
        <n:BillingProgID>****</n:BillingProgID>
        <n:DefaultGroupID>****</n:DefaultGroupID>
        <n:PrimarySiteID>****</n:PrimarySiteID>
        <n:SecondarySiteID>****</n:SecondarySiteID>
        <n:ContactInfo></n:ContactInfo>
        <n:Password>****</n:Password>
      </n:UserData>
    </n:RequestUserMod>
  </env:Body>
</env:Envelope>

EOF

A: to post:
cat file | curl ...

but to retrieve the result, and act according to it, embed it all in a expect script.


text:
Q: How to generate popup(usercontrol or div) on click of hyperlink residing in usercontrol of aspx? Project is based on Nhibernate & spring framework with ext.net controls .
I have a usercontrol UCA.ascx which has a hyperlink on click of which I want to generate a popup to show details . So what can be done ? Any help is welcome

A: The target attribute allows you set the target window of the anchor.

A: you can write a function like this
       function openWindow() {
var URL = "/Test.aspx"
        window.open(URL);
        }

and call like this

A: For popup you can use AJAX modal popup extender.
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ModalPopup/ModalPopup.aspx

A: Have you tried using JqueryUI Dialogue Box.
dialogue
add required input box inside the div which is going to popup.

//show details here....

you can modify the div and add whatever controls you want inside it.


text:
Q: Can a Google Spreadsheet Apps Script library contain a user dialog? Are there restrictions on what may be in an Apps Script library to be used by Google Spreadsheets?  Specifically, can a library include an HTML dialog?
I've created a spreadsheet script that adds a menu item to present the user with a dialog box.  It uses
HtmlService.createHtmlOutputFromFile('mappingForm').setSandboxMode(HtmlService.SandboxMode.IFRAME)
as described in https://developers.google.com/apps-script/guides/html/communication.  The HTML file includes HTML, CSS and JavaScript with jQuery.  It uses google.script.run to populate the dialog with data from the spreadsheet and to submit a form to it.
This all works fine in the original spreadsheet.
I need multiple spreadsheets to use this same code, however, so I'm trying to follow the general idea of Google Spreadsheet Scripts shared across spreadsheets (not libraries) to have a master script with a spreadsheet template and multiple copies.
I followed the directions at https://developers.google.com/apps-script/guide_libraries to create a library from the original spreadsheet.  When another spreadsheet uses the library, I'm able to get the dialog to appear, but all calls back to the server (either to populate the dialog or to submit a form) fail with an error caught browser-side by the google.script.run.withFailureHandler as an Error object with properties:
message: "We're sorry, a server error occurred. Please wait a bit and try again."
name: "ScriptError"

I've placed Logger calls in the apps script to see if the server-side functions are being called but none of them are being hit.  The script editor's Execution Transcript shows:

[14-12-27 19:38:05:340 PST] Starting execution
[14-12-27 19:38:05:372 PST] Execution failed: We're sorry, a server error occurred. Please wait a bit and try again. [0.0 seconds total runtime]

The client is making the call, but something is failing before it reaches the spreadsheet script.
This makes me wonder whether

*

*I need to do something differently for the code to work as a library.

*Libraries can't have dialogs.

*There's a server bug.

Thanks in advance for any suggestions.

A: I was able to have a working library containing an HTML dialog by doing the following.

*

*Move the script and HTML files from the original spreadsheet to a standalone script project.  Take note of the library's Project key in the Info tab of File > Project properties....  It will be needed by any spreadsheet that intends to use the library.

*If the standalone script project is to used by others, click its Share button to make it shareable to anyone with a link, otherwise it will silently fail for them.

*If the HTML dialog needs to call back to a library function (to get or submit data), the library function must be present in the spreadsheet that uses the library, or you'll get an error message in the browser's JavaScript console.

*In the spreadsheet that uses the library: Tools > Script editor...  Click Resources > Libraries....  In the "Included Libraries" dialog box, enter the standalone project's key in the Find a Library text box, click Select, then choose the appropriate Version, change the Identifier, if necessary, and Save.  The Identifier value creates an object of the same name for use by the spreadsheet's script to call library functions.  In my case, it is SignupFormResponsesSheet.

*In the same Script Editor's code editor, add wrapper functions that call library functions, including any that will be called back from the HTML dialog.  My library has an onOpen() which creates two menu items to show HTML dialogs, so I added

function onOpen() {
    SignupFormResponsesSheet.onOpen();
}

function showMappingForm() {
    SignupFormResponsesSheet.showMappingForm();
}

function showSubmitForm() {
    SignupFormResponsesSheet.showSubmitForm();
}

*My HTML dialog has a number of callbacks to get and submit data, so rather than writing a wrapper function for each, I added one function to cover all of them by taking advantage of the way Apps Script treats a library as an object containing functions.  The first argument is a string naming the library function to call.  Any additional arguments are passed to the library function.

function runSignupFormResponseFunction(funcName, varargs) {
  return SignupFormResponsesSheet[funcName].apply(this,
    Array.prototype.slice.call(arguments, 1));
}

*Because of the restriction identified in step 3 above, the JavaScript in the HTML dialog uses google.script.run to call the runSignupFormResponseFunction whenever it needs to get or submit data.  For example, it has two lists that are dynamically populated with server data from the library's getRangeLabels and getColumnExamples functions (and one must be populated before the other), so the code is

google.script.run
  .withFailureHandler(showError)
  .withSuccessHandler(function(ranges) {
    loadRanges(ranges);
    // once ranges are loaded, load columns
    google.script.run
      .withSuccessHandler(loadColumns)
      .withFailureHandler(showError)
      .runSignupFormResponseFunction("getColumnExamples");
  })
  .runSignupFormResponseFunction("getRangeLabels");

This worked for me today.  I hope it works for others who may find this question.


text:
Q: How to search a binary file for a signature offset This is my example so far:
import io
import mmap
import os
import time

# 20 MB test file
filename = "random.bin"
if not os.path.isfile(filename):
    with open(filename, "wb") as f:
        for _ in range(20):
            f.write(os.urandom(1_000_000))

signature = b"\x01\x02\x03\x04"

print("Method 1:")
start_time = time.time()
offsets = []
with open(filename, "rb") as f:
    buf = b"\x00" + f.read(len(signature) - 1)
    for offset, byte in enumerate(iter(lambda: f.read(1), b"")):
        buf = buf[1:] + byte
        if buf == signature:
            offsets.append(offset)
print(f"{time.time() - start_time:.2f} seconds")
print(offsets)

print("Method 2:")
start_time = time.time()
offsets = []
with open(filename, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
    for offset in range(len(mm)):
        if mm[offset : offset + len(signature)] == signature:
            offsets.append(offset)
print(f"{time.time() - start_time:.2f} seconds")
print(offsets)

print("Method 3:")
start_time = time.time()
offsets = []
with open(filename, "rb") as f:
    offset = 0
    chunk = f.read(len(signature) - 1)
    while True:
        chunk = chunk[-(len(signature) - 1) :] + f.read1(io.DEFAULT_BUFFER_SIZE)
        if len(chunk) < len(signature):
            # EOF
            break
        for i in range(len(chunk) - (len(signature) - 1)):
            if chunk[i : i + len(signature)] == signature:
                offsets.append(offset + i)
        offset += len(chunk) - (len(signature) - 1)
print(f"{time.time() - start_time:.2f} seconds")
print(offsets)

I'm searching through a 20 MB test file, looking for signature of 4 bytes. Switching to method 2 with mmap.mmap saved 50% of runtime, but it's still really slow. Especially since my actual target file will be between 1 and 10 GB. (Which is why I don't just load the whole file into memory, first.) It is orders of magnitude slower than md5sum random.bin.
Edit: I've added another method, which doesn't use f.read(1), but reads chunks of io.DEFAULT_BUFFER_SIZE and also uses read1 to prevent any blocking. But it's still not faster.

A: Reading the file wasn't the issue. Using chunks instead of read(1) should definitely be fast enough. However, afterwards, it's apparently a bad idea to iterate the bytes with slicing. bytes.find is much faster. I don't yet understand why, but I've posted a new question How is str.find so fast? about that.
Here is a simple solution - a 4th method for the example code from above - which uses bytes.find:
print("Method 4:")
start_time = time.time()
offsets = []
def _find(haystack, needle, start=0, offset=0):
    while True:
        position = haystack.find(needle, start)
        if position < 0:
            return
        start = position + 1
        yield position + offset
with open(filename, "rb") as f:
    offset = 0
    chunk = f.read(len(signature) - 1)
    while True:
        chunk = chunk[-(len(signature) - 1) :] + f.read1(io.DEFAULT_BUFFER_SIZE)
        if len(chunk) < len(signature):
            # EOF
            break
        offsets.extend(_find(chunk, signature, offset=offset))
        offset += len(chunk) - (len(signature) - 1)
print(f"{time.time() - start_time:.2f} seconds")
print(offsets)

It produces the following time measurements:
Method 1:
8.83 seconds
[20971596, 20971686]
Method 2:
5.69 seconds
[20971596, 20971686]
Method 3:
5.76 seconds
[20971596, 20971686]
Method 4:
0.02 seconds
[20971596, 20971686]

So yeah, method 4 is clearly the winner.


text:
Q: Getting errors when switching screen to RootViewController I'm hopeless at the moment, I need some help here.
So from the beginning:
I've made a view based app which I want to use as the main app. And I have build another app which is a navigation based one.
I combined the two projects into one, I dragged and dropped the navigation one in de first app I've made. I added the header file to the .m file of the view based one. So far so good. But when I add this code:
-(IBAction)search
{
  RootViewController *search = [[RootViewController alloc] initWithNibName:nil bundle:nil];
  search.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  [self presentModalViewController:search animated:YES];
}

Then I'll get two errors which is:
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_RootViewController", referenced from:
      objc-class-ref in Home.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
So what I'm trying to do here is when I click on a button in the main app the screen needs to go to the main one from the other app.
I tried changing the RootViewController into UINavigationController and that worked, but it's not the fullscreen of course. I need to show the RootView Controller.
Can someone help me? Or if you need more info please let me know!
iPhone 4S, Mac OS X (10.7.3), XCODE

A: You need to add RootViewController.m to the project that's complaining. The RootViewController.h by itself will not work.


text:
Q: Why the BAT file launched from JMeter OS Sampler is not triggering the Maven execution? Summary:- I need lots of dynamic data for my performance testing and it's not possible to generate those test data from Jmeter itself. Hence, I wrote a Java code which will generate these dynamic test data and will put those data into the excel file. This excel file can be consumed by JMeter script for the performance testing. Every iteration in JMeter needs a new set of test data and that's why I have created a bat file which will trigger the Maven execution(it's just mvn clean test) and will generate the fresh set of test data before each of iteration. Everything is working fine till this point. I just need to run the bat file from JMeter to trigger the test data creation before each iteration and that's the problem which I am facing
Problem:- As mentioned in the link How to run batch file(.bat) from Jmeter and as suggested by user @Dmitry T, I have added the OS sampler with the given parameters(See the screenshot below) but it is not starting the Maven execution. It is hitting the bat file(I put some msg command to check) but somehow it is not starting the execution. I tried the other solution given by the same user about using the Beanshell Sampler and running the command
 Runtime.getRuntime().exec("C:/Windows/System32/cmd.exe /c D:/XXXX/XXX/XXXX/GenerateTestData.bat");

This is also not working. Am I missing something here? Please let me know if there is any solution for this? Appreciate any help on this?

A: *

*In the Command input provide full path to the cmd.exe

*Change the Working directory to where your batch file lives

*Use just batch file name in the Command Parameters
Something like:

See How to Run External Commands and Programs Locally and Remotely from JMeter article for more details.
Alternatively you can use Maven Exec Plugin to run your custom command before running the JMeter test

A: The batch file is most likely not designed to work properly with current directory on execution being different to the directory containing the batch file. The current directory can be any directory. Very common are the directories %SystemRoot% (Windows directory) and %SystemRoot%\System32 or %SystemRoot%\SysWOW64 (Windows system directory) as current directory, whereby any directory can be the current directory on running a batch file.
A batch file referencing other files or directories relative to the batch file directory should set the current directory to the batch file directory or reference all directories and files with full batch file path.
The argument 0 of a batch file is always the batch file itself. The help output on running in command prompt window call /? explains how to reference an argument with a modifier. In this case %~dp0 should be used to get full path of the batch file.
So in the batch file can be used at top:
@echo off
cd /D "%~dp0"

The current directory is set with second command line to the directory containing the batch file as long as the batch file is stored on a drive with a drive letter.
There is another method to make the directory of the batch file the current directory which works even with batch file being stored on a network resource and the batch file is executed using its UNC path.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0" || exit /B

rem Other commands accessing files and directories in batch file directory
rem using no path or a path relative to current working directory.

popd
endlocal

The help output on running in a command prompt window pushd /? describes why this code works even with a UNC path on command extensions enabled which is made sure by the second command line which defines together with first command line completely the execution environment for the batch file without depending on configurations outside of the batch file.
Another solution is referencing all files and directories in batch file directory with full path which means with using %~dp0, for example "%~dp0ExcelFile.xlsx".
Note: The path string referenced with %~dp0 always ends with a backslash which is the directory separator on Windows as explained by Microsoft documentation about Naming Files, Paths, and Namespaces. Therefore concatenation of %~dp0 with another string like file/folder name or wildcard pattern should be done always without using an additional backslash for a 100% correct full file/folder/pattern argument string.


text:
Q: Adding all Time values in a column I have the following data
    Shift_Working_Hours
    --------------------
    03:45
    09:00
    08:45
    07:50

I want to add up all the values in the Shift_Working_Hours column and I want the result as 28:40.
Please guide me how can i do it using SQL.
I am using TOAD.

A: -- If it String Column

  Select convert(varchar,sum(convert(int,parsename(replace(WH,':',''),2)
    +(sum(convert(int,parsename(replace(WH,':',''),1)/60))+':'
    +convert(varchar,(sum(convert(int,parsename(replace(WH,':',''),2)%60))
    from table

    -- If it is a datecolumn
Select convert(varchar,SUM(DATEPART(hh,Wh))+
SUM(DATEPART(mm,WH))/60)+':'+
convert(varchar,SUM(DATEPART(mm,WH))%60)


text:
Q: how to convert asp.net website project to sharepoint wsp I have created a Visual studio 2012 asp.net project on my local machine and now want to use in other sharepoint site.
How to convert my asp.net project to wsp file and to deploy to sharepoint environment.

A: You cannot automatically convert asp.net project to wsp file!
You need to adjust and change your asp.net code manually so it can be deployed to SharePoint and there is a lot to consider depending on your asp.net Projects functionality and structure - wsp (full trust code with c#) vs add-in (clientside code with JavaScript and REST).
Start here at MSDN: SharePoint general development
If you use the new SharePoint Framework (SPFx) to develop your client-side webparts, then you don't need a Visual Studio installed on a SharePoint server. You don't even need a SharePoint server.
Using SPFx you can develop in Notepad or any other code editor.
Note that SPFx is currently (Dec 13 2016) in preview.
Start here at Office Dev Center: Overview of SharePoint Framework (SPFx)


text:
Q: SQL match first part of string and compare I use Oracle and MySql, so if you have any answer in both codes please let me know,
Issue:
I have 2 columns in one table called: USers
Column#1= Names
Column#2= UCNames
This list contain names that are from different sources but partially match like:
Names

Alex Jones Marfex
UCNames

Alex Jonnes Mike Marfex
I want to compare both of the columns and find match based on the following attributes:
Search on the first 4 for letters and 4 last words and to store in new column called: verifiyed
Thanks

A: This gives you the first word in a string
Substring(Col,1,(Locate (' ',Col + ' ')-1)) First

This gives you the last word in a string
Reverse(Substring(Reverse(Col), 1,  Locate(' ',Reverse(Col)) - 1)) Last

So your compare could be
Where
    Substring(Col1,1,( Locate(' ',Col1 + ' ')-1))
    = Substring(Col2,1,( Locate(' ',Col2 + ' ')-1))
  And
    Reverse(Substring(Reverse(Col1), 1,  Locate(' ',Reverse(Col1)) - 1))
    = Reverse(Substring(Reverse(Col2), 1,  Locate(' ',Reverse(Col2)) - 1))

I went with words which seemed safer for what you are trying to do with just a bit more effort. If you do want to keep the 4 characters, just replace the  Locate es with 4.

A: Based on the answer by @asantaballa , but using MySQL SUBSTRING_INDEX function :-
WHERE SUBSTRING_INDEX(Col1, ' ', 1) = SUBSTRING_INDEX(Col2, ' ', 1)
AND SUBSTRING_INDEX(Col1, ' ', -1) = SUBSTRING_INDEX(Col2, ' ', -1)

or to crudely check the first 4 characters and the last 4 words:-
WHERE SUBSTRING(Col1, 1, 4) = SUBSTRING(Col2, 1, 4)
AND SUBSTRING_INDEX(Col1, ' ', -4) = SUBSTRING_INDEX(Col2, ' ', -4)


text:
Q: Tensorflow.js : TypeError : backend.select is not a function I am making a color classifier using tensorflow.js. The methodology of training is to show a color in the canvas and there are 10 buttons which has 10 colors associated with and the user needs to click any one of the button to select the color. Taking the input from the buttons,normalizing the colors and applying tf.oneHot, the tensors look like this. rgb color and the label
Tensor
     [[0.772549, 0.3568628, 0.9098039],]
Tensor
     [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],]

Then we take the colors and train the model. Every time the user clicks the button, model gets trained and gets better. This is my model configuration
const model = tf.sequential();

const hidden = tf.layers.dense({
    units: 16,
    inputShape: [3],
    activation: "relu"
});
model.add(hidden);
const output = tf.layers.dense({
    units: 10,
    activation: "softmax"
});
model.add(output);

const optimizer = tf.train.sgd(0.25);
model.compile({
    optimizer: optimizer,
    loss: "categoricalCrossentropy",
    metrics: ["accuracy"]
});

Now i'm getting an error called TypeError: backend.select is not a function It would be nice if someone tells me what this error actually means.

A: This seems to be a problem in tfjs-node version 0.1.9 according to this GitHub issue.
A quick npm update updated it to 0.1.10, which seems to have solved the problem!


text:
Q: How to sort a string list alphabetically in Dart language? I have 4 companies and each company has more than 10 branches.
If a user chooses a company, I need to show the selected company branch using showDialog. Till here everything work as expected. My problem is that I cannot sort List<String> alphabetically.
Any idea how to sort string list (List) alphabetically in Dart?
List<String> _myBranchListName;

A: *

*Flutter is an application development SDK

*Dart is a general-purpose programming language

*Flutter application is written in Dart

*so:

How to sort A to Z in Flutter List< String > ?

*Will be

How to sort A to Z in Dart List< String > ?

*A to Z : is called alphabetically so :

How to sort alphabetically in Dart List< String > ?

*List< String > : is a list of type string
so

How to sort alphabetically in Dart String List?

*more

How to sort a string list alphabetically in Dart language?

Code:
main() {
  List<String> _myBranchListName= ['k branch', 'a branch', 'f branch'];

  _myBranchListName.sort();
  print(_myBranchListName);

  //[a branch, f branch, k branch]
}

update

I have a custom list with menas list contain class produt and product contain varable title and now i need to short my list based on title how to do it'''

*

*base on sort method - List class - dart:core library - Dart API

sort method:
Sorts this list according to the order specified by the compare function.
The default List implementations use Comparable.compare if compare is omitted.
A Comparator may compare objects as equal (return zero),
even if they are distinct objects. The sort function is
not guaranteed to be stable, so distinct objects that
compare as equal may occur in any order in the result

*

*your code (Waring: i did not test this code i need your feedback):

produts.sort((a, b) => a.title.compareTo(b.title));

A: List Contains method called sort, that function will sort the list in alphabetical order (from a to z).
I created function for you to make the process more clear:
List<String> sort(List<String> _myBranchListName){    // This function take List of strings and return it organized alphabetically
 // List<String> _myBranchListName = ["B branch", "C branch" , "A branch"]; // example of input
  print(_myBranchListName);   // will show the result in the run log
  _myBranchListName.sort();
  print(_myBranchListName);   // will show the result in the run log
  return _myBranchListName;
}

Technically you only need _myBranchListName.sort() to sort the array.


text:
Q: Error: "Firebase Storage: User does not have permission to access..." I'm trying to write a Firebase Cloud Function to get an audio file from an API and save it to Firebase Storage. I'm getting this error:
Firebase Storage: User does not have permission to access 'Audio/English/United_States-OED-0/winter.mp3'. (storage/unauthorized)

I'm getting the same error using the emulator and the cloud. No file is written in Storage. The log Uploaded a string!' doesn't appear.
I have a Firebase IAM service account. I know how to import it into a CommonJS module (require) but my functions are in an ES module (import). How do I import my service account? This didn't work because assert only works in Node 17, when Firebase Functions uses Node 16.
import serviceAccount from "./my-awesome-project-firebase-adminsdk-12345.json" assert { type: "json" };

Here's my cloud function:
import { initializeApp } from "firebase/app";
import * as functions from "firebase-functions";
import { getStorage, ref, uploadString, connectStorageEmulator } from "firebase/storage";

const firebaseConfig = {
    apiKey: ...,
    authDomain: ...,
    databaseURL: ...,
    projectId: ...,
    storageBucket: "my-awesome-project.appspot.com",
    appId: "..."
};

const app = initializeApp(firebaseConfig);

import got from 'got';

export const Oxford_T2S = functions.firestore.document('Users/{userID}/English/OED_T2S_Request').onUpdate((change, context) => {
  const storage = getStorage(app);
  connectStorageEmulator(storage, "localhost", 9199); // comment out to use cloud
  const audioEnglishOEDWinterRef = ref(storage, 'Audio/English/United_States-OED-0/winter.mp3');

  async function getOED() {
    try {
      let file = await got('https://audio.oxforddictionaries.com/en/mp3/winter__us_2.mp3');
      uploadString(audioEnglishOEDWinterRef, file).then((snapshot) => {
          console.log('Uploaded a string!');
      });
    } catch (error) {
        console.error(error);
    }
  }

  return getOED()
});

Here are my cloud rules:
service firebase.storage {
  match /b/{bucket}/o {
    // anything using request.auth.token relies on the userLogin cloud function.

    match /Audio/{shortLangA}/{file=**} {
        // allow writing of audio files if the user is trusted or a teacher of the language, apply recursively
        allow write: if (request.auth.token.trusted || shortLangA in request.auth.token.teaches);
    }

     match /Users/{file=**} {
        // allow writing of pronunciation tests
        // this rule is insecure
      // this rule needs to be improved by allowing users to only write to their own folders
      allow read, write: if true;
    }

    match /{allPaths=**} {
      // Only authenticated users can read from the bucket
      allow read: if request.auth != null;
    }
  }
}

I tried spinning up my Angular project and logging in but that didn't help.
Here are my emulator rules. These are the default rules created by firebase init functions:
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
  }
}

I changed false to true but that didn't help.
Documentation on got is here. That line isn't throwing errors.

A: The Cloud Storage error messages documentation says
storage/unauthorized
User is not authorized to perform the desired action, check your security rules to ensure they are correct.

Looking at the emulator's default storage.rules, nothing can read or write. Gee, thanks for protecting my emulator from Russian hackers. The default should be
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write
    }
  }
}

Even with the new rules the emulator seems to be finicky. Sometimes a file writes, most of the time nothing writes to Storage.
My Cloud Storage rules, particularly request.auth.token.trusted, are set up for calls from my Angular app. If the call isn't coming from a logged in user on the app then the request is stopped. I.e., testing the Cloud Function in the Firebase Console won't write to Storage.


text:
Q: Editing the column of an objectdatasource before databind Currently I'm using a gridview with an objectdatasource to display a table of product info. I also have a drop down list to switch the view between Imperial and Metric units. To switch between the two, every time someone changes the drop down list selection, I am deleting the old units column and inserting a new column based on the selection, as follows:
if (GridView1.Columns.Count > 7)
     JobListGridView.Columns.Remove(GridView1.Columns[7]);

BoundField colIndex8 = new BoundField();
colIndex8.HeaderText = "Units";

if (UnitsDropDown.Text == "Imperial")
{
     colIndex8.DataField = "IUnits";
     colIndex8.SortExpression = "IUnits";
     GridView1.Columns.Add(colIndex8);
}
else
{
     colIndex8.DataField = "MUnits";
     colIndex8.SortExpression = "MUnits";
     GridView1.Columns.Add(colIndex8);
}
GridView1.DataBind();

This works to change the units being displayed in the units column (e.g. from "mm" to "ft"). However, I also need to change the value of another column that displays length. Is it possible to somehow edit the values in the length column (say multiply by a constant) and then databinding the modified column to the gridview without having to create a new column in the database table to store this information?
I am imagining something like:
DataColumn dc = GridView1.Columns[4];
foreach (cell c in dc)
{
    c *= 0.5;
}
GridView1.Columns.Add(dc);
GridView1.DataBind();

As simple pseudo-code, but is this the right approach/is this possible?
Thanks

A: Don't add and remove columns. Just hide the column you don't want to see:
<asp:BoundField DataField="IUnits" Visible="<%# UnitsDropDown.Text == "Imperial" %>" />
<asp:BoundField DataField="MUnits" Visible="<%# UnitsDropDown.Text != "Imperial" %>" />

As for your second question, use a TemplateField:
<asp:TemplateField HeaderText="foo">
    <ItemTemplate>
        <asp:Label runat="server" Text='<%# ((int)Eval("foo")) * (UnitsDropDown.Text == "Imperial" ? 0.5 : 1) %>' />
    </ItemTemplate>
</asp:TemplateField>


text:
Q: React Warning: Cannot update during an existing state transition (such as within `render`) I've ResetPassword component which renders Timer component, below are their code -
ResendPassword.js
class ResetPassword extends Component{
    constructor(props){
        super(props);
        this.state = {
            resendActive: false
        };
    }

    endHandler(){
        this.setState({
            resendActive: true
        })
    }

    render(){
        return (
            <Timer sec={5} counter={this.state.counter} end={this.endHandler.bind(this)}/>
        )
    }
}

Timer.js
const Timer = (props) => {
    const [sec, setSec] = useState(props.sec);

    useEffect(() => {
        setSec(props.sec);
        const intr = setInterval(() => {
            setSec((s) => {
                if(s > 0)
                    return --s;
                props.end(); // Line: causing warning
                clearInterval(intr);
                return s;
            });
        }, 1000)

        return () => {
            clearInterval(intr);
        }
    }, [props.counter])

    return (
        {sec > 60 ? `${Math.floor(sec/60)}:${sec - Math.floor(sec/60)}`: `${sec}`} sec
    )
}

In Above code I'm using timer in ResetPassword and I want a function call when timer ends so I'm passing endHandler as end in Timer component but calling that function giving - Warning: Cannot update during an existing state transition (such as within 'render'), can anyone let me know what I'm doing wrong here?
Thanks In Advance

A: Issue
setSec is a state update function and you use the functional state update variant. This update function callback is necessarily required to be a pure function, i.e. with zero side-effects. The invocation of props.end() is a side-effect.
Solution
Split out the side-effect invocation of props.end into its own effect hook so that it is independent of the state updater function.
const Timer = (props) => {
  const [sec, setSec] = useState(props.sec);

  useEffect(() => {
    setSec(props.sec);
    const intr = setInterval(() => {
      setSec((s) => {
        if (s > 0) return --s;
        clearInterval(intr);
        return s;
      });
    }, 1000);

    return () => {
      clearInterval(intr);
    };
  }, [props.counter]);

  useEffect(() => {
    console.log(sec);
    if (sec <= 0) props.end(); // <-- move invoking `end` to own effect
  }, [sec]);

  return (

      {sec > 60
        ? `${Math.floor(sec / 60)}:${sec - Math.floor(sec / 60)}`
        : `${sec}`}{" "}
      sec

  );
};

Suggestion
Create a useInterval hook
const useInterval = (callback, delay) => {
  const savedCallback = useRef(null);

  useEffect(() => {
    savedCallback.current = callback;
  });

  useEffect(() => {
    const id = setInterval(savedCallback.current, delay);
    return () => clearInterval(id);
  }, [delay]);
};

Update Timer to use interval hook
const Timer = ({ end, sec: secProp}) => {
  const [sec, setSec] = useState(secProp);

  // Only decrement sec if sec !== 0
  useInterval(() => setSec((s) => s - (s ? 1 : 0)), 1000);

  useEffect(() => {
    !sec && end(); // sec === 0, end!
  }, [sec, end]);

  return (

      {sec > 60
        ? `${Math.floor(sec / 60)}:${sec - Math.floor(sec / 60)}`
        : `${sec}`}{" "}
      sec

  );
};


text:
Q: Proving that a combinatorial expression is an integer without combinatorics The number of ways to tile an $m \times n$ rectangle with dominos is $$S_{m,n} = \prod_{j=1}^{\lceil \frac{m}{2} \rceil} \prod_{k=1}^{\lceil \frac{n}{2} \rceil}\left( 4 \cos^2 \frac{\pi j}{m+1} + 4 \cos^2 \frac{\pi k}{n+1} \right) $$
How can we prove that this expression is an integer without appeal to its combinatorial interpretation? It's been suggested to me that since the expression above is an algebraic integer, it suffices to show that it is rational using Galois theory, but I am not familiar enough with Galois theory to produce such an argument.
Edit: Following the hint below, using $\cos(\theta) = \frac{e^{i\theta} + e^{-i\theta}}{2}$, we have that $\cos^2(\theta) = \frac{e^{2i\theta}  + e^{-2i\theta} + 2}{4}$ with which we can rewrite $$S_{m,n} = \prod_{j=1}^{\lceil \frac{m}{2} \rceil}\prod_{k=1}^{\lceil \frac{n}{2} \rceil} \left(e^{\frac{2\pi i j}{m+1}} + e^{-\frac{2\pi i j}{m+1}}  + e^{\frac{2 \pi i k}{n+1}} + e^{-\frac{2 \pi i k}{n+1}} +4 \right) =\prod_{j=1}^{\lceil \frac{m}{2} \rceil}\prod_{k=1}^{\lceil \frac{n}{2} \rceil} \left(\zeta_{m+1}^j + \zeta_{m+1}^{-j} + \zeta_{n+1}^k + \zeta_{n+1}^{-k} +4 \right) $$
Clearly, $S_{m,n} \in \mathbb{Q}[\zeta_{m+1},\zeta_{n+1}]$ where $\zeta_k = e^\frac{2\pi i }{k}$.
Then $\Gamma(\mathbb{Q}[\zeta_{m+1},\zeta_{n+1}]/\mathbb{Q}) \subseteq (\mathbb{Z}/m \mathbb{Z})^\times \times (\mathbb{Z}/n \mathbb{Z})^\times$ generated by the automorphisms $\zeta_{m+1} \mapsto \zeta_{m+1}^a$ for $1 \leq a < m+1$ relatively prime to $m+1$ and $\zeta_{n+1} \mapsto \zeta_{n+1}^b$ for $1 \leq b < n+1$ relatively prime to $n+1$. From here, I don't know how to show that $S_{m,n}$ is invariant under this action, as (for example) $\zeta_{m+1}^{\lceil \frac{m}{2} \rceil -1} \mapsto \left(\zeta_{m+1}^{\lceil \frac{m}{2} \rceil -1}\right)^2$ gives rise to a term outside the index of the product.
We can rewrite $$S_{m,n} = 2\prod_{j=1}^m \prod_{k=1}^n \left(\cos \frac{\pi j}{m+1} + i \cos \frac{\pi k}{n+1} \right) $$ using the properties of the cosine. We further expand this as above: $$S_{m,n} = \prod_{j=1}^m \prod_{k=1}^n \left(e^{i\frac{\pi j}{m+1}} + e^{-i\frac{\pi j}{m+1}} + e^{i\frac{\pi k}{n+1}} + e^{-i\frac{\pi k}{n+1}} \right)  = \prod_{j=1}^m \prod_{k=1}^n (\zeta_{2m+2}^j + \zeta_{2m+2}^{-j} + \zeta_{2n+2}^k + \zeta_{2n+2}^{-k})$$ but we have the same problem here as above, there are too many automorphisms.


text:
Q: Looking for the title of a Lovecraftian story about faces getting torn off In the sixties I remember reading a story where a group of men are searching for an unknown, unseen monster who was killing people and destroying property. At one point, the men barricade themselves in a cabin/house while two men are looking out windows keeping watch. In the morning the watchers are still at the windows but it's discovered their faces have been ripped off.
For 45 years I've thought the story was The Dunwich Horror by H. P. Lovecraft. Today I discovered that it's not. I'm trying to decide if this scene is from a different story, Lovecraft or other author, or if it's an invented memory. Any ideas?

A: The story you are describing sounds like "The Lurking Fear".
See this part of the plot summary:

II. A Passer In The Storm
Traumatized by the disappearance of his friends, and by the disturbing shadow he saw in the fireplace, the narrator continues the investigation. He befriends another reporter named Arthur Monroe, and tells him of the things he has experienced so far. Munroe agrees to help him, and the two scour the countryside for any clues to the murderous creature and any remains of the Martenses. There is no trace of the evil family, but they manage to uncover an ancestral diary that had once belonged to them. All the while, the narrator has the constant feeling of being watched. However, they are trapped by yet another thunderstorm, and seek shelter in an abandoned cabin, where the narrator thinks back of the horrible events back at the mansion. As an unusually large thunderbolt clashes across the sky, Munroe walks over to the window to survey the damage, and the storm soon clears up. However, Munroe doesnt move from the window, and when the narrator tries to rouse him, he finds him dead, with his face hideously mutilated by some unseen horror outside.


text:
Q: Why does downloading bash script from pastebin not work? I'm trying to upload and download a bash script from pastebin, upload was straightforward enough with copy and paste, download didn't go as easy.
There are two scripts I'm trying to download, these are the commands:
wget http://pastebin.com/raw.php?i=M6iQ6RaY --output-document=ts3update
wget http://pastebin.com/raw/e11R2wkP --output-document=ts3restore

When I try to run them, I get  this error:
./ts3update: /bin/bash^M: bad interpreter: No such file or directory

Then if I remove the interpreter line, I just get this:
./ts3update: line 4: $'\r': command not found

And this:
./ts3restore: line 3: $'\r': command not found
./ts3restore: line 7: syntax error near unexpected token `$'in\r''
'/ts3restore: line 7: `        case $yn in

Why does this happen, and how can I fix it? When I read or grep the files I find no instances of ^M or '\r' why does bash see something like that when nothing else does?

A: The answer as Michael Homer pointed out is that pastebin has added Windows CRLF line endings to my files. To fix it I ran the following:
sed -i 's/\r$//' ts3update
sed -i 's/\r$//' ts3restore

And the scripts executed successfully. The answer was taken from here: Bash/Korn shell script edited on Windows throws error '...^M: not found'


text:
Q: openssl version gives multiple results I have installed the latest openssl version from source to /usr/local/stow/openssl-1.0.2d and managed with stow to have it available in /usr/local. This works fine
# /usr/local/bin/openssl version
OpenSSL 1.0.2d 9 Jul 2015

However, when I don't give the absolute path to the executable, I get a different output:
# which openssl
/usr/local/bin/openssl
# openssl version
openssl: /usr/local/lib/libssl.so.1.0.0: no version information available (required by openssl)
openssl: /usr/local/lib/libssl.so.1.0.0: no version information available (required by openssl)
openssl: /usr/local/lib/libcrypto.so.1.0.0: no version information available (required by openssl)
openssl: /usr/local/lib/libcrypto.so.1.0.0: no version information available (required by openssl)
OpenSSL 1.0.1e 11 Feb 2013 (Library: OpenSSL 1.0.2d 9 Jul 2015)

which is the exact same output as when I call /usr/bin/openssl version, the packages version on that OS.
However, when I set the PATH to use the binary under the stow directory directly, I get the same output as with the absolute path.
Anyone capable of explaining what goes on here?


text:
Q: What exactly happens when you get a "Trick" after clicking the pumpkin? When you click the pumpkin that wanders over your screen fast enough, you will eventually get a treat or a trick. Treats are obvious, but what exactly happens if you get tricked?
I am unable to see any consequence.

A:
There is no consequence or any action whatsoever. The only punishment is that you don't get the treat.

That pretty much sums it up. The wiki says:

There was a chance of a pumpkin appearing on the screen. Clicking on this until it disappeared makes it give a "trick" or "treat". The treat is a random skill that is immediately activated, even if it hadn't been bought yet or was on cool down. (It does not affect the current status of that skill.) This can even activate The Dark Ritual. Trick appears to do nothing.

Source


text:
Q: TessBaseAPI() error i am doing a project on ocr using tesseract in python on a raspberry pi 3 device
installed tesseract via pip and sucessfully imported tesseract
import tesseract
api = tesseract.TessBaseAPI()

i am getting this error
Traceback (most recent call last):
File "/home/pi/ff.py", line 53, in <module>
api = tesseract.TessBaseAPI()
AttributeError: 'module' object has no attribute 'TessBaseAPI'

some one please give a solution for this

A: The package you're looking for is Tesserocr, that is a Tesseract Python wrapper. You have to install tesseract in your system, then you can install Tesserocr with
pip install tesserocr

To use the package tesserocr write
import tesserocr

api = tesserocr.PyTessBaseAPI()


text:
Q: screen goes blank when loading ubuntu 12.04 LTS for the 1st time I installed ubuntu 12.04 LTS along Win 7(Win 7 in C:\ and ubuntu in D:). After I select ubuntu from Win 7 boot loader, a screen which contains some lines that goes off within a second to the next screen where a cursor blinks. All I can notice from this flashing screen is "NTFS" and after this the screen just goes black.
Note: Before installing ubuntu, I partitioned my C:\ into D:\ with NTFS file system and I'm using alienware 14

A: *

*Some nVidia graphics solutions do not work out of box with Ubuntu.
[b]Workaround:[/b] https://help.ubuntu.com/community/BinaryDriverHowto/Nvidia

*The greeter is malfunctioning.
When using lightdm, sometimes I have to restart because there's nothing on screen but it clearly booted.
[b]Workaround:[/b] Restart until it works.

*Another monitor is plugged in.
Do you have a TV, or did you have another monitor plugged in? Unless I explicitly go to Settings, and disable other monitors, sometimes I get a black screen at start up.
[b]Workaround:[/b] Unplug the other monitor(s) and restart. If there's a display toggle try that.


text:
Q: How to use 'Where Not In' in Laravel 5.4? I'm trying to create a query where I get data from a table and I use INNER JOIN and Where Not In, I was able to adapt the INNER JOIN part, but in 'WHERE NOT IN' I tried using 'WhereNotIn' from Laravel 5.4. But it returns the error: Invalid argument supplied for foreach()
SELECT
        em.erp_mlbid AS category_id

            FROM
                erp_product AS ep
            INNER JOIN
                erp_product_category AS epc ON epc.erp_productid = ep.erp_productid
            INNER JOIN
                erp_mlbcategory_erpcategory AS emc ON emc.erp_categoryid = epc.erp_categoryid
            INNER JOIN
                erp_mlb_category AS em ON em.erp_mcid = emc.erp_mlbcategoryid
            WHERE
                ep.erp_productid NOT IN (
                        SELECT
                            epm.erp_productid
                        FROM
                            erp_product_to_mlb AS epm
                )
                AND ep.erp_quantity > 0
                AND ep.erp_status > 0
            LIMIT
                    10,10

So I created this in my application:
$categoria = DB::table('erp_product')
                            ->join('erp_product_category','erp_product_category.erp_productid', '=', 'erp_product.erp_productid')
                            ->join('erp_mlbcategory_erpcategory', 'erp_mlbcategory_erpcategory.erp_categoryid', '=','erp_product_category.erp_categoryid')
                            ->join('erp_mlb_category', 'erp_mlb_category.erp_mcid', '=', 'erp_mlbcategory_erpcategory.erp_mlbcategoryid')
                            ->select('erp_mlb_category.erp_mlbid')
                            ->whereNotIn('erp_product.erp_productid', function($query){
                                $query->select('erp_productid')
                                       ->from('erp_product')
                                       ->where('erp_productid', '=', 'erp_product_category.erp_productid');
                            })
                            ->get();

Any suggestion?

A: This lines of code is wrong:
->whereNotIn('erp_product.erp_productid', function($query){
  $query->select('erp_productid')
  ->from('erp_product')
  ->where('erp_productid', '=', 'erp_product_category.erp_productid');
})

*

*remove this line ->where('erp_productid', '=', 'erp_product_category.erp_productid') cause there is not join here.

*you can't say ->whereNotIn('erp_product.erp_productid' and $query->select('erp_productid')->from('erp_product') in the same order whereNotIn to check the value in the first_column not exists in the second_column not in same first_column.

So, clear this line ->where('erp_productid', '=', 'erp_product_category.erp_productid') and check the right name to put in $query->select('right_column_name')->from('right_table_name').

A: $ids= DB::table('erp_product')->pluck('erp_productid')

$categoria = DB::table('erp_product')
                            ->join('erp_product_category','erp_product_category.erp_productid', '=', 'erp_product.erp_productid')
                            ->join('erp_mlbcategory_erpcategory', 'erp_mlbcategory_erpcategory.erp_categoryid', '=','erp_product_category.erp_categoryid')
                            ->join('erp_mlb_category', 'erp_mlb_category.erp_mcid', '=', 'erp_mlbcategory_erpcategory.erp_mlbcategoryid')
                            ->select('erp_mlb_category.erp_mlbid')
                            ->whereNotIn('erp_product.erp_productid',$ids)
                            ->get();


text:
Q: How to solve a Capybara::ElementNotFound Error I'm stuck with the following problem, this is the first time I use capybara, have you an idea how I can solve this issue, thanks
I use rails 3.0.0 and the following gems
gem 'rails', '3.0.0'
gem 'capybara'
gem 'database_cleaner'
gem 'cucumber-rails'
gem 'cucumber'
gem 'rspec-rails'
gem 'spork'
gem 'launchy'

I have the following in my senario
When I go to the new customer page
And I fill in "Email" with "john@example.com"

in my customer_steps.rb I have
When /^I fill in "([^"]*)" with "([^"]*)"$/ do |arg1, arg2|
  fill_in arg1, :with => arg2
end

In my view
- form_for @customer do |f|
  = f.label :email, 'Email'
  = f.text_field :email
  = f.submit

When I run my scenario I get this error message
 Scenario: Register new customer                  # features/manage_customers.feature:7
    When I go to the new customer page             # features/step_definitions/customer_steps.rb:1
    And I fill in "Email" with "john@example.com"  # features/step_definitions/customer_steps.rb:5
      cannot fill in, no text field, text area or password field with id, name, or label 'Email' found (Capybara::ElementNotFound)
      ./features/step_definitions/customer_steps.rb:6:in `/^I fill in "([^"]*)" with "([^"]*)"$/'
      features/manage_customers.feature:9:in `And I fill in "Email" with "john@example.com"'

A: I found my mistake!!!
When I go to the new customer page

before the step was
When /^I go to (.+)$/ do |page_name|
  path_to page_name
end

I forgot the visit...
When /^I go to (.+)$/ do |page_name|
  visit path_to(page_name)
end

A: Use this id of the field instead, which should be like

And I fill in "customer_email" with "john@example.com"

if the @customer is a object customer model


text:
Q: Pandas Left Merge with xlsx with CSV producing null value columns in output I am using Python 3.4, Pandas 0.16.2 and Jupyter Notebook as my IDE.
I am importing the following two dataframes as follows:
Lookup = pd.read_excel("LookupMergeOutput.xlsx")

Concatenated = pd.read_csv('Concatenated.csv', error_bad_lines = False, na_values='', iterator=True,  chunksize=1000)
data = pd.concat([chunk for chunk in Concatenated], ignore_index=True)

Data
Lookup dataframe spec: 23353 rows 8; 8 columns
Columns:          Dtype:

LOGINNAME         object
FIRSTNAME         object
LASTNAME          object
ID_y               int64
CREATEUSERID       int64
REVISIONUSERID     int64
BEGINDATE         object
ENDDATE           object

data dataframe spec: 23653 rows; 667 columns
The column of interest for the merge in this dataframe is REFERENCE_ID with
data.REFERENCE_ID.dtype

as 'object'
The columns to merge on are ID_y and REFERENCE_ID (in the data dataframe). The columns in Lookup contain unique value counts (eg. 265926639 etc).
The data dataframe has unique values, but also repeating instances of an an entry (for example, three instances of 265946567. Moreover, there are error strings with the following caricature: 421D6158-22D4-EDAC-0DEA-33B1FB5CC7AF.
Goal:
To merge Lookup and data on the to key columns ID_y and REFERENCE_ID, respectively.
***References and prior search for answers but with little fruit to bear:

*

*Left merge without reindexing

*Conditional Merge

*Chris Albon's Tutorial

*Merging multiple dataframes

*Data Carpentry's Review
What I have attempted so far:
merged_left = pd.merge(left=Lookup,right=data, how='left', left_on='ID_y', right_on='REFERENCE_ID')

This returns all of the Lookup data but all 667 columns of the data dataframe come back as null values.
In theory, if there are common numbers in the two "key" columns, the data from the data dataframe to match. My hypothesis is either that there is a data type conflict or because there are repeating numbers in the data dataframe, that the merge is not taking place. I want to avoid dropping the duplicates or multiple instances of keys in the data column as this may have valid data.
I have also tried to rename the ID_ycolumnname to REFERENCE_ID and perform a merge as follows:
Lookup=Lookup.rename(columns = {'ID_y':'REFERENCE_ID'})

This produces a null dataframe (just columns, but no values). I have also attempted to set the index as ID_y and REFERENCE_ID and then perform the merge on the index:
Lookup = Lookup.set_index('ID_y')
data = data.set_index('REFERENCE_ID')

merged_on_index = pd.merge(Lookup,data, left_index=True,right_index=True)

I receive the following traceback:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-35-3909fd759082> in <module>()
----> 1 pd.merge(AgentLookup,data,left_index=True,right_index=True)

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tools\merge.py in merge(left, right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy)
     36                          right_index=right_index, sort=sort, suffixes=suffixes,
     37                          copy=copy)
---> 38     return op.get_result()
     39 if __debug__:
     40     merge.__doc__ = _merge_doc % '\nleft : DataFrame'

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tools\merge.py in get_result(self)
    184
    185     def get_result(self):
--> 186         join_index, left_indexer, right_indexer = self._get_join_info()
    187
    188         ldata, rdata = self.left._data, self.right._data

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tools\merge.py in _get_join_info(self)
    257         if self.left_index and self.right_index:
    258             join_index, left_indexer, right_indexer = \
--> 259                 left_ax.join(right_ax, how=self.how, return_indexers=True)
    260         elif self.right_index and self.how == 'left':
    261             join_index, left_indexer, right_indexer = \

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\core\index.py in join(self, other, how, level, return_indexers)
   2041             other = other.astype('O')
   2042             return this.join(other, how=how,
-> 2043                              return_indexers=return_indexers)
   2044
   2045         _validate_join_method(how)

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\core\index.py in join(self, other, how, level, return_indexers)
   2054             else:
   2055                 return self._join_non_unique(other, how=how,
-> 2056                                              return_indexers=return_indexers)
   2057         elif self.is_monotonic and other.is_monotonic:
   2058             try:

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\core\index.py in _join_non_unique(self, other, how, return_indexers)
   2125
   2126         left_idx, right_idx = _get_join_indexers([self.values], [other.values],
-> 2127                                                  how=how, sort=True)
   2128
   2129         left_idx = com._ensure_platform_int(left_idx)

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tools\merge.py in _get_join_indexers(left_keys, right_keys, sort, how)
    459
    460     # get left & right join labels and num. of levels at each location
--> 461     llab, rlab, shape = map(list, zip( * map(fkeys, left_keys, right_keys)))
    462
    463     # get flat i8 keys from label lists

TypeError: type object argument after * must be a sequence, not map

At this point in time, I at a loss as to what would be the best strategy. I welcome feedback on next steps.

A: Both your join fields are different data types. REFERENCE_ID as an object type and ID_y as a numeric int64 type. Interestingly, the object dtype in pandas is a NumPy ndarray which holds pointers to variable-length string items. Also, object is the most general of the data types when imported data contains both strings and numbers.
Consider converting the join fields to same data types using astype. Of course, strings tend to be most permissive allowing various characters like hyphens.
String conversion:
data['REFERENCE_ID'] = data['REFERENCE_ID'].apply(str)  # NOTICE APPLY HERE
LookUp['ID_y'] = LookUp['ID_y'].astype(str)

Numeric conversion:
data['REFERENCE_ID'] = data['REFERENCE_ID'].astype(int)

Combination:
data['REFERENCE_ID'] = data['REFERENCE_ID'].astype(str).astype(int)
LookUp['ID_y'] = LookUp['ID_y'].astype(str).astype(int)


text:
Q: Strike through text without affecting text box size I want to strike through text with a simple line. Unfortunately, in the solution(s) I found, the text always has a larger distance to the next line (see example).
How can I strike through text without increasing the distance to the next line?
\documentclass[12pt]{beamer}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{lmodern}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[normalem]{ulem}
\newcommand\tst{% thick strike through  %% from http://tex.stackexchange.com/questions/134088/mis-alignment-of-columns-in-tabular-environment-when-using-ulem-and-beamer
  \bgroup%
  \markoverwith{\textcolor{red}{\rule[.8ex]{1pt}{0.8pt}}}%
  \ULon%
}

\begin{document}

\begin{frame}
\begin{align*}
P = \{ & \tst{S\rightarrow X_{1,4,2}}\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1},\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1}\}
\end{align*}
\end{frame}

\end{document}

A: Without ulem or soul:
\documentclass[12pt]{beamer}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{lmodern}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\makeatletter
\newcommand{\tst}[1]{%
  \ifmeasuring@
    % we're in the measuring stage, just use the argument
    #1
  \else
    % we're typesetting, add the strikeout rule
    \sbox0{$\displaystyle#1$}
    \rlap{\color{red}%
          \vrule height \dimexpr.5ex+0.4pt\relax
                 depth -\dimexpr.5ex-0.4pt\relax
                 width \wd0 }
    \box0
  \fi
}
\makeatother

\begin{document}

\begin{frame}
\begin{align*}
P = \{ & \tst{S\rightarrow X_{1,4,2}}\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1},\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1}\}
\end{align*}
\begin{align*}
P = \{ & S\rightarrow X_{1,4,2}\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1},\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1}\}
\end{align*}
\end{frame}

\end{document}

A: I used soul to do the strikethrough, but had to define a displayst command to do strikethrough in display math mode. (soul commands only work with math as in \st{$abc$} . . . ) I also used the solution from Why is it that coloring in soul in beamer is not visible to make the color work. Use \setul{⟨underline depth⟩}{⟨underline thickness⟩} to change thickness of underline/strikethrough in soul.–
\documentclass[12pt]{beamer}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{lmodern}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{color,soul}
\makeatletter
\newcommand\SoulColor{%
  \let\set@color\beamerorig@set@color
  \let\reset@color\beamerorig@reset@color}
\makeatother
\setstcolor{red}
%\setul{}{1pt} Use this to change weight of underline/strikethrough

\newcommand{\displayst}[1]{\textrm{\SoulColor\st{$\displaystyle#1$}}}

\begin{document}

\begin{frame}
\begin{align*}
P = \{ & \displayst{S\rightarrow X_{1,4,2}}\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1},\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1}\}
\end{align*}
\end{frame}

\end{document}

Result:

Edit
I guess making this work nicely with soul required fixing a few things. The original solution I posted strikes behind the text, instead of on top of it, but this was solved in Strikeout in different color appears behind letters, not on top of them
\documentclass[12pt]{beamer}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{lmodern}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{xparse,xcolor,soul}

%% First define strikethrough command that strikes on top of letters, not behind them
\makeatletter
\NewDocumentCommand{\sttwo}{O{red}O{black}+m}
    {%
        \begingroup
        \setulcolor{#1}%
        \setul{-.5ex}{1pt}% <---- sets the undline/strikeout weight to 1pt
        \def\SOUL@uleverysyllable{%
            \rlap{%
                \color{#2}\the\SOUL@syllable
                \SOUL@setkern\SOUL@charkern}%
            \SOUL@ulunderline{%
                \phantom{\the\SOUL@syllable}}%
        }%
        \ul{#3}%
        \endgroup
    }
\makeatother

% Now make soul colors work with beamer
\makeatletter
\newcommand\SoulColor{%
  \let\set@color\beamerorig@set@color
  \let\reset@color\beamerorig@reset@color}
\makeatother

%Now make a version of strikethrough that works with display math
\newcommand{\displayst}[1]{\textrm{\SoulColor\sttwo{$\displaystyle#1$}}}

\begin{document}

\begin{frame}
\begin{align*}
P = \{ & \displayst{S\rightarrow X_{1,4,2}}\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1},\\
       & X_{1,4,1}\rightarrow X_{1,1,1}X_{2,3,1}\}
\end{align*}
\end{frame}

\end{document}

Result:


text:
Q: Kivy Image is not loading showing white square on the Phone screen corner I made a simple application with Kivy in Python which just displays up a Png Image. But when I Build an APK with the buildozer and run it on the Mobile phone it shows me a black screen with a white box square in the bottom left corner. I visited forums with similar questions but I didn't found anything clearly mentioned about this problem. Kindly guide me, what is wrong with my APK?
here's the code.

import kivy
from kivy.app import App
from kivy.uix.image import Image

  class MyApp(App):

        def build(self):

            return Image(source =r'C:\Users\amitn\Music\apk luci stuff\luci2.png',allow_stretch=True)

    MyApp().run()

When I build Apk of this python file with Buildozer, it gave me the result as in the below Image.
This is what my phone screen shows up when I run the app after the installation.


text:
Q: django FileField and data migrations So I added a FileField to my model:
def sig_directory_path(instance, filename):
    try:
        ext = filename.split('.')[-1]
    except:
        ext = ""
    filename = '{}.{}'.format(uuid4().hex, ext)
    return 'sig/{0}'.format(filename)

ServiceReportData(models.Model):
    ...
    # Newly added.
    ca_technicianSignatureImage = models.FileField(null=True, blank=True, verbose_name="Technician Signature", upload_to=sig_directory_path)

I already created the auto migration and migrated the changes. So the DB now has null values for ca_technicianSignatureImage column.
Then I wanted to create a data migration for this field because I don't want null values for the field:
from django.core.files.base import ContentFile
from django.db import migrations

# File content.

no_image_svg_content = """
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns="http://www.w3.org/2000/svg"
version="1.1"
width="200"
height="150">
<rect
width="199"
height="149"
x="0.5"
y="0.5"
id="rect2824"
fill="#ffffff" stroke="#999999" stroke-width="1"/>
<text
x="64.648438"
y="79.863152"
id="text2818"
font-size="24"
font-weight="bold" text-align="center" text-anchor="middle" fill="#999999" stroke="none" font-family="Sans">
<tspan
x="100"
y="60"
id="tspan2820">No image</tspan>
<tspan
x="100"
y="90"
id="tspan2822">available</tspan>
</text>
</svg>
"""

def set_signatures(apps, schema_editor):
    no_image_data = ContentFile(no_image_svg_content)
    ServiceReportData = apps.get_model('mism', 'ServiceReportData')
    for service_report in ServiceReportData.objects.all():
        if service_report.ca_customerSignatureImage is None:
            service_report.ca_customerSignatureImage.save('no_image.svg', no_image_data)

class Migration(migrations.Migration):

    dependencies = [
        ('mism', '0004_auto_20180131_1651'),
    ]

    operations = [
        migrations.RunPython(set_signatures, migrations.RunPython.noop),
    ]

Running this migration doesn't change the DB. I can't figure out how to do it. Simply, I just want to put a default .svg file in the field if the field is empty. How to get this done?

A: You need to call instance's save() method also:
service_report.ca_customerSignatureImage.save('no_image.svg', no_image_data)
service_report.save()

or as a shortcut use save=True of File save method:
service_report.ca_customerSignatureImage.save('no_image.svg', no_image_data, save=True)

A: The bug after all was simple.
This is not the correct way to check if a FileField is null:
if service_report.ca_customerSignatureImage is None:

Rather had to do this:
if service_report.ca_customerSignatureImage.name is None:


text:
Q: CocoStudio: Possible to generate dynamic sized scene for cross-platform use? Is it possible to make a scene, or maybe UI element in cocostudio that scales with the size of the app?
I'm using cocos2d-x and want to make sure I accommodate many screen sizes since the app is cross-platform. As of now, I make my UI elements, add them to a scene in the scene editor, export them and my app picks up the json and imports the scene correctly. That's the good news.
I've also added the options of scaling location and size in cocostudio, to the best of my knowledge as shown in this screen shot.

But, when I change the size of my app the scene I imported does not resize like it should. For example, I created the scene as 640x960 and it always stays that height and width even when the app starts at different.
Anyone successfully gotten cocostudio to export a scene that resizes dynamically?

A: I think I found the answer on this Chinese CocoStudio forum. (Thanks Google translate!)
In the UI editor of CocoStudio you need to have the root node selected. (it's the top node, I just named it root). This is the only node I found that allows you to select absolute or relative positioning.

Select relative positioning under "Child Control Layout" and set the mode to custom under "size and mode" and enable percent.

I also made sure each individual child node was enabled for relative sizing and positioning as mentioned in my original question
EDIT: Important note!
The steps above are required, but there is one more thing to note. The field labeled "adapt resolution" must be checked in order for this to work


text:
Q: Tomcat Run but browser don't display localhost page Welcome, I have problem with Spring Boot, I want start with Spring Boot and generate projekt using SPRING INITIALIZR. But when I want run empty projekt ( I don't change nothing after generate) my http://localhost:8080/ display me:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this
as a fallback.

Wed Oct 10 22:45:26 CEST 2018
There was an unexpected error (type=Not Found, status=404).
No message available

but server tomcat run coretly and looks good. Only these logs disturb me:
2018-10-10 22:47:35.378  INFO 2820 --- [           main]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-10-10 22:47:35.382  INFO 2820 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
Thank you for any suggestions


text:
Q: Connecting to external database in ASP.NET C# I don't know whether this should be here or stack exchange. Seems like stack exchange is more for theoretical discussion so I am starting here.
I want to create a connection string in the web.config file for queries to a database residing at another domain. I can't seem to find a good article for what to put in the connection string, and how to set up the responding database and it's security so that it will accept the connection with the proper credentials passed and execute and return the query. Does anybody know of a good article for this? Thanks.

A: Here you have examples on every kind of connectionstring, or at least the ones that matter plus a few that dont:
http://www.connectionstrings.com/