text:
Q: How to programmatically distinguish/control Azure internal vs. outbound traffic? Background
I'm lead architect of developer-accelerator platform called the Ball. The Ball is designed to provide authorized processing within cloud-alike scalability, running already on Windows Azure on production with web content management. The problem it solves, is to provide full-distributed scale architecture for easy plug-in developable for back-end (.NET) and front-end web (jQuery, JSON).
The platform manages data/content up to massive scales. It's native storage design is Key-Value blob-storage, so its scalability is designed to Terabyte-scale. It supports flexible communications between instances - both end-points running in Azure.
We're now in process of plugging in user-definable integrations of content - thus to the problem.
Problem/Question
The architecture already uses low-level request management, and it's already plugged in to monitor traffic/cost through HTTP-module/handler implementation. However I don't find any clean reference how to ensure and guarantee that network calls stay within datacenter - and in a way that I know that Azure infrastructure also agrees that traffic was within datacenter.
The current production use will cause instantly gigabyte scale daily data traffic (per customer) and we need to get this right from the moment it's launched. Given the cost-efficiency for the architecture, it will become largest component by far, if it's getting billed by outbound traffic rates.
I'm not looking to remove the costs where they do apply. If customer runs their own instance of the Ball on AWS or Azure in different datacenter, there will be outbound-traffic component - no matter what.
Current status of the solution
The Ball has it's authorization stack at network level. While technically instance-internal traffic could be controlled within internal network, it would logically complicate things and I believe this should be solved through outbound network interface level control. If there is good reference-alike answer (or we make up one in this chain) it should apply to all distributed architecture cases that have to cost-optimize network outbound traffic.
The current solutions that I've found circulate around detection of datacenter-specific traffic due to IP-address, based on lists such as this:
http://msdn.microsoft.com/en-us/library/windowsazure/dn175718.aspx
While those kind of lists technically can be used, it's loosely coupled trust to "not-to-cause-costs" at best.
Techwise the Ball is built with .NET 4.5 and latest Azure SDK for .NET. For devops-automation the Powershell is planned on roadmap, so any Azure-management level configuration can be applied for the solution as well.
I've attached few architecture images to clarify the architecture design within single Ball and as network of distributed Ball instances.

A: I just got response from our MSFT sources, that as of today (13th of Feb 2014) no required capability is exposed from the Azure platform.
So answering about how to get this info as "platform supported" is: Not possible.
I can think already few workarounds around involving IP-address based logic (not so trustworty) or adding external registry, that can be manually checked/updated for known parties that will be calling within certain datacenter. While workarounds (hopefully) suffice for certain scenarios, they do not qualify a solution for "we share this data public, as long as you're within our datacenter".
I won't flag this as accepted answer, as it's not including even the workaround specs. I'll come back myself later to fill in how we solved it.


text:
Q: Filter/Search JavaScript array of objects based on other array in Node JS i have one array of ids and one JavaScript objects array. I need to filter/search the JavaScript objects array with the values in the array in Node JS.
For example
var id = [1,2,3];

var fullData = [
    {id:1, name: "test1"}
   ,{id:2, name: "test2"}
   ,{id:3, name: "test3"}
   ,{id:4, name: "test4"}
   ,{id:5, name: "test5"}
];

Using the above data, as a result i need to have :
var result = [
    {id:1, name: "test1"}
   ,{id:2, name: "test2"}
   ,{id:3, name: "test3"}
];

I know i can loop through both and check for matching ids. But is this the only way to do it or there is more simple and resource friendly solution.
The amount of data which will be compared is about 30-40k rows.

A: This will do the trick, using Array.prototype.filter:
var result = fullData.filter(function(item){ // Filter fulldata on...
    return id.indexOf(item.id) !== -1; // Whether or not the current item's `id`
});                                    // is found in the `id` array.

Please note that this filter function is not available on IE 8 or lower, but the MDN has a polyfill available.

A: As long as you're starting with an unsorted Array of all possible Objects, there's no way around iterating through it. @Cerbrus' answer is one good way of doing this, with Array.prototype.filter, but you could also use loops.
But do you really need to start with an unsorted Array of all possible Objects?
For example, is it possible to filter these objects out before they ever get into the Array? Maybe you could apply your test when you're first building the Array, so that objects which fail the test never even become part of it. That would be more resource-friendly, and if it makes sense for your particular app, then it might even be simpler.
function insertItemIfPass(theArray, theItem, theTest) {
    if (theTest(theItem)) {
        theArray.push(theItem);
    }
}

// Insert your items by using insertItemIfPass

var i;

for (i = 0; i < theArray.length; i += 1) {
    doSomething(theArray[i]);
}

Alternatively, could you use a data structure that keeps track of whether an object passes the test? The simplest way to do this, if you absolutely must use an Array, would be to also keep an index to it. When you add your objects to the Array, you apply the test: if an object passes, then its position in the Array gets put into the index. Then, when you need to get objects out of the Array, you can consult the index: that way, you don't waste time going through the Array when you don't need to touch most of the objects in the first place. If you have several different tests, then you could keep several different indexes, one for each test. This takes a little more memory, but it can save a lot of time.
function insertItem(theArray, theItem, theTest, theIndex) {
    theArray.push(theItem);
    if (theTest(theItem)) {
        theIndex.push(theArray.length - 1);
    }
}

// Insert your items using insertItem, which also builds the index

var i;

for (i = 0; i < theIndex.length; i += 1) {
    doSomething(theArray[theIndex[i]]);
}

Could you sort the Array so that the test can short-circuit? Imagine a setup where you've got your array set up so that everything which passes the test comes first. That way, as soon as you hit your first item that fails, you know that all of the remaining items will fail. Then you can stop your loop right away, since you know there aren't any more "good" items.
// Insert your items, keeping items which pass theTest before items which don't

var i = 0;

while (i < theArray.length) {
    if (!theTest(theArray[i])) {
        break;
    }
    doSomething(theArray[i]);
    i += 1;
}

The bottom line is that this isn't so much a language question as an algorithms question. It doesn't sound like your current data structure -an unsorted Array of all possible items- is well-suited for your particular problem. Depending on what else the application needs to do, it might make more sense to use another data structure entirely, or to augment the existing structure with indexes. Either way, if it's planned carefully, will save you some time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing Data from Service to Template via Controller and $stateParams I have a service with the following code:
.service('ChatService', function() {
  return { //Gets Data from controller
    sendData: function(data) {
      this.chatData = data;
      console.log('this.chatData: '+this.chatData);
    },
    chats: this.chatData,
    getChats: function() {
      return this.chatData;
    },
    getChat: function(chatId) {
      for(i=0; i<this.chats.length; i++) {
        if (this.chats[i].id == chatId) {
          return this.chats[i];
        }
      }
    }
  }
})

The Important thing here is that sendData retrieves info
[{id: 1, message: "Chat Message 1"},{id: 2, message: "Message 2"}]

from the controller. The getChats in Services is then called $scope.chats = ChatService.getChats(); by the same controller to show in the template.
When that item is clicked a new page with more info is to show hence the getChat and getChats function in the service.
The code in the controller for the page to load more details is
$scope.chatId = $stateParams.chatId;
$scope.chat = ChatService.getChat($scope.chatId);

However I'm getting error cannot read property length of undefined. Now if I change the chats: this.ChatData in the services to
chats: [{id: 1, message: "Chat Message 1"},{id: 2, message: "Message 2"}]

It works like a charm but I need it to display in real time what is in the controller because I'm downloading and receiving info from the server that will be updated in real time for a chat app.

A: Use angular.copy to update the reference:
app.service('ChatService', function() {
    //Gets Data from controller
    this.sendData = function(data) {
      //this.chatData = data;
      //console.log('this.chatData: '+this.chatData);
      //Use angular.copy
      angular.copy(data, this.chats);
    };
    this.chats = [];
    this.getChats = function() {
      return this.chats;
    };
    this.getChat =  function(chatId) {
      for(i=0; i<this.chats.length; i++) {
        if (this.chats[i].id == chatId) {
          return this.chats[i];
        };
      };
    };
});

By using the angular.copy to update the array reference, controllers that have previously fetched the reference will get updated.
For more information, see AngularJS angular.copy API Reference.


text:
Q: HierarchicalDataTemplate with Treeview in MVVM I'm relatively new to MVVM and WPF. I'm attempting to fill a TreeView control with a directory and it's files / subdirectories (in effect the contents of a zip file that I have unpacked)
Following along after this SO question, I have the following class:
namespace IFR_Full.Model
{
    public class Item
    {
        public string Name { get; set; }
        public string Path { get; set; }
    }

    public class FileItem : Item
    {
    }

    public class DirectoryItem : Item
    {
        public List<Item> Items { get; set; }

        public DirectoryItem()
        {
            Items = new List<Item>();
        }
    }

    public class TVItemProvider
    {
        public List<Item> GetItems(string path)
        {
            var items = new List<Item>();
            var dirInfo = new DirectoryInfo(path);

            foreach (var directory in dirInfo.GetDirectories())
            {
                var item = new DirectoryItem
                    {
                        Name = directory.Name,
                        Path = directory.FullName,
                        Items = GetItems(directory.FullName)
                    };
                items.Add(item);
            }

            foreach (var file in dirInfo.GetFiles())
            {
                var item = new FileItem
                {
                    Name = file.Name,
                    Path = file.FullName
                };
                items.Add(item);
            }
            return items;
        }
    }
}

In my ViewModel class I have these properties:
TVItemProvider TVIP = new TVItemProvider();

private List<Item> _tvitems;
public List<Item> TVItems
{
    get { return _tvitems; }
}

which is created in this method:
private void LoadIDMLTreeView(string path)
{
    _tvitems = TVIP.GetItems(path);
}

I set the header and DataContext of my MainWindow like this:
...
xmlns:ViewModel="clr-namespace:IFR_Full"
xmlns:Model ="clr-namespace:IFR_Full.Model"
...

<Window.DataContext>
    <ViewModel:ExcelImportViewModel/>
</Window.DataContext>

and set my treeview xaml code like this:
<TreeView ItemsSource="{Binding}" Name="IDMLView" Margin="10,171.74,10,8" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type Model:DirectoryItem}" ItemsSource="{Binding Path=TVItems}">
            <TextBlock Text="{Binding Path=Name}" ToolTip="{Binding Path=Path}" />
        </HierarchicalDataTemplate>
        <DataTemplate DataType="{x:Type Model:FileItem}">
     <TextBlock Text="{Binding Path=Name}" ToolTip="{Binding Path=Path}" />
    </DataTemplate>
 </TreeView.Resources>
</TreeView>

When I run the program in debug mode I can see that TVItems contains the appropriate items (Directories and files), but my TreeView control is blank.
I imagine that the issue is with the bindings?

A: *

*Change <TreeView ItemsSource="{Binding}" ... to <TreeView ItemsSource="{Binding TVItems}" ...

*Also , Change to <HierarchicalDataTemplate DataType="{x:Type local:DirectoryItem}" ItemsSource="{Binding Items}" >

*Your class has to be like this :
 public class TVItemProvider
    {

        List<object> items = new List<object>();
          DirectoryInfo dirInfo;
          public List<object> GetItems(string path)
        {
            dirInfo = new DirectoryInfo(path);
            foreach (var directory in dirInfo.GetDirectories())
            {
                var item = new DirectoryItem
                {
                    Name = directory.Name,
                    Path = directory.FullName,
                    Items = new TVItemProvider().GetItems(directory.FullName)
                };
                items.Add(item);
            }

            foreach (var file in dirInfo.GetFiles())
            {
                var item = new FileItem
                {
                    Name = file.Name,
                    Path = file.FullName
                };

                items.Add(item);
            }
            return items;
        }

}

*Finally change the type of your lists to List<object> (all of them)

Hope it would help


text:
Q: Add parameter name to gravity forms I am using Gravity form. I have more 400 forms. I want to add a parameter name in every form and in a particular field. I know how to add the parameter in a Gravity form field.
But i want to add parameter in each form like search replace. Is there any trick available for Gravity form. Because it is so time taking to add a parameter name in each form.

A: something like this should do it:
add_filter( 'gform_pre_render', function( $form ) {
    foreach( $form['fields'] as &$field ) {
        // if( field you want ) {
        $field->allowsPrepopulate = true;
        $field->inputName = 'your_parameter';
        // }
    }
}, 9 );

You will need to determine the best way to identify the fields you wish to apply this to. You'll see I've left the condition commented out. If they all have the same field ID you could do:
if( $field->id == 1 ) { ... }

If they'll have the same label, you could do:
if( $field->label == 'My Label' ) { ... }


text:
Q: Pulling a Metal Bar in Space Let's say I have a metal bar (which does not expand or contract at all) that's 1 light-second long which is connected to a block at the end. I am in space holding the other end of the bar. If I pull on the bar, what happens?
If the block moves instantly, then shouldn't the bar appear to get longer, because I don't see the end move until one second later?
On the other hand, if the block takes one second to move, does the bar actually expand, as my end has moved but the block's end hasn't?

A: As mentioned in the comments, there is no such thing as a perfectly rigid body in the context of relativity. As for what you would see, the other end of the rod would not move the instant you pulled it. The effect actually would propagate at the speed of sound in the material. Therefore, not only would the bar appear longer, it actually would be longer. On the other hand, the Lorentz length contraction of the bar is given by $$L=L_{0}\sqrt{1-\frac{v^{2}}{c^{2}}}.$$ Depending on how fast you are pulling the bar, it could also appear shorter.


text:
Q: facebook and WhatsApp not appearing in "complete action using:" list when started from my app I want to start the facebook app or the WhastApp app from my own app but they wont appear in the "Complete action using:" list
I have
Intent intentFB = new Intent(Intent.ACTION_MAIN);
intentFB.setComponent(ComponentName.unflattenFromString("com.facebook"));
intentFB.putExtra("ClassName","FB");
intentFB.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
intentFB.addCategory(Intent.CATEGORY_LAUNCHER);
intentFB.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentFB);

Basiclly I have a webview with a page with an article. This page has a facebook link to share the article. When I tap the link the list appear without the facebook option


text:
Q: For package.loadlib does lua require the dll to be COFF format or ELF format? I'm trying to load a dll into my lua script and call the function. When I create the dll using GCC (under cygwin) and lua (5.2.4) I'm able to load the library & execute it without a problem.
However, when I create run the same script from SciTE, using Lua 5.1, the dll loads successfully. However, it does not execute. In the dll I'm trying to simply write two integers into a file.
t = package.loadlib("mylibrary.dll","myfunc")
t(23,45)

There are two questions here:
1. What format should the 'mylibrary.dll' be, for lua to understand and execute without problems - ELF or COFF.
2. Can I run dll (built under windows, obviously) under lua running on linux?

A: The question in your title seems to be very different from the cause of the problem you describe.
On the one hand, the format for dynamic libraries loaded by Lua is the format for the platform that the Lua code is running on. Just as you can't take a compiled Win32 executable and expect it to run on Linux, you can't take a compiled Win32 dll and expect it to load it on Linux. Obviously emulation tools like Wine exist, but those work by emulating Windows. You could run them within the emulator, but not outside of it.
But on the other hand, that is not the source of your problem. Your problem is that you're using a dynamic library that was built for one version of Lua with an application that was built for another version of Lua. That doesn't work; Lua does not retain compatibility between "minor" versions, only between revisions (Lua 5.1.3 vs. 5.1.4).
ELF or COFF, that isn't going to work.


text:
Q: Action Script 3. Stop game after loop 3 times I'm creating flash game, Idea is falling objects (in this case apples) from the sky and player need to click on apples. I need to make that when 3 apples are missed show "Game over" or etc, I need to stop game. I know this is simple for you professionals :)
Thank you for answers.
This is part of code:
 for (var i = apples.length-1; i >= 0; i--)
        {
            apples[i].y += gravity;
                                                  //here I need to add loop?
            if (apples[i].y > C.APPLE_END_Y)
            {
                mcGameStage.removeChild(apples[i]);

                apples.splice(i,1);
            }
        }

A: I remember you having the function called update() in your last post about this program.  Whatever class all of this is happening in, place this variable:
private var m_iLives:int = 3;

Then, in your update() function, use this code:
for (var i = apples.length-1; i >= 0; i--)
{
    apples[i].y += gravity;
    if (apples[i].y > C.APPLE_END_Y)
    {
        mcGameStage.removeChild(apples[i]);
        apples.splice(i,1);
        m_iLives--;

        if (!m_iLives)
        {
            gameOverFunc();
            break;
        }
    }
}


text:
Q: NoCredentialProviders error when using docker compose up on Windows I tried to follow this guide: link
Apparently it's an easy way to deploy your project on an ECS, but every time I'm trying the docker compose up command it gives me that error:
NoCredentialProviders: no valid providers in chain. Deprecated.
        For verbose messaging see aws.Config.CredentialsChainVerboseErrors

My docker-compose.yaml looks pretty much the same just with my ECR repository and VPC.
I also already put the credentials in the aws credentials file.


text:
Q: Check if request input is not null before set the value I have an API that set user settings. Because neither of inputs are mandatory I want to check first if the value exists and then set it to the model attributes in order to avoid null values.
$this->InputValidator->validate($request, [
                'firsname' => 'string',
                'lastname' => 'string',
                'email' => 'email',
                'mobile_phone' => 'string',
                'address' => 'string',
                'language' => 'string',
                'timezone' => 'string',
                'nationality' => 'string',
                'profile_photo' => 'url'
            ]);

            $userInformation = new UserInformation([
                'firstname' => $request->input('firstname'),
                'lastname' => $request->input('lastname'),
                'email' => $request->input('email'),
                'mobile_phone' => $request->input('mobile_phone'),
                'address' => $request->input('address'),
                'profile_photo' => $request->input('profile_photo')
            ]);
            $User->information()->save($userInformation);

Specificaly when one of inputs is not existin I dont want to pass it to the model. Also I dont want to make inputs required

A: This answer to this question taken from here :
if($request->filled('user_id'))

A: do this
$userInformation = new UserInformation;

if(request->has('firstname')){
   $userInformation->firstname = $request->firstname;
}
if(request->has('lastnme')){
   $userInformation->lastname = $request->lastname;
}

 // do it for all

 $User->information()->save($userInformation);

Edit: Or use Form requests, it's a better approach

A: Check each value and push it first into array. Then assign array.
<?php
$userArray=array();
if($request->input('firstname') != "") $userArray['firstname']=$request->input('firstname');

if($request->input('lastname') != "") $userArray['lastname']=$request->input('lastname');
if($request->input('email') != "") $userArray['email']=$request->input('email');
if($request->input('mobile_phone') != "") $userArray['mobile_phone']=$request->input('mobile_phone');
if($request->input('address') != "") $userArray['address']=$request->input('address');
if($request->input('profile_photo') != "") $userArray['profile_photo']=$request->input('profile_photo');

$userInformation = new UserInformation($userArray);
?>


text:
Q: Backward diodes VI curve I am searching for the IV curve of a backward diode but couldn't find anything, any help?

A: If you just need an IV-curve of a random backward diode, the German Wikipedia site has one:

(Unknown authorUnknown author, Public domain, via Wikimedia Commons)
There is a hint, that the diagram might be flipped by 180 ° compared to those of a tunnel diodes. So the right side of that picture is actually the reverse polarity side. Not sure why it was done like that.

A: There seems to be a misunderstanding of your terminology globally. My apologies.
18GHz Planar Tunnel (Back) diode datasheet
A Backward Diode(EU) or Back Diode (USA) is a special type with much higher negative  impedance and low capacitance which can be biased to be an amplifier, rectifier or switch for UHF to EHF microwave (EHF means >30 GHz, UHF is <30 GHz) It uses an expensive process for a crystal semiconductor fabricated with such low impurities that it has a breakdown voltage ratio of 50kV/mm. (Although similar low impurity levels are required for the smallest lithography CMOS).
As such it is a very specialized process with a very narrow gap in Germanium and not your "garden variety" commercial diode so it is only produced by specialized high purity foundries with specialized expensive annealing and high doping chemical processes.
This led to the recent development of other shallow negative resistance devices using Indium Gallium Arsenide Nitride over Gallium Arsenide InGaAsN/GaAs for high efficiency (43%) solar panels.
Others may find companies who make these types  but one of the first "Back Diodes" were the 1N371x series found in old data books.
Dr. Leo Esaki (Sony) was credited with a Nobel Prize in Physics for explaining the Quantum Tunnelling effect in 1958 so IMHO his name ought to be used for Tunnel diodes. "back diode" was used by Horowitz's books for this "Back" diode  special version of Tunnel Diodes which has lower capacitance and higher resistance than the classic Tunnel diodes.
You would have to lookup old GE transistor books to find the ones Esaki used on archive.org. 1N3716
Detector
It has low capacitance and much higher "negative incremental resistance" or smaller hump when reverse biased, almost like a normal diode leakage which has only a positive incremental resistance that is rises sharply near the Vr limit .
This  class of diode has such a low capacitance that it has  no charge storage effect.
The hump which rises slower with neg. R than a Tunnel diode strongly nonlinear because of this change in polarity if resistance for small signals.
As an FM/AM detector it can be used as a detector up to 40 GHz. Esaki designed the Tunnel diode (Germanium Arsenic ) into the SONY FM Radio (EFM-117) radio and it still works today.
Rectifier
A backward diode can be used for rectifying weak signals with peak amplitudes of 0.1 to 0.7 V.
Switch
A backward diode can be used in high speed switching applications.
But it shares the leakage sensitivity of a normal diode.
Reverse leakage is very temperature sensitive and constant till Vr max , so often just the table values  are given at 25'C and 125'C which is orders of magnitude worse.
Here's one sample see Fig 3
https://www.taiwansemi.com/assets/uploads/datasheet/TSUP5M45SH_A1909.pdf
Esaki's Do's and Don'ts
-

Don't allow yourself to be trapped by your past experiences.
Don't allow yourself to become overly attached to any one authority in your field – the great professor, perhaps.
Don't hold on to what you don't need.
Don't avoid confrontation.
Don't forget your spirit of childhood curiosity.


text:
Q: How to assign existing NIC/Vnet to VM on Azure portal while creating a VM? When creating a VM, as we can see in the image below, we cannot choose an existing VNet. The solution I found is to create using ARM template and specify an existing VM. More over it is stated "When creating a virtual machine, a network interface will be created for you."

*

*Is there a better way to do this on portal? (even though it is a combo box, we really cannot select an existing vnet)

*Why is Azure not allowing it when the same functionality is available for storage accounts (choosing existing network)?

A: Unfortunately, you cannot select the existing NIC in the way you used as the screenshot shows, but you can select the existing Vnet in the same region. As you see, Azure will create the nic itself for you.
In the Azure portal, you can only use the template to create a VM with both existing NIC and Vnet as I know. And you can also achieve what you want using the Azure CLI locally. Also does the PowerShell and REST API and etc.


text:
Q: Python hidapi, why can't read my keyboard via usb? I am trying to read the data input from my keyboard in python hidapi, and print it to the console.
(This is the keyboard I am currently using, but I would like to read the USB with a python code too)
I can't get it to work.
At data = device.read(64)
line I always getting a read error.
I was trying different alternatives with the help of chatGPT, start visual studio code as administrator, plug out-in the keyboard, but nothing helps.
Here is my code:
import hid

# Enumerate all connected HID devices
devices = hid.enumerate(0, 0)
for device in devices:
    print("Device:", device)

# Open a specific HID device
device = hid.device()
device.open(3690, 704)

# Read data from the device
data = device.read(64)

# Print the data
print("Data:", data)

# Close the device
device.close()

Here are the datas of my keyboard:

Device: {'path': b'\\?\HID#VID_0E6A&PID_02C0&MI_01&Col05#7&28db5c83&0&0004#{4d1e55b2-f16f-11cf-88cb-001111000030}\KBD', 'vendor_id': 3690, 'product_id': 704, 'serial_number': '', 'release_number':
22529, 'manufacturer_string': 'dakai', 'product_string': 'PS/2+USB Keyboard', 'usage_page': 1, 'usage': 6, 'interface_number': 1}

Here is the failure message:

Thanks for your help!


text:
Q: css paragraphs in the middle How can I do it that all sentences are in the middle
like :

but it should be text not horizontal lines ^^

A: Give the property text-align: center to the element containing the text.

A: Use text-align: center;
Link: https://developer.mozilla.org/en-US/docs/Web/CSS/text-align

  veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat

A: Try doing this example (remember to replace text in div with your own).

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu sapien vitae sem blandit pulvinar.


text:
Q: How to create a reminder using Alarm which can be editable in future I want to create alarm inside an application at a particular Date & Time. It should display its description when it's time elapses which can be editable. And it should display only description and should not contain other details such as "Mark As Private", "Conference Call" etc..

A: Alarm is a type if Event. To retrieve events you should use the following:
EventList list = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE);

Then use method items(int searchType, long startDate, long endDate, boolean initialEventOnly) to iterate over events:
for(Enumeration e = list.items(EventList.STARTING, startDate, endDate, false); e.hasMoreElements; ) {
    Event event = (Event)e.nextElement();
    if (sholdBeChanged()) {
        Event event2 = list.createEvent();
        // initialize fields of event2. Probably copy them from event
        list.removeEvent(event);
        break;
    }
}

For more information refer to
http://developers.sun.com/mobility/apis/articles/pim/index.html
http://www.jcp.org/en/jsr/detail?id=75


text:
Q: Can I ignore a specific project in a .Net solution when using git? I have a .Net solution with multiple projects, for example, project A, B and C.
B and C are dependencies of A. That means without A, B and C could be compiled as well.
There are some special configurations in project A, so I want to exclude project A when uploading to Github repository.
If I just set the project folder name in .gitignore then I will get error while compiling the solution from Git.
What should I do?

A: You can organize the projects in one folder each one and ignore the folder. On the .gitignore file:
/Project.Web/*

Considering the directory Project.Web is ion the root of the repository, everything under the Project.Web path would be ignored.
Potential Problems:

*

*If your solution file .sln references a project that may be not exists on the structure

*You could not be able to compile until you remove it from the sln.

*It also could be a reference to other projects in the same solution which also could avoid to compile.
If you just want to make possible the compilation, generate the dependent assembly you want to ignore and switch the reference from the project in solution to the generated assembly. It will make the compilation possible and you will not be exposing your code.


text:
Q: Output of Anonymous Thread class is not synchronized I have the following code snippet.
public class Test {
     static final StringBuffer sb1 = new StringBuffer();
     static final StringBuffer sb2 = new StringBuffer();
     public static void main(String args[])
     {
        new Thread()
        {
           public void run()  {
            synchronized(this)
            {
                try {
                sb1.append("A");
                sb2.append("B");
                System.out.println (sb1 + " " + sb2);
                Thread.currentThread().sleep(5000);
                    h.sb1.append("U");
                    h.sb2.append("V");
                    System.out.println (sb1 + " " + sb2);
                 } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
           }
        }.start();
        new Thread()
        {
        public void run()
        {
            synchronized(this)
            {
                sb1.append("C");
                sb2.append("D");
                System.out.println (sb1 + " " + sb2);
            }
        }
    }.start(); /* Line 28 */

    new Thread()
        {
        public void run()
        {
            synchronized(this)
            {
                sb1.append("E");
                sb2.append("F");
                System.out.println (sb1 + " " + sb2);
            }
        }
    }.start();

    }
}

And when I run the program looks like it is not synchronized at object level. The output I'm getting is:
A B
AC BD
ACE BDF
ACEU BDFV

And I'm expecting the expected output as
A B
AU BV
AUC BVD
AUCE BVDF

Can someone please clarify what does this keyword refer to? Also if I use synchronize(this.getThreadGroup()) instead of synchronized(this). I get the output the expected output.

A: synchronized(this)

can't work in this case, since this would refer to the Thread object and every run function is running in the own Thread.
if you use synchronized(sb1) your code should work as intended. You can synchronize on every object you want, java will lock the object on the statement and release it after the brackets. You should simply care, that you really synchronize on the same object.


text:
Q: How assign Pandas column value referring to list in Python? The idea is assign pandas column according to a list.
from pandas import DataFrame
time_window_order=['268','264','260','256','252','248','244','240']
df =DataFrame ({'time_window':['268','268','268','264','252','252','252','240'],'seq_no':[0,0,0,1,4,4,4,7]})

for idx,ord in enumerate(time_window_order):
    df.loc[df['time_window'].isin([ord]), 'centre_point'] = idx

But, I wonder whether there is more efficient or built-in pandas approach.

A: You can convert the list into a dictionary with the position as the value. The key will be the value in the list. Then do a map to get the result.
from pandas import DataFrame
time_window_order=['268','264','260','256','252','248','244','240']
order_dict = {k:i for i,k in enumerate(time_window_order)}
df =DataFrame ({'time_window':['268','268','268','264','252','252','252','240'],'seq_no':[0,0,0,1,4,4,4,7]})
df['centre_point'] = df['time_window'].map(order_dict)
print (df)

The output of this will be:
  time_window  seq_no  centre_point
0         268       0             0
1         268       0             0
2         268       0             0
3         264       1             1
4         252       4             4
5         252       4             4
6         252       4             4
7         240       7             7


text:
Q: RoR Active Record Serialize JSON I am encountering "UndefinedConversionError - "\x92" from ASCII-8BIT to UTF-8"
When saving to the text field: "data" with content in a CSV file
class ManagedFile < SomeParent
  serialize :data, JSON

Is there a way to avoid the error?


text:
Q: Oracle: Is There a Variant of REGEX_REPLACE that supports inline code? Note: This question has originally been asked in the context of c++ regexp_replace (see here). However, it occurred to me that it might be of interest in the oracle universe, too. The wording of the question has been adopted with the kind permission of the original author.
Perl has the e regex modifier which allows Perl code rather than just a string to formulate the replacement: http://perldoc.perl.org/perlretut.html#Search-and-replace Though that example is not the greatest as there are switches to accomplish this. For those of you who understand Perl here's an example that makes more sense:
$string = "StackOverflow user: Old Faithful";

$string =~ s/:\s*(.*)$/$1 == "Old Faithful" ? ": ".$1." is AWESOME!" : ": ".$1." is ???"/e;

print $string; #Will print "StackOverflow user: Old Faithful is AWESOME!"

Is there a regex_replace variant in (Pl)Sql that will allow me to do something similar? As in code inline for the replacement.

A: Unfortunately, REGEX_REPLACE doesn't cater for dynamically generated replacement strings.
However, you can come close. This answer contains 3 variations of the same idea. In a nutshell:

*

*Variation 1: static
simplest, computations in expression syntax only, sql compatible, performance nightmare

*Variation 2: static + function call
simple, complex computations, sql compatible, performance nightmare;
privileges to create function/packages needed.

*Variation 3: dynamic
complex, utmost flexibility in executed code, not sql compatible, performance ... you guessed it.
The basic idea of all methods is to use REGEXP_SUBSTR to get hold of the capture group contents and feed these contents to the code computing the data actually substituted with it.
In Variation 1 this code would be the expression itself, variation 2 hides this code in a function body and variation 3 implements it as a dynamic plsql block around it.
Variant 1 (static)
Use REGEXP_SUBSTR to get hold of the capture group contents and feed the expression to process this data accordingly:
set serveroutput on
DECLARE
    text_orig_yep VARCHAR2(1000) := 'StackOverflow user: Old Faithful';
    text_orig_nay VARCHAR2(1000) := 'StackOverflow user: Some Nobody';
    text_pattern  VARCHAR2(1000) := ':\s*(.*)$';
    text_repl     VARCHAR2(1000);
BEGIN
    text_repl :=
       REGEXP_REPLACE (
            text_orig_yep
          , text_pattern
          , CASE REGEXP_SUBSTR(text_orig_yep, text_pattern, 1, 1, '', 1)
               WHEN 'Old Faithful' THEN REGEXP_SUBSTR(text_orig_yep, text_pattern, 1, 1, '', 1)||' is AWESOME!'
               ELSE                     REGEXP_SUBSTR(text_orig_yep, text_pattern, 1, 1, '', 1)||' is ???'
            END
       );
    dbms_output.put_line ( text_repl );
    text_repl :=
       REGEXP_REPLACE (
            text_orig_nay
          , text_pattern
          , CASE REGEXP_SUBSTR(text_orig_nay, text_pattern, 1, 1, '', 1)
               WHEN 'Old Faithful' THEN REGEXP_SUBSTR(text_orig_yep, text_pattern, 1, 1, '', 1)||' is AWESOME!'
               ELSE                     REGEXP_SUBSTR(text_orig_yep, text_pattern, 1, 1, '', 1)||' is ???'
            END
       );
    dbms_output.put_line ( text_repl );
END;
/
show error

Variant 2 (static + function call)
Use REGEXP_SUBSTR to get hold of the capture group contents and feed a function to compute results. This way you can perform complex computations that are impossible or cumbersome to express as a plsql expression.
set serveroutput on
CREATE OR REPLACE FUNCTION test_rreval ( match_1 IN VARCHAR2 ) RETURN VARCHAR2
IS
BEGIN
    RETURN
        CASE match_1
            WHEN 'Old Faithful' THEN match_1||' is AWESOME!'
            ELSE                     match_1||' is ???'
        END
    ;
END test_rreval;
/
show error

DECLARE
    text_orig_yep VARCHAR2(1000) := 'StackOverflow user: Old Faithful';
    text_orig_nay VARCHAR2(1000) := 'StackOverflow user: Some Nobody';
    text_pattern  VARCHAR2(1000) := ':\s*(.*)$';
    text_repl     VARCHAR2(1000);
BEGIN
    text_repl :=
       REGEXP_REPLACE (
            text_orig_yep
          , text_pattern
          , test_rreval ( REGEXP_SUBSTR(text_orig_yep, text_pattern, 1, 1, '', 1) )
       );
    dbms_output.put_line ( text_repl );
    text_repl :=
       REGEXP_REPLACE (
            text_orig_nay
          , text_pattern
          , test_rreval ( REGEXP_SUBSTR(text_orig_nay, text_pattern, 1, 1, '', 1) )
       );
    dbms_output.put_line ( text_repl );
END;
/
show error

Variant 3 (dynamic)
You gain utmost flexibility at the cost of performance and maintainability by generating a dynamic plsql block to produce your result.As a perk you can keep closer to the perl syntax ( but you can tweak variation 2 accordingly ).
set serveroutput on
DECLARE
    text_orig_yep VARCHAR2(1000) := 'StackOverflow user: Old Faithful';
    text_orig_nay VARCHAR2(1000) := 'StackOverflow user: Some Nobody';
    text_pattern  VARCHAR2(1000) := ':\s*(.*)$';
    text_repl     VARCHAR2(1000);
    dyncode       VARCHAR2(32000);
BEGIN
    dyncode := 'DECLARE "$1" VARCHAR2(32000) := :1; BEGIN :outvar := REGEXP_REPLACE ( :text_orig, :text_pattern, CASE "$1" WHEN ''Old Faithful'' THEN "$1"||'' is AWESOME!'' ELSE "$1"||'' is ???'' END ); END;';
    EXECUTE IMMEDIATE dyncode
                USING IN   REGEXP_SUBSTR(text_orig_yep, text_pattern, 1, 1, '', 1)
                    , OUT  text_repl
                    , IN   text_orig_yep
                    , IN   text_pattern
                    ;
    dbms_output.put_line ( text_repl );
    EXECUTE IMMEDIATE dyncode
                USING IN   REGEXP_SUBSTR(text_orig_nay, text_pattern, 1, 1, '', 1)
                    , OUT  text_repl
                    , IN   text_orig_nay
                    , IN   text_pattern
                    ;
    dbms_output.put_line ( text_repl );
END;
/
show error


text:
Q: Redundant definite article? Why do we say

*

*get hold of

*lose sight of

instead of

*

*get the hold of

*lose the sight of

The missing article has always bugged me.

A: There are different ways of approaching this:

*

*on the one hand, English has evolved so that the notion of a "concept in general" is generally expressed without an article;

*but irrespectively of that, set expressions can have arbitrary use of articles (or indeed basically any other part of the expression).

In the second of your expressions at least, it appears to fit with general usage (i.e. point 1). For example, one would say:

Sight is just as important as hearing.

and not:

*The sight is just as important as the hearing.


text:
Q: Is cross validation used for model selection? So this is starting to confuse me a bit. Having for example the following code that trains a GLM model:
glm_sens = train(
  form = target ~ .,
  data = ABT,
  trControl = trainControl(method = "repeatedcv", number = 5, repeats = 10, classProbs = TRUE, summaryFunction = twoClassSummary, savePredictions = TRUE),
  method = "glm",
  family = "binomial",
  metric = "Sens"
)

I expected that this trains a few models and then selects the one that performs best on the sensitivity. Yet when I read up on cross validation most I find is on how it is used to calculate average performance scores.
Was my assumption wrong?

A: caret does train different models, but normally it is done with different hyper-parameters. You can check out an an explanation of the process. Hyper parameters cannot be directly learned from the data so you need the training process. These parameters decide how your model will behave, for example you have lambda in lasso which decides how much regularization applied to the model.
In a glm, there is no hyper-parameter to train. I guess what you are looking for is something to select the best possible linear model out of the many potential variables. You can use step()
fit = lm(mpg ~ .,data=mtcars)
step(fit,direction="back")

Another option is to use leaps with caret, for example an equivalent of the above will be:
train(mpg~ .,data=mtcars,method='leapBackward', trControl=trainControl(method="cv",number=10),tuneGrid=data.frame(nvmax=2:6))

Linear Regression with Backwards Selection

32 samples
10 predictors

No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 30, 28, 28, 28, 30, 28, ...
Resampling results across tuning parameters:

  nvmax  RMSE      Rsquared   MAE
  2      3.299712  0.9169529  2.783068
  3      3.124146  0.8895539  2.750305
  4      3.249803  0.8849213  2.853777
  5      3.258143  0.8939493  2.823721
  6      3.123481  0.8917197  2.723475

RMSE was used to select the optimal model using the smallest value.
The final value used for the model was nvmax = 6.

You can check out more about variable selection using leaps in this website


text:
Q: Too many re-renders. Using switch statement with useState() I have an ErrorBox component that is purely displaying the error with the specified attributes. The expected output should be that depending on the ErrorReason it will display the associated color, icon and info
const ErrorBox = ({ ErrorReason }) => {

  const [status, setStatus] = useState({})
  switch (ErrorReason) {
    case "wrong-password":
      setStatus({
        icon: "lock",
        info: "Incorrect password",
        color: "#fff"
      });
      break;
    case "invalid-email":
      setStatus({
        icon: "cross",
        info: "Invalid email",
        color: "#000"
      });
      break;
    case "too-many-request":
      setStatus({
        icon: "user",
        info: "Too many incorrect requests",
        color: "#bbb"
      });
      break;
  }

  return (

       <Icon
        type={status.icon}
        style={{ color: `${status.color}` }}
      />
      {status.info}

  );
};

A: The problem is that you're starting with the state {} and then immediately modifying it.
You don't need to want state here at all. Just use the error reason:
const ErrorBox = ({ ErrorReason }) => {
  let icon, info, color;
  switch (ErrorReason) {
    case "wrong-password":
      icon = "lock";
      info = "Incorrect password";
      color = "#fff";
      break;
    case "invalid-email":
      icon = "cross";
      info = "Invalid email";
      color = "#000";
      break;
    case "too-many-request":
      icon = "user";
      info = "Too many incorrect requests";
      color = "#bbb";
      break;
    default:
      // Must throw here
      throw new Error(`Invalid ErrorReason: ${ErrorReason}`);
  }

  return (

       <Icon
        type={icon}
        style={{ color: `${color}` }}
      />
      {info}

  );
};

But if you did need state, you'd do the switch first and then use the value as the initial value of the state:
// If you needed state for some reason (you don't below)
const ErrorBox = ({ ErrorReason }) => {

  let initialStatus;
  switch (ErrorReason) {
    case "wrong-password":
      initialStatus = {
        icon: "lock",
        info: "Incorrect password",
        color: "#fff"
      };
      break;
    case "invalid-email":
      initialStatus = {
        icon: "cross",
        info: "Invalid email",
        color: "#000"
      };
      break;
    case "too-many-request":
      initialStatus = {
        icon: "user",
        info: "Too many incorrect requests",
        color: "#bbb"
      };
      break;
    default:
      // Must throw here
      throw new Error(`Invalid ErrorReason: ${ErrorReason}`);
  }
  const [status, setStatus] = useState(initialStatus);

  return (

       <Icon
        type={status.icon}
        style={{ color: `${status.color}` }}
      />
      {status.info}

  );
};

I don't think I'd use a switch to map the ErrorReason to error information at all, I'd use a map (or an object created with Object.create(null)):
const statusInfoMap = new Map([
  [
    "wrong-password",
    {
        icon: "lock",
        info: "Incorrect password",
        color: "#fff"
    }
  ],
  [
    "invalid-email",
    {
      icon: "cross",
      info: "Invalid email",
      color: "#000"
    }
  ],
  [
    "too-many-request",
    {
      icon: "user",
      info: "Too many incorrect requests",
      color: "#bbb"
    }
  ]
]);

Then the component is just:
const ErrorBox = ({ ErrorReason }) => {
  const status = statusInfoMap.get(ErrorReason);
  if (!status) {
    throw new Error(`Invalid ErrorReason: ${ErrorReason}`);
  }

  const {icon, color, info} = status;
  return (

       <Icon
        type={icon}
        style={{ color: `${color}` }}
      />
      {info}

  );
};

Live Example:

const {useState, useCallback} = React;

const statusInfoMap = new Map([
  [
    "wrong-password",
    {
        icon: "lock",
        info: "Incorrect password",
        color: "#fff"
    }
  ],
  [
    "invalid-email",
    {
      icon: "cross",
      info: "Invalid email",
      color: "#000"
    }
  ],
  [
    "too-many-request",
    {
      icon: "user",
      info: "Too many incorrect requests",
      color: "#bbb"
    }
  ]
]);

const ErrorBox = ({ ErrorReason }) => {
  const status = statusInfoMap.get(ErrorReason);
  if (!status) {
    throw new Error(`Invalid ErrorReason: ${ErrorReason}`);
  }

  const {icon, color, info} = status;
  return (

       icon: {icon}, color: {color}, info: {info}

  );
};

const errors = [
  "wrong-password",
  "invalid-email",
  "too-many-request",
];
const Example = () => {
    const [index, setIndex] = useState(0);
    const error = errors[index];

    const onClick = useCallback(() => {
        setIndex(index + 1);
    }, [index]);

    return (

            <ErrorBox ErrorReason={error} />
            {index < errors.length - 1
            ? <input type="button" value="Next" onClick={onClick} />
            : <input type="button" value="Start Again" onClick={() => setIndex(0)} />
            }

    );
};

ReactDOM.render(<Example />, document.getElementById("root"));

Or if you need state for something you haven't shown:
const ErrorBox = ({ ErrorReason }) => {
  const initialStatus = statusInfoMap.get(ErrorReason);
  if (!initialStatus) {
    throw new Error(`Invalid ErrorReason: ${ErrorReason}`);
  }
  const [status, setStatus] = useState(initialStatus);

  const {icon, color, info} = status;
  return (

       <Icon
        type={icon}
        style={{ color: `${color}` }}
      />
      {info}

  );
};

A: You should perform state update only when ErrorReason changes. In this scenario use useEffect hook and add ErrorReason as dependency.
useEffect(() => {
 switch (ErrorReason) {
    case "wrong-password":
      setStatus({
        icon: "lock",
        info: "Incorrect password",
        color: "#fff"
      });
      break;
    case "invalid-email":
      setStatus({
        icon: "cross",
        info: "Invalid email",
        color: "#000"
      });
      break;
    case "too-many-request":
      setStatus({
        icon: "user",
        info: "Too many incorrect requests",
        color: "#bbb"
      });
      break;
  }
}, [ErrorReason])

Update:
To avoid local state and variables.
const ErrorBox = ({ ErrorReason }) => {

  const getData = () => {
switch (ErrorReason) {
    case "wrong-password":
      return ({
        icon: "lock",
        info: "Incorrect password",
        color: "#fff"
      });
    case "invalid-email":
      return ({
        icon: "cross",
        info: "Invalid email",
        color: "#000"
      });
    case "too-many-request":
      return ({
        icon: "user",
        info: "Too many incorrect requests",
        color: "#bbb"
      });
  }}

  return (

       <Icon
        type={status.icon}
        style={{ color: `${status.color}` }}
      />
      {getData().info}

  );
};


text:
Q: Spring setting property from code while having bean's name in short... my aspect catches an invocation (by @Before).
I can get from joinpoint the bean's name
 myapp.dao.BookRepository

in spring xml it looks like that:
<bean id="bookRepo" class="myapp.dao.BookRepository">
    <property name="dataSource" ref="dataSource" />
</bean>

All I want to do is to set that property like below in invoked method.
Locally in that class I can do it like that (first line in method body):
@Override
public Collection<Book> getAll() {
    jdbcTemplate.setDataSource(dataSource); // this line I want to move to the aspect
    return jdbcTemplate.query("select * from Book", new RowMapper<Book>() {
        public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
            return extractBook(rs);
        }
    });
}

Unfortunately I had to do it in that aspect. It should also be said that I have many other classes which inherit that method, so I can't just cast it without large switch (check bean name and cast to apropriate class).
 Please let me know if something like this is possible in Spring.

A: I believe you are not using Aspects where you shall! It doesn't seem a problem which shall be handled by AOP to me.
Do you have multiple data-sources? If you have just one data-source just inject the datasource in Spring XMLs, and configure JdbcTemplate there.
If you have multiple data-sources, don't use a jdbcTemplate as field in your class, otherwise you will face strange bugs in concurrent environment, because each thread sets its own data-source in a single jdbcTemplate and....


text:
Q: the difference between the present perfect simple and continuous - She's been playing tennis since she was eight
She's been playing tennis since she was eight.

Does the meaning of the sentence above change if I use the present perfect simple as below?

She's played tennis since she was eight.

A: In this case, there is no significant change in meaning.

She's played tennis since she was eight.

could be used if she played all that time, but has now stopped, while the first form could not. But standing alone, it would never be interpreted that way.

She's played tennis since she was eight, but now she devotes all her time to social media.

adds the context to mark the action of playing tennis as completed and wholly in the past.


text:
Q: jQuery JSONP request of image gets 403 error OK I have a simple script at http://kleague.org/test/
Type a movie name and it should output the movie name, year, and get the movie poster URL (if there is one, there usually is.)
Well, I just tried it and I got a 403 error on the image. it GOT the image but it didn't display it. What am I doing wrong?
<!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=iso-8859-1" />

    <title>IMDB api</title>

<form method="get" action="#" enctype="text/html" >
<input type="text" id="movie" maxlength="50" /> Search now!

</form>

  Trigger the handler

<textarea id="debug" style="width: 500px;height:150px;border:1px solid black;font-face:typewriter;"></textarea>

<textarea id="more" style="width: 500px;height:150px;border:1px solid red;font-face:typewriter;"></textarea>

A: JSONP requires a function/script to be returned. Loading an image through AJAX has no use. Just appending the image itself will do the trick.


text:
Q: Set cell width of a Datagrid in a c# windows application I have a datagrid in my c# windows application and my code is
private void BindGrid(SmsPdu pdu)
 {
   DataRow dr=dt.NewRow();
   SmsDeliverPdu data = (SmsDeliverPdu)pdu;
   dr[0]=data.OriginatingAddress.ToString();
   dr[1]=data.SCTimestamp.ToString();
   dr[2]=data.UserDataText;
   dt.Rows.Add(dr);
   dataGrid1.DataSource=dt;
  }

And my datagrid looks like this
alt text http://www.freeimagehosting.net/uploads/c368f82e0e.jpg

*

*How to set width of all three columns
sender,time,Message?

A: the simple way: use autosize
otherwise, use the Columns collection to set the size of each column
ADDENDUM:
sorry, I assumed you were using DataGridView, since it replaced DataGrid in .NET 2.0
for DataGrid, it's a little more complex - but google knows all!
http://www.syncfusion.com/faq/windowsforms/search/1004.aspx

A: There is a Width property on the Columns collection:
DataGridView1.Columns(X).Width = Y
Where X is the name or index of the column and Y is the width

A: How about datagrid1.Columns[0].Width?
Look at this class. It has a width property that you can set.
EDIT: Look at this page. And look at the code under AddGridStyle, which shows how to create the mapping & set each of the column style, width etc.
Hope that helps.
EDIT2: I am writing the following code without compiler (just using reflector & MSDN to look at the documentation). So, please be kind
DataGridTableStyle tableStyle = dataGrid1.TableStyles[0];
GridColumnStylesCollection colStyles = tableStyle.GridColumnStyles[0];

DataGridColumnStyle styleForCol1 = colStyles[0];
styleForCol1.Width = 165;

DataGridColumnStyle styleForCol2 = colStyles[1];
styleForCol1.Width = 125;

The code is derived from what I understood from this page under Remarks , which is quoted below

The System.Windows.Forms..::.DataGrid
  control automatically creates a
  collection of DataGridColumnStyle
  objects for you when you set the
  DataSource property to an appropriate
  data source. The objects created
  actually are instances of one of the
  following classes that inherit from
  DataGridColumnStyle:
  DataGridBoolColumn or
  DataGridTextBoxColumn class.


text:
Q: Which dataType will return the value (37.961498) as it is ? Double didn't work Which dataType will return the value (37.961498) as it is?
I am working in MapView. Where, at present I am setting annotation and hence I have to set CLLocationCoordinate2DMake with some lat and lng parsed from googleAPI (Eg:lat = "37.9615000" and lng = "60.5566000") . I have the values in string, hence I converted the sting to double and then assigned But it didn't help. Please some one help me.
   double int1=[num1s floatValue];
    double int2=[num2s floatValue];
   NSLog(@" %f %f ",int1,int2);
    annotation.coordinate=CLLocationCoordinate2DMake(int1, int2);

actual values are: 37.9615000,60.5566000
Values I get in NSLog:   37.961498, 60.556599
Thanks in advance.
More explanation and reason why I need exact value:
I need to set annotation for china With its lat and lan ( lat = "53.5609740";
        lng = "134.7728099")
But while converting again from string the value changes

A: When converting a string to a double you should be using doubleValue instead of floatValue
double int1=[num1s doubleValue];
double int2=[num2s doubleValue];
NSLog(@" %f %f ",int1,int2);
annotation.coordinate=CLLocationCoordinate2DMake(int1, int2);

also not critical but I wouldn't recommend naming your doubles as int1 and int2 that is likely to cause you confusion at some point

A: annotation.coordinate=CLLocationCoordinate2DMake([nums doubleValue], [int2 doubleValue]);

Try this

A: double int1=[num1s floatValue];
double int2=[num2s floatValue];
NSLog(@" %0.7f %0.7f ",int1,int2);
annotation.coordinate=CLLocationCoordinate2DMake(int1, int2);

Read String Format Specifiers for more info.


text:
Q: B+ Tree builbing from scratch I've being trying to build this b+ tree and was unable to do it. the tree of order 2 (4 maximum nodes & 2 minimum) should have the following entries 23, 65, 37, 60, 46, 92, 48, 71, 56, 59, 18, 21, 10, 74, 78, 15, 16, 20, 24, 28, 39, 43, 47, 50, 69, 75, 8, 49, 33, 38.
This is what I got:
Root:   46
1st Level: {28,46,60}
2nd Level: L1={15,18,23}, L2={37,39}, L3= {48,56}, L4= {71,78}
3rd Level: L11= {8,10},L12= {15,16},L13= {18,20,21},L14= {23,24}, L21= {28,33},L22= {37,38}, L23= {39,43}, L31= {28,33},L32= {37,38},L33= {39,43}, L41= {60,65,69}, L42= {71,74,75}, L43= {78,92}
Please let me know if I made any mistakes.

A: It doesn't look right to me.
You can watch the tree getting generated. Here's the result:


text:
Q: Performing rake tasks in a user data script on AWS ec2 I am trying to fully launch my Rails application as part of the user data script passed to the launch instance EC2 API. The script sets proper keys, downloads the app from my git repo, and then it should run some initialization scripts, starting with the:
bundle install

which should install all the missing gems. However, it fails. Other commands work just fine.
Original failure was that it could not find the bundle command, I have fixed that by manually setting environment variables, but still Ruby wasn't able to find the bundler gem.
My problem here is that when I ssh (once the user data script has failed) to the launched instance, bundler work with no problem. This gives me no way to debug the original problem.
Under which credentials  is user data being executed in ec2? Can this be the problem? Is there some special reason why bundler cannot be called from a bash script?

A: Did you change directories to rails app?
You might try just calling bundle as well. If you haven't already found a solution, I'd try something like this.
#Pipe stdout and stderr to a log file.
exec &> /home/ubuntu/startup.log

DIR=/home/ubuntu/[rails app]

echo "[START UP] change directory: " $DIR
cd $DIR

echo "[START UP] Update code"
sudo -u ubuntu git pull origin master

echo "[START UP] Bundling latest codebase"
bundle


text:
Q: TypeError: App.check_stru() missing 1 required positional argument: 'self' Olá
Eu estou a tentar criar uma app em python
Este é o codigo
#IMPORTS

import os as os

class App:
    def __init__(self):
        self.config_path = os.path.join("config")
        self.account_path = os.path.join("account")
        self.desktop_path = os.path.join("account/desktop")
        self.book_shelf_path = os.path.join("account/desktop/books_shelf")
        self.storage_books = os.path.join("config/storage")
    def check_stru(self):
        self.was_created = 0
        self.already_created = 0
        if not os.path.exists(self.config_path):
            os.mkdir(self.config_path)
            print("1 created")
            self.was_created += 1
        else:
            self.already_created += 1
        if not os.path.exists(self.account_path):
            os.mkdir(self.account_path)
            print("2 created")
            self.was_created += 1
        else:
            self.already_created += 1
        if not os.path.exists(self.desktop_path):
            os.mkdir(self.desktop_path)
            print("3 created")
            self.was_created += 1
        else:
            self.already_created += 1
        if not os.path.exists(self.book_shelf_path):
            os.mkdir(self.book_shelf_path)
            print("4 created")
            self.was_created += 1
        else:
            self.already_created += 1
        if not os.path.exists(self.storage_books):
            os.mkdir(self.storage_books)
            print("5 created")
            self.was_created += 1
        else:
            self.already_created += 1

run = App

run.check_stru()

Mas não sei muito bem mas dá o seguinte erro:
    Traceback (most recent call last):
  File "none\src\main.py", line 48, in <module>
    run.check_stru()
TypeError: App.check_stru() missing 1 required positional argument: 'self'

Podem me ajudar? Eu sou um bocado novo na parte do self e nas classes...
Obrigado

A: Olá, Devilas. Tudo bem?
Faltou acrescentar um parênteses nesta linha:
run = App

Ela deveria ficar assim:
run = App()

Por que isso? No primeiro caso, você está dizendo que run é igual a classe App e não a um objeto que é instância da classe App. Já no segundo caso, há o instanciamento. Você deve fazer o instanciamento com parênteses mesmo que a construção da classe não exija argumentos, o que é o caso da classe que você está utilizando.
Testei aqui e obtive isso na saída:
1 created
2 created
3 created
4 created
5 created


text:
Q: Sharepoint Powershell Online - Delete items by date Hello Im getting this error when executing this. Can you please help me?
foreach($item in $items)
{
   $created = $item["Created"]
   if ($created -lt $days)
   {
      Write-Host  "Title - " $item["Title"] "Created - " $item["Created"]

      $test = $item["ID"]
      write-host $test
      $item["ID"].DeleteObject()
      #$item[].DeleteObject()
   }
}

$context.ExecuteQuery()

Method invocation failed because [System.Int32] does not contain a method
  named 'DeleteObject'.
  At F:\JoshScript\deletebydate.ps1:46 char:2
  +     $item["ID"].DeleteObject()
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : MethodNotFound

A: I recommend you have a look at the SharePoint PnP PowerShell cmdlets, they make lots of small tasks easier to manage.
Here's the same script using their cmdlets
Connect-PnPOnline -Url <tenant>.sharepoint.com

$listName = "Shared Documents"
$items = Get-PnPListItem -List $listName -Fields "Title","Created","ID","GUID"
$days = (Get-Date).AddDays(-7)

foreach($item in $items)
{
    $created = $item["Created"]

    Write-Host "Item created on $created"
    if($created -gt $days)
    {
        continue;
    }

    try
    {
        Remove-PnPListItem -List $listName -Identity $item.Id -Force -ErrorAction Stop
    }
    catch
    {
        Write-Host "Unable to delete $($item.Id) in list $listName"
    }
}

If you are running Windows 10, then simply run
Install-Module -Name SharePointPnPPowerShellOnline

and it will download and install them from here.


text:
Q: Cannot download R Really stupid issue, apologies in advance. I am trying to download R since yesterday since I had a clean install on my computer. I cannot seem to access the site. All other pages of CRAN work, but when I want to access https://cran.r-project.org/bin/windows/base/ I get the error:
Object not found!

 The requested URL was not found on this server. The link on the referring
 page seems to be wrong or outdated. Please inform the author of that page
 about   the error.

If you think this is a server error, please contact the webmaster.

Error 404

cran.r-project.org
Apache/2.4.10 (Debian)

Since it has been nearly a day I was wondering if there is something I can do, or an alternative R mirror?
Edit: should specify that I had used www.downforeveryoneorjustme.com/ before posting here, which suggested that it is just me (which does not seem to be the case).
Thanks for the helpful replies.

A: You should be able to download it here:
https://cran.cnr.berkeley.edu/


text:
Q: How to read a fixed length file in Spark using DataFrame API and SCALA I have a fixed length file ( a sample is shown below) and I want to read this file using DataFrames API in Spark using SCALA(not python or java).
Using DataFrames API there are ways to read textFile, json file and so on but not sure if there is a way to read a fixed-length file. I was searching the internet for this and found a github link, but I got to download spark-fixedwidth-assembly-1.0.jar for this purpose however I was unable to figure out the jar anywhere. I am completely lost here and need your suggestions and help. There are couple of posts in Stackoverflow but they are not relevant to Scala and DataFrame API.
Here is the file
56 apple     TRUE 0.56
45 pear      FALSE1.34
34 raspberry TRUE 2.43
34 plum      TRUE 1.31
53 cherry    TRUE 1.4
23 orange    FALSE2.34
56 persimmon FALSE23.2

The fixed width of each columns are 3, 10, 5, 4
Please suggest your opinion.

A: The Fixed Length format is very old and I could not find a good Scala library for this format... so I have created my own.
You can check it out here: https://github.com/atais/Fixed-Length
Usage with Spark is quite simple, you would get a DataSet of your objects!
You first need to create a description of your objects, fe:
case class Employee(name: String, number: Option[Int], manager: Boolean)

object Employee {

    import com.github.atais.util.Read._
    import cats.implicits._
    import com.github.atais.util.Write._
    import Codec._

    implicit val employeeCodec: Codec[Employee] = {
      fixed[String](0, 10) <<:
        fixed[Option[Int]](10, 13, Alignment.Right) <<:
        fixed[Boolean](13, 18)
    }.as[Employee]
}

And later just use the parser:
val input = sql.sparkContext.textFile(file)
               .filter(_.trim.nonEmpty)
               .map(Parser.decode[Employee])
               .flatMap {
                  case Right(x) => Some(x)
                  case Left(e) =>
                         System.err.println(s"Failed to process file $file, error: $e")
                         None
               }
sql.createDataset(input)

A: Well... use substring to break lines. Then trim to remove wheitespaces. And then do whatever you want.
case class DataUnit(s1: Int, s2: String, s3:Boolean, s4:Double)

sc.textFile('your_file_path')
  .map(l => (l.substring(0, 3).trim(), l.substring(3, 13).trim(), l.substring(13,18).trim(), l.substring(18,22).trim()))
  .map({ case (e1, e2, e3, e4) => DataUnit(e1.toInt, e2, e3.toBoolean, e4.toDouble) })
  .toDF


text:
Q: Python dictionary with long key and value names I have a dictionary with entries that would exceed 80 characters and I wanted to know if there is anything wrong in having the value of the key in a new line? ie:
from datetime import date

name = 'NAME'
mdy = date.today().strftime('%m%d%y')
d_my = date.today().strftime('%m-%y')

files = {
    '{}_FirstFile_{}.TXT'.format(name, mdy):
        '{}-FirstReport_{}.xlsx'.format(name, d_my),

    '{}_SecondFile_{}.TXT'.format(name, mdy):
        '{}-SecondReport_{}.xlsx'.format(name, d_my),

    '{}_ThirdFile_{}.TXT'.format(name, mdy):
        '{}-ThirdReport_{}.xlsx'.format(name, d_my),

    '{}_FourthFile_{}.TXT'.format(name, mdy):
        '{}-FourthReport_{}.xlsx'.format(name, d_my)
    }


text:
Q: How to show zoomable/ magnifying part of imageview into another imageview like flipkart? My layout as follows :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/activity_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#ffffff"
>
 <ImageView
    android:layout_width="wrap_content"
    android:layout_height="200dp"
    android:id="@+id/imageViewZooming"
    android:scaleType="fitXY"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

 <utility.ImageMagnifier
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:src="@drawable/banner_image"
    android:id="@+id/imageViewOriginal"
    android:scaleType="fitXY"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/imageViewZooming"
    android:layout_toEndOf="@+id/imageViewZooming"
    />
</RelativeLayout>

My ImageMagnifier.java Code as follows:
public class ImageMagnifier extends ImageView {

private PointF zoomPos;
private boolean zooming = false;
private Matrix matrix;
private Paint paint;
private Bitmap bitmap;
private BitmapShader shader;
private int sizeOfMagnifier = 200;

public ImageMagnifier(Context context) {
    super(context);
    init();
}

public ImageMagnifier(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

public ImageMagnifier(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    zoomPos = new PointF(0, 0);
    matrix = new Matrix();
    paint = new Paint();

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction();

    zoomPos.x = event.getX();
    zoomPos.y = event.getY();

    switch (action) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            zooming = true;
            this.invalidate();
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            zooming = false;
            this.invalidate();
            break;

        default:
            break;
    }

    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!zooming) {
        buildDrawingCache();
    } else {

        bitmap = getDrawingCache();
        shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        paint = new Paint();
        paint.setShader(shader);
        matrix.reset();
        matrix.postScale(2f, 2f, zoomPos.x, zoomPos.y);
        paint.getShader().setLocalMatrix(matrix);
        canvas.drawCircle(zoomPos.x, zoomPos.y, sizeOfMagnifier, paint);

    }
  }
}

I am using above code for magnifying/zooming some part of imageview using touch. But I was unable to see that particular zooming image in another imageview. Here I am using canvas.drawCircle method for zooming.


text:
Q: How can I solve a performance issue in my stored procedure? I have a performance problem with a stored procedure. Because when I check my benchmark's result I realized that "MatchxxxReferencesByIds" has '240.25' ms Average LastElapsedTimeInSecond. How can I improve my procedure?
ALTER PROCEDURE [Common].[MatchxxxReferencesByIds]
    (@refxxxIds VARCHAR(MAX),
     @refxxxType NVARCHAR(250))
BEGIN
    SET NOCOUNT ON;

    BEGIN TRAN

    DECLARE @fake_tbl TABLE (xxxid NVARCHAR(50))

    INSERT INTO @fake_tbl
        SELECT LTRIM(RTRIM(split.a.value('.', 'NVARCHAR(MAX)'))) AS fqdn
        FROM
            (SELECT
                 CAST ('<M>' + REPLACE(@refxxxIds, ',', '</M><M>') + '</M>' AS XML) AS data
            ) AS a
        CROSS APPLY
            data.nodes ('/M') AS split(a)

    SELECT [p].[ReferencedxxxId]
    FROM [Common].[xxxReference] AS [p]
    WHERE ([p].[IsDeleted] = 0)
      AND (([p].[ReferencedxxxType] COLLATE Turkish_CI_AS  = @refxxxType COLLATE Turkish_CI_AS )
      AND [p].[ReferencedxxxId] COLLATE Turkish_CI_AS  IN (SELECT ft.xxxid COLLATE Turkish_CI_AS FROM @fake_tbl ft))

    COMMIT;
END;

A: One can only make assumptions without knowing the table's schema, indexes and data sizes.
Hard-coding collations can prevent the query optimizer from using any indexes on the ReferencedEntityId column. The field name and sample data '423423,423423,423432,23423' suggest this is a numeric column anyway (int? bigint?). The collation shouldn't be needed and the variable's column type should match the table's type.
Finally, a.value can return an int or bigint directly, which means the splitting query can be rewritten as:
declare @refEntityIds nvarchar(max)='423423,423423,423432,23423';

DECLARE @fake_tbl TABLE (entityid bigint PRIMARY KEY, INDEX IX_TBL(Entityid))

INSERT INTO @fake_tbl
SELECT split.a.value('.', 'bigint') AS fqdn
FROM
    (SELECT
            CAST ('<M>' + REPLACE(@refEntityIds, ',', '</M><M>') + '</M>' AS XML) AS data
    ) AS a
CROSS APPLY
    data.nodes ('/M') AS split(a)

The input data contains some duplicates so entityid can't be a PRIMARY KEY.
After that, the query can change to :
SELECT [p].[ReferencedEntityId]
FROM [Common].[EntityReference] AS [p]
WHERE [p].[IsDeleted] = 0
  AND [p].[ReferencedEntityType] COLLATE Turkish_CI_AS  = @refEntityType COLLATE Turkish_CI_AS
  AND [p].[ReferencedEntityId]  IN (SELECT ft.entityid FROM @fake_tbl ft)

The next problem is the hard-coded collation. Unless it matches the column's actual collation, this prevents the server from using any indexes that cover that column. How to fix this depends on the actual data statistics. Perhaps the column's collation has to change or perhaps the rows after filtering by ReferencedEntityId are so few that there's no benefit to this.
Finally, IsDeleted can't be indexed. It's either a bit columns whose values are 1/0 or another numberic column that still contains 0/1. An index that's so bad at selecting rows won't be used by the query optimizer because it's actually faster to just scan the rows returned by the other conditions.
A general rule is to put the most selective index column first. The database combines all columns to create one "key" value and construct a B+-tree index from it. The more selective the key, the fewer index nodes need to be scanned.
IsDeleted can still be used in a filtered index to index only the non-deleted columns. This allows the query optimizer to eliminate unwanted columns from the search. The resulting index will be smaller too, which means the same number of IO operations will load more index pages in memory and allow faster seeking.
All of this means that EntityReference should have an index like this one.
CREATE NONCLUSTERED INDEX IX_EntityReference_ReferenceEntityID
    ON Common.EntityReference (ReferenceEntityId, ReferenceEntityType)
    WHERE IsDeleted =0;

If the collations don't match, ReferenceEntityType won't be used for seeking. If this is the most common case we can remove ReferenceEntityType from the index and put it in an INCLUDE clause. The field won't be part of the index key although it will still be available for filtering without having to load data from the actual table:
CREATE NONCLUSTERED INDEX IX_EntityReference_ReferenceEntityID
    ON Common.EntityReference (ReferenceEntityId)
    INCLUDE(ReferenceEntityType)
    WHERE IsDeleted =0;

Of course, if that's the most common case the column's collation should be changed instead

A: *

*I don't think you need a TRAN.  You are simply "shredding" your comma seperated values into a @variable table.  and doing a SELECT.  TRAN not need here.

*try an exists
SELECT [p].[ReferencedEntityId]
    FROM [Common].[EntityReference] AS [p]
    WHERE ([p].[IsDeleted] = 0)
      AND (([p].[ReferencedEntityType] COLLATE Turkish_CI_AS  = @refEntityType COLLATE Turkish_CI_AS )
      AND EXISTS (SELECT 1 FROM @fake_tbl ft WHERE ft.entityid COLLATE Turkish_CI_AS =  [p].[ReferencedEntityId] COLLATE Turkish_CI_AS  )

3.
See https://www.sqlshack.com/efficient-creation-parsing-delimited-strings/
for different ways to parse your delimited string.
quote from article:

Microsoft's built-in function provides a solution that is convenient
  and appears to perform well. It isn't faster than XML, but it clearly
  was written in a way that provides an easy-to-optimize execution plan.
  Logical reads are higher, as well. While we cannot look under the
  covers and see exactly how Microsoft implemented this function, we at
  least have the convenience of a function to split strings that are
  shipped with SQL Server. Note that the separator passed into this
  function must be of size 1. In other words, you cannot use
  STRING_SPLIT with a multi-character delimiter, such as '","'.

*post a screen shot of your execution plan.  if you don't have proper index (or you have "hints" that prevent use of indexes)..your query will never perform well.

A: Based on the execution plan of the stored procedure, what makes it to perform slowly, is the part where you are going to work with XML.
Lets rethink about the solution:
I have created a table like this:
CREATE TABLE [Common].[EntityReference]
(
    IsDeleted BIT,
    ReferencedEntityType VARCHAR(100),
    ReferencedEntityId VARCHAR(10)
);
GO

and manipulate it like this(Insert 1M records into it):
DECLARE @i INT = 1000000;
DECLARE @isDeleted BIT,
        @ReferencedEntityType VARCHAR(100),
        @ReferencedEntityId VARCHAR(10);
WHILE @i > 0
BEGIN
    SET @isDeleted =(SELECT @i % 2);
    SET @ReferencedEntityType = 'TEST' + CASE WHEN @i % 2 = 0 THEN '' ELSE CAST(@i % 2 AS VARCHAR(100)) END;
    SET @ReferencedEntityId = CAST(@i AS VARCHAR(10));
    INSERT INTO [Common].[EntityReference]
    (
        IsDeleted,
        ReferencedEntityType,
        ReferencedEntityId
    )
    VALUES (@isDeleted, @ReferencedEntityType, @ReferencedEntityId);

    SET @i = @i - 1;
END;

lets analyse your code:
You have a comma delimited input(@refEntityIds), which you want to split it and then run a query against these values. (your SP's subtree cost in my PC is about 376) To do so you have different approaches:
1.Pass a table variable to stored procedure which contains the refEntityIds
2.Make use of STRING_SPLIT function to split the string
Lets see the sample query:
INSERT INTO @fake_tbl
      SELECT value
        FROM STRING_SPLIT(@refEntityIds, ',');

Using this, you will gain a great performance improvement in your code.(subtree cost: 6.19 without following indexes) BUT this feature is not available in SQL Server 2008!
You can use a replacement for this function(read this: https://stackoverflow.com/a/54926996/1666800) and changing your query to this(subtree cost still is about 6.19):
INSERT INTO @fake_tbl
    SELECT value FROM dbo.[fn_split_string_to_column](@refEntityIds,',')

In this case again you will see the notable performance improvement.
You can also create a non clustered index on [Common].[EntityReference] table, which has a little performance improvement too. But please think about creating index, before creating it, it might have negative impact on your DML operations:
CREATE NONCLUSTERED INDEX [Index Name] ON [Common].[EntityReference]
(
    [IsDeleted] ASC
)
INCLUDE ([ReferencedEntityType],[ReferencedEntityId])

In case that I have not this index(Suppose that I have replaced your split solution with mine), the subtree cost is: 6.19, When I add aforementioned index, the subtree cost decreased to 4.70, and finally when I change the index to following one, the subtree cost is 5.16
CREATE NONCLUSTERED INDEX [Index Name] ON [Common].[EntityReference]
(
    [ReferencedEntityType] ASC,
    [ReferencedEntityId] ASC
)
INCLUDE ([IsDeleted])

Thanks to @PanagiotisKanavos following index will even performs better than the aforementioned ones (subtree cost: 3.95):
CREATE NONCLUSTERED INDEX IX_EntityReference_ReferenceEntityID
    ON Common.EntityReference (ReferencedEntityId)
    INCLUDE(ReferencedEntityType)
    WHERE IsDeleted =0;

Also please note that, using transaction against a local table variable has almost no effect, and probably you can simply ignore it.

A: If [p].[ReferencedEntityId] is going to be integers, then you don't need to apply COLLATE clause. You can directly apply IN condition.

*

*You can go for simple comma separated values to integers list using Table valued functions. There are many samples. Keep the datatype of the ID as integer, to avoid collation application.

[p].[ReferencedEntityId] IN (SELECT ft.entityid AS FROM @fake_tbl ft))


text:
Q: Confuse about responsive image use cases In the Responsive Use Case, I confused about the Resolution-based selection and Viewport-based selection. I think they are the same.
I think they are both talking about choosing the appropriate size image for the specify screen size. If big size image apply to small mobile device, bandwidth and performance will be wasted.
Am I right? If I'm wrong, what exactly the differences between Resolution-based selection and Viewport-based selection?


text:
Q: Laravel Nova 404 at source map files In my Chrome DevTools I see this Erros:
DevTools failed to load source map: Could not load content for http://xxx.yyy.net.local/nova-api/styles/filter.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load source map: Could not load content for http://xxx.yyy.net.local/nova-api/scripts/filter.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

How can I find out why this errors appear?
I use v3.32.0 version of Laravel Nova.

A: Both map files exist? if yes check in the end of both files, maybe you need to change the reference path.


text:
Q: PCRE Regex - Match everything to the first pipe not enclosed by square brackets I have the following line of text, where I am trying to extract everything up to the first pipe character that is not enclosed in square brackets.
action=search sourcetype=audittrail [ localop | stats count | eval search_id = replace("$top10_drilldown_sid$", "^remote_[^_]*_", "") | table search_id ] [ localop | stats count | eval earliest = $top10_drilldown_earliest$ - 86400 | table earliest ] latest="$top10_drilldown_latest$" | stats values(savedsearch_name) AS search_name

Expected output:
action=search sourcetype=audittrail [ localop | stats count | eval search_id = replace("$top10_drilldown_sid$", "^remote_[^_]*_", "") | table search_id ] [ localop | stats count | eval earliest = $top10_drilldown_earliest$ - 86400 | table earliest ] latest="$top10_drilldown_latest$"

i.e. Everything but the trailing | stats values(savedsearch_name) AS search_name
Following some lookaround examples, I could (nearly) get what I needed using a JavaScript Regex expression
/.*\|(?![^\[]*\])/g - http://refiddle.com/refiddles/596dec4c75622d608f290000
But this didn't translate well into a PCRE-compatible expression that worked (plus I want to capture everything up to, but not including, the first pipe).
From what I've read, the nested square brackets in the first bracketed set may be a complication that can't be worked around? There would only be one level of nested brackets in any given set (e.g. [..[]..] or [..[]..[]..])
I admit that I don't think I've got my head fully around positive & negative lookarounds, but any help would be greatly appreciated!

A: In this kind of situation, it's more efficient to match all that isn't the delimiter than trying to split:
(?=[^|])[^][|]*(?:(\[[^][]*+(?:(?1)[^][]*)*+])[^][|]*)*

demo
details:
(?=[^|]) # lookahead: ensure there's at least one non pipe character at the
         # current position, the goal is to avoid empty match.
[^][|]* # all that isn't a bracket or a pipe
(?:
    (  # open the capture group 1: describe a bracket part
        \[
         [^][]*+ # all that isn't a bracket (note that you don't have to care
                 # about of the pipe here, you are between brackets)
         (?:
             (?1)  # refer to the capture group 1 subpattern (it's a recursion
                   # since this reference is in the capture group 1 itself)
             [^][]*
         )*+
         ]
    ) # close the capture group 1
    [^][|]*
)*

If you need empty parts too, you can rewrite it like this:
(?=[^|])[^][|]*(?:(\[[^][]*+(?:(?1)[^][]*)*+])[^][|]*)*|(?<=\|)


text:
Q: Monit cannot read content I've installed the latest version of Monit and created a very basic rule:
alert me when the word "Google" cannot be found on google.com (deface check).
I keep getting following error:
failed to [www.google.com]:443/ type TCP/IP using SSL/TLS protocol HTTP
Should I open some kind of different port if I want to check the content?
Without the content rule it's working just fine.
I already tried opening port 80 and 443.
    check host google with address srv1.google.com
  if failed url http://www.google.com
    content == "Google"
    with timeout 20 seconds for 2 cycles then alert

Monit is hosted on a Synology NAS.

A: Here you are trying to access http://www.google.com but it seems google is now only supporting httpS.
Try to change your rule to use HTTPS:
if failed url https://www.google.com

Syntax is more like (didn't try to validate it so not sure)
check host google with address srv1.google.com
  if failed
    port 443
    protocol https
    content = "Google"
       with timeout 20 seconds for 2 cycles then alert


text:
Q: for vs while loop python ¡Hola! Soy nuevo en python y sageMath y estoy intentando resolver un ejercicio con mi compañero, el caso es que necesitamos una lista de cuadrados perfectos y he pensado que podría hacerlo de esta manera.
n =95
squares=[]
edges=[];
for i in range(int(sqrt(n)+1)):
    squares.append(i*i)

Entonces leí que sería una buena idea usar el bucle while porque estoy iterando hasta que la condición int(sqrt(n)+1) deje de ser cierta lo cual tiene sentido, por lo tanto esto sería lo que creo que es el código equivalente.
n =95
squares=[]
edges=[]
i=0
root= int(sqrt(n)+1)
while i < root:
    squares.append(i*i)

Sin embargo obtengo un error Traceback (most recent call last) en diferentes partes del código cada vez que lo ejecuto o tarda demasiado. Cualquier ayuda será apreciada ya que soy nuevo, muchísimas gracias!

A: si lo que quieres es generar una lista de todos los cuadrados perfectos hasta n,
te basta con un for, por que iteramos sobre un range(n)
el rpimer error que se aprecia es que cuadrados no esta definido,lo que defines es squares con eso nos basta
squares = []
for i in range(n):
    squares.append(i*i)

se podria utilizar un while pero la estructura seria mas compleja:
i = 0
squares = []
while i < n:
    squares.append(i*i)
    i += 1


text:
Q: Azure CLI Windows VM creation os disk size I've been trying to create a Windows Server 2016 VM with an os disk that is less than the default of size 128GB using the azure cli.
Below is a sample of what I've executed with simplified parameter names
az vm create  --name 'dWeb02-vm' --resource-group 'dev-rg' --admin-password 'ComplexPassword' --admin-username 'dwebadm' --availability-set 'dev-as' --image 'Win2016Datacenter' --location 'northeurope' --nics 'dev-nic' --size 'Standard_B1ms' --os-disk-size-gb '32' --storage-sku 'StandardSSD_LRS'

This results in a VM being created with a managed disk but the size of the disk is 127GB and I get a Resize error on script execution
Deployment error
Deployment failed. Correlation ID: 0c0f1476-8464-444e-91e1-52de3631a64f. {
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "ResizeDiskError",
        "message": "Resource with id THE RESOURCE ID."
      }
    ]
  }
}

Is it possible to create an OS disk that is less than 128GB for a windows VM?

A: We actually released a Windows Server Edition that uses a smaller disk instead of the default 128GB. Managed disks cannot be resized down, only up. So if you want to deploy a smaller OS disk on Windows Server you should use any of the images with [smalldisk] in the image name

If deploying to CLI or PowerShell you can use the following doc to navigate the available images and find the ones that support small disk
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/cli-ps-findimage#navigate-the-images


text:
Q: Globalization of windows application in vb.net I have a richtextbox and combobox in my form. the richtext box contain some data and combobox has following items like
english
hindi
gujrati
marathi
urdu

So I want whenever user select any of these language then whole data of Richtextbox convert into that language which is user selected. I tried in google api but I want to do that without an internet connection.
Because all users don't have an internet connection due to some reasons. Please help me out.

A: Its ok to support multiple languages in your applications by changing the label text etc to the language required by the user and its easy too.. Because you know which words have to be translated.But dont think you can easily translate any random user input to any language all by yourself and that too offline.Programs like Google translate uses complex algorithms (rather than simple text replcement) and relies on websites written in other languages to chose the best match.

A: If the text in the Richtextbox is dynammic and either inserted by the user or modified by the user then you could try FreeTranslator or Lingoes, although I don't think either have an API that you can integrate with your application and I'm not positive if they support the languages you are looking for.
If the text is static, there are many resources available on how to do this, Hanselman has a good initial post and there are probably many links on the page that can lead you to further information.


text:
Q: How to programmatically turn on GPS on Android I have survey some article on stackoverflow.
It seems android version above 4.0 is not able to turn on/off GPS programmatically.
Is there anything changed now? Or is this still not possible?

A: You can't turn it on/off programatically due to security reasons. According to Change location settings docs:

If your app needs to request location or receive permission updates, the device needs to enable the appropriate system settings, such as GPS or Wi-Fi scanning. Rather than directly enabling services such as the device's GPS, your app specifies the required level of accuracy/power consumption and desired update interval, and the device automatically makes the appropriate changes to system settings.

So, the best thing to do is, if the user has disabled the GPS, then for better UX you can show a prompt and redirect the user to the Location activity like this:
MainActivity.Instance.StartActivity(new Intent(ActionLocationSourceSettings));

Where MainActivity.Instance is your current Activity.