text:
Q: How to individually refer to a dynamically generated bootstrap panels with jQuery I'm trying to refer to each individual bootstrap panel that has been generated using a 'for' loop in JavaScript but it doesn't work as expected.
Am trying to change it's border color when it is hovered on. Here's the JavaScript code snippet:
                     /*****For loop starts here******/
                  for (var i = 0; i < data.query.search.length; i++) {
                    var title = data.query.search[i].title;
                    var summary = data.query.search[i].page;
                    $('#article').append('

' + title + '

' + summary + '

');

                    /*********Here is the hover function********/
                    $(".panel").hover(function() {
                      $(this).css({
                        "border": "2px solid rgb(255,145,0)",
                        "cursor": "pointer"
                      });
                    }, function() {
                      $(this).css("border", "1px solid #ccc");
                    });
                    /********Ends here*************************/

                  }

                  /****For loop ends here*****/

The first few panels don't seem to respond to the hover but the others do.
Please what am I doing wrong or rather how do I refer to a dynamically generated bootstrap panels? Thank you.
Here is what am talking about http://codepen.io/ofuochi/full/yOaXgx/
What the code basically does is to fetch Titles from Wikipedia's API based on searched terms. The first three panels don't respond to 'hover' but the rest do. I don't know what exactly am doing wrong.

A: #searchRow element is set to position:absolute and is above your panels.
You could position #searchRow better or set .panel to position:relative and z-index above that of #searchRow.
JavaScript is not at fault here although it too could be improved.
If this is all you want from hover I would suggest to do that with css.

A: Use css
#searchRow{
   display: table;
    position: absolute;
/*     height: 100%; *///remove
    width: 100%;
}

    .panel:hover {
       border: 2px solid rgb(255,145,0);
       cursor: pointer;
    }

http://codepen.io/anon/pen/yJpYqJ

A: Try this way,
$("#article > .panel").on("mouseover", function () {
//stuff to do on mouseover
});

A: You should attach the event handler for hover after the loop, not every time inside the loop.
for (var i = 0; i < data.query.search.length; i++) {
    var title = data.query.search[i].title;
    var summary = data.query.search[i].page;
    $('#article').append('

' + title + '

' + summary + '

');
}

$(".panel").hover(function () {
    $(this).css({
        "border": "2px solid rgb(255,145,0)",
        "cursor": "pointer"
    });
}, function () {
    $(this).css("border", "1px solid #ccc");
});


text:
Q: Clearing an array content and reactivity issues using Vue.js A few years ago it was bad practice to do
array = [];

because if the array was referenced somewhere that reference wasn't updated or something like that.
The correct way was supposed to be array.length = 0;
Anyway, JavaScript has been updated now, and there's a framework called Vue.js
Vue does not catch  array.length = 0; so the property won't be reactive. But it does catch array = [];
Can we use array = []; now, or is JavaScript still broken?

A:
Vue cannot detect the following changes to an array: When you directly
set an item with the index, e.g. vm.items[indexOfItem] = newValue When
you modify the length of the array, e.g. vm.items.length = newLength

From: Reactivity in Depth, For Arrays
So, cleaning a reactive array:
yourArray.splice(0)

A: Doing something like myArray.splice(0) will clear the content of the array and that will also be reactive:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      items: ["a", "b", "c"]
    }
  },
  methods: {
    flush() {
      this.items.splice(0);
    }
  }

});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

{{i}}

  <button @click="flush"> flush</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Visual Studio ignore DefineConstants in csproj? I have a CSPROJ in which I define my own constant / compiler directive.
<PropertyGroup>
    <DefineConstants>$(DefineConstants);MY_DIRECTIVE</DefineConstants>
    <MY_DIRECTIVE>true</MY_DIRECTIVE>
</PropertyGroup>

Then I proceed to include its use somewhere in my application, like this:
#if MY_DIRECTIVE
    System.Console.WriteLine("Yes");
#else
    System.Console.WriteLine("No");
#endif

Picture:

That works fine after building and running the application, but Visual Studio has both lines (Yes and No) highlighted, so if I were to do something like <MY_DIRECTIVE>false</MY_DIRECTIVE>, Visual Studio should "hide" and grey out and ignore the line where it says System.Console.WriteLine("Yes");, shouldn't it? I would expect it to, but it doesn't. Am I doing something wrong?

A: This is not going to work because the MSBuild property (<MY_DIRECTIVE>true</MY_DIRECTIVE>) has nothing to do with the C# preprocessor directive (<DefineConstants>$(DefineConstants);MY_DIRECTIVE</DefineConstants>) - these are two independent concepts.
If you want to trigger the #else branch you have to bring these concepts together, e. g.:
<PropertyGroup>
    <MY_DIRECTIVE>true</MY_DIRECTIVE>
    <DefineConstants Condition="'$(MY_DIRECTIVE)' == 'true'">$(DefineConstants);MY_DIRECTIVE</DefineConstants>
</PropertyGroup>


text:
Q: one django project - render different content depending on domain I seem to be using django's site framework. :) BUT. here what I dont understand:
How to write dynamic views to check current domain and render proper content to that domain
what I did is: (I have one single django project with single settings.py)

*

*created 2 extra settings__domainname.py files with SITE_ID set to respective ID of Site object in db

*in view:
if get_current_site(self.request).domain == "domain-usa.com":
  context['allnews'] = News.objects.filter(country='USA')
elif get_current_site(self.request).domain == "domain-hun.com":
  context['allnews'] = News.objects.filter(country='Hungary')

I am running the dev server like ./manage.py runserver --settings=myproj.settings_domainname
But I am hard-coding it anyways, i want my views to check and get content totally dynamically without any hardcoding.
How can I achieve this? I am trying to make the life of my coworkers (who may want create new domain thru admin) and of mine (have to hardcode in views) easy.
any guidance is greatly appreciated.
EDIT - almost the solution:.
I extended the Site Model like this:
class CustomSite(models.Model):
   sites = models.OneToOneField(Site, null=True, related_name='customsite')
   COUNTRY_CHOICES = (
       ('en', 'USA'),
       ('de', 'Germany'),
       ('es', 'Spain'),
       ('ru', 'Russia'),
       ('fr', 'French')
   )
   country = models.CharField(max_length=3, choices=COUNTRY_CHOICES)
   def __unicode__(self):
       return 'Country of {0}'.format(self.sites.domain)

and in view, I can do:
country_ofdomain = get_current_site(self.request).customsite.country
news_for_this_country = News.objects.filter(country=country_ofdomain)

Does this make sense? Aaand, as usual, any feedback is greatly appreciated.

A: You can edit you hosts file (/etc/hosts in unix, mac or C:/windows/system32/drivers/etc/hosts at windows)  and add some domains, like this:
127.0.0.1    domain-usa.com
127.0.0.1    domain-hun.com

after this, run dev server as public (python manage.py runserver 0.0.0.0:8000)
and go to url http://domain-usa.com:8000/
get_current_site look at SITE_ID in your settings, but you need to get request.META['HTTP_HOST'] variable, and get domain from it.


text:
Q: how to find all directories with a certain name on an unix shell, how can i find all directories with a certain name?
say i have a folder structure like
/home/abcd/foo/
/home/abcd/foo/bar
/home/xyz/ab/foo/
/home/none/in/here

and i am searching for folders named foo, i would want to return a list like:
/home/abcd/foo/
/home/xyz/ab/foo/

how could i do this?
thanks

A: find /home -name foo -type d


text:
Q: Auto-size TextView with API before 26 I am trying to auto-size my TextView to fit in a specific width on one line, it was quite easy for API 26 and above, however, I want to support my app for use with APIs back to Lolipop. I am having a hard time trying to do this with java code. Can anyone help me? Thank you.

A: Yes you can !
replace
android:autoSizeTextTyp="uniform"

with :
app:autoSizeTextType="uniform"

(At least working on sdk 23, with a simple TextView)

A: You can use the support library for older APIs
https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html

A: May be it 'll work for you. This is the Library,
https://github.com/grantland/android-autofittextview


text:
Q: Python MySQLdb convert list data for CSV output from SELECT I am struggling with the following (relatively simple) problem. I have am using SELECT query in MySQLdb which returns the following data:
select * from extension_recording where filename = "20091030_135711-out.wav";
+----+--------------+------+-------------------------+----------+--------+--------------------+---------------------------+--------+-----------------+------+-------+
| id | extension_id | flow | filename                | filesize | unread | cr_date             | callerid                  | length | callid          | info | party |
+----+--------------+------+-------------------------+----------+--------+---------------------+---------------------------+--------+-----------------+------+-------+
|  1 |           41 | out  | 20091030_135711-out.wav |   264684 | 1      | 2009-10-30 13:57:31 | Some user <01273123456> |     20 | 1256911031.5482 |      | NULL  |
+----+--------------+------+-------------------------+----------+--------+---------------------+---------------------------+--------+-----------------+------+-------+

I am trying to use it in the following way:
cur.execute ("SELECT * FROM extension_recording WHERE filename = %s;", (file))
csv_result = cur.fetchone()
csv_list.append ([csv_result])

This results in a list with Python data types:
print csv_list
(1L, 41L, 'out', '20091030_135711-out.wav', 264684L, '1', datetime.datetime(2009, 10, 30, 13, 57, 31), 'Some user <01273123456>', 20L, '1256911031.5482', '', None)

I need to output the data to CSV as MySQL data types, therefore I need to convert each field appropriately, i.e. convert the id and extension_id fields to ints rather than longs and convert the date to a string. The point of all this is that I end up with a CSV file something like this:
1,41,'out','20091030_135711-out.wav',264684,'1','2009-10-30 13:57:31','Some user <01273123456>',20,'1256911031.5482','',None

I can see that I may need to iterate through csv_result but I can't for the life of me see how to do it differently for each data type.

A: You could use the csv module to do the conversion back to string automatically after the fact, or you could initialize your Connection object with a custom conv value to override the default type conversion dictionary to give you everything as the raw strings returned from MySQL.  Just realize that means you'll have to do all conversion manually, or have a second auto-conversion connection to the same DB, if you want automatic type conversion at any other point in your code.

A: Why are those values peculiar? MySQLdb does automatic conversion into python types (int becomes long, DATE becomes datetime, etc...). Just csv the tuple returned:
import csv
with open('file.csv', 'wb') as csvfile:
    csv_ = csv.writer(csvfile)
    csv_.writerow(csv_list)

This does everything you need.
(If you need quotes, add the quotechar="'", quoting = csv.CONSTANTHERE keywords)
File contents:
1,41,out,20091030_135711-out.wav,264684,1,2009-10-30 13:57:31,Some user <01273123456>,20,1256911031.5482,,

(note: None is an empty string using this.)


text:
Q: Acquire Azure token from .Net Core 2.0 controller (Bearer) This is my startup.cs code
services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddAzureAdBearer(configureOptions =>
{
    configureOptions.Instance = Environment.GetEnvironmentVariable("AD_Instance");
    configureOptions.Domain = Environment.GetEnvironmentVariable("AD_Domain");
    configureOptions.TenantId = Environment.GetEnvironmentVariable("AD_TenantId");
    configureOptions.ClientId = Environment.GetEnvironmentVariable("AD_ClientId");
}

JwtBearerDefaults.AuthenticationScheme is Bearer
These are my options:
public void Configure(string name, JwtBearerOptions options)
{
    options.Audience = _azureOptions.ClientId;
    options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = false
    };
    options.SaveToken = true;
}

Now, according to many blogs and Questions & Answers here
I use this code to retrieve the token: (Btw application works fine more than 6 months already, don't consider some set up issues)
var token = _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

And this is what it returns:

What I need is the access_token. ex. Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1...
UPDATE:
After I saw the comments/answers I added await, but I get null as a result.

A: The method GetTokenAsync("access_token") is asynchronous and is returning an System.Threading.Tasks.Task<string> result. So the var here is translating to:
Task<string> token = _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

In order to access the actual result, you need to unpack it from the Task. The easiest way to do this is to use the await keyword:
string token = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");


text:
Q: The return type 'List' isn't a 'Widget', as required by the closure's context I am trying to use ListView.builder and map together. Can i use them together?? I checked the map code without listView.builder and it is working fine. when i use this code with listview.builder to get index value i am getting error. where is the mistake?
final nameAndRollNo = [
    {
      'name': 'Name 1',
      'details': [
        {'Roll No.': 'F101', 'age': 20,},
      ]
    },
    {
      'name': 'Name 2',
      'details': [
        {'Roll No.': 'F102', 'age': 25,},
      ]
    },
```
ListView.builder(
        itemCount: nameAndRollNo.length,
        itemBuilder: (context, index) {
          return (nameAndRollNo[index]['details'] as List<Map<String, dynamic>>)
              .map((value) {
            return ListTile(
              leading: Icon(Icons.person),
              title: Text('Any Name'),
              subtitle: Text(value['Roll No.']),
              trailing: Icon(Icons.delete),
            );
          }).toList();
        },
      ),

A: You can return single widget from itemBuilder, but while you are performing map and creating List<ListTile>, means it can't return list of widget. If you like to wrap them as List, you can wrap items with Column widget.
itemBuilder: (context, index) {
  return Column(
    children: (nameAndRollNo[index]['details']
            as List<Map<String, dynamic>>)
        .map((value) {
      return ListTile(
        leading: Icon(Icons.person),
        title: Text('Any Name'),
        subtitle: Text(value['Roll No.']),
        trailing: Icon(Icons.delete),
      );
    }).toList(),
  );


text:
Q: non vr project with leap motion and ue4 Does anyone know how to setup a leap motion for a non VR project.
Also I want it to be orientated frontside down 45 degrees.
There almost no documentation about this on the internet, anyone some experience?
Many thanks,
Olivierus

A: The Leap controller is already available in UE4 (definitely in 4.14.3 and probably earlier). In the editor, go to Edit->Plugins and search for Leap. That should enable reading the input events.
Next, you need to make arms and fingers articulate to follow the Leap inputs. Tbh I cannot remember if there are Leap-ready models in Engine Content, but once you enable the plugin you should see the Leap content as well. Look in there, or google "getnamo leap ue4" for his old Leap-UE4 implementation. That's where I got my models from.


text:
Q: How to run a Method on the exit of a kivy app I would like to run a Method when the user tries to exit the app , kind of like a "are you sure you want to exit" or "Do you want to save the file" type of message whenever the user tries to exit by clicking the Exit button on top of the window
Some thing like
on_quit: app.root.saveSession()

A: If you want your application to simply run things after the GUI has closed, the easiest and smallest approach would be to place any exit code after TestApp().run(). run() creates a endless loop which also clears any event-data from within kivy so it doesn't hang. That endless loop breaks as soon as the window/gui instance dies. So there for, any code after will execute only after the GUI dies too.
If you want to create a graceful shutdown of the GUI with for instance socket-closing events or a popup asking the user if that's what they really want to do, then creating a hook for the on_request_close event is the way to go:
from kivy.config import Config
Config.set('kivy', 'exit_on_escape', '0')

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.core.window import Window

class ChildApp(App):

    def build(self):
        Window.bind(on_request_close=self.on_request_close)
        return Label(text='Child')

    def on_request_close(self, *args):
        self.textpopup(title='Exit', text='Are you sure?')
        return True

    def textpopup(self, title='', text=''):
        """Open the pop-up with the name.

        :param title: title of the pop-up to open
        :type title: str
        :param text: main text of the pop-up to open
        :type text: str
        :rtype: None
        """
        box = BoxLayout(orientation='vertical')
        box.add_widget(Label(text=text))
        mybutton = Button(text='OK', size_hint=(1, 0.25))
        box.add_widget(mybutton)
        popup = Popup(title=title, content=box, size_hint=(None, None), size=(600, 300))
        mybutton.bind(on_release=self.stop)
        popup.open()

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

Courtesy of pythonic64 who created a gist on the topic in a issue way back when.


text:
Q: Concaternate Array value with Ternary Operator result I'm using PHP 7 and Laravel 6. I got errors when I made a user request rule and used it in user controller. The request rule I made is to be reusable in create and update function, so if i pass the id of user, it will validate the unique of user except that id. But if not, it will search all the ids and validate if it's unique. I follow BaM solution, here: https://stackoverflow.com/a/24205849
This my UserRequest.php:
public static function rules ($id=0, $merge=[]) {
    return array_merge(
        [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users' . ($id ? ",$id" : ''),
            'phone_number' => 'required|string|min:9|max:10|unique:users' . ($id ? ",$id" : ''),
            'user_img' => 'required|mimes:jpeg,jpg,png,gif|max:10000',
        ],
            $merge);
}

This is my UserController:

public function store(Request $request)
  {
    $extend_rules = [
      'pass'       => 'required|string|min:8',
  ];

    $validator = Validator::make($request->all(), UserRequest::rules($extend_rules));

    if ($validator->fails())
    {
      return redirect()->back();
    }

    $user = User::create([
      'name' => $request->name,
      'email' => $request->email,
      'password' => Hash::make($request->pass),
      'phone_number' => $request->phone_number,
      'user_img' => $request->user_image->store('user_img'),
    ]);

    $user->save();

    Session::flash('message', 'Your account is successfully created !');
    Session::flash('alert-class', 'alert alert-success');

    return redirect()->route('users.index');

  }

And I got this errors:
ErrorException: Array to string conversion
I tried to search for solutions but couldn't seem to find anything much my case.
If anyone know, please help me!

A: That's because you're just passing an array while the method accept two different type of parameter
$validator = Validator::make($request->all(), UserRequest::rules(0, $extend_rules)); // <-- you need to either pass 1 or 0 for the id and then $extended rules

// here is your method signature
public static function rules ($id=0, $merge=[]) {


text:
Q: Why is while loop much faster than range in this case? According to this post, range loop should be faster than while loop in python, but please have a look at the following code. It is simply used to test if a number is prime and return the divisor if n is not a prime.
import time

def isPrimeWhile(n):
    i = 2
    while(i <= n/2+1):
        if(n%i == 0):
            return i
        i += 1
    return n

def isPrimeRange(n):
    for i in range(2,n/2+1):
        if(n%i == 0):
            return i
    return n

n = 353591872901

start = time.time()
isPrimeWhile(n)
print("%s while seconds"%(time.time() - start))

start = time.time()
isPrimeRange(n)
print("%s range seconds"%(time.time() - start))

Run the code and you will find the while loop is much faster than the range loop.I am guessing that the range(0,aLargeNumber) takes a very long time to run. But why in the last post mentioned above, the range method is much quicker? Any answers?

A: Since you are using Python 2+ ( your code needs to use integer division to work in Python 3+ ) you are running into the fact that Python 2+ range generates a list of all elements and then iterates over them.
This would explain the differences in time that it takes for the while and range functions to run.
Incedentally the code for Python 3+ needs the following change:
def isPrimeRange(n):
    for i in range(2,n//2+1): # integer division
        if(n%i == 0):
            return i
    return n

 This Python Blog Post  explains in great detail the differences between range (returns a list) and xrange (returns an iterator) in Python 2+ and how Python 3+ has changed this functionality.
A pick of the most relevent paragraph from that source is here:

When you're using an iterator, every loop of the for statement produces the next number on the fly. Whereas the original range() function produced all numbers instantaneously, before the for loop started executing. The problem with the original range() function was that it used a very large amount of memory when producing a lot of numbers. However it tends to be quicker with a small amount of numbers. Note that in Python 3.x, you can still produce a list by passing the generator returned to the list() function.

A: As mentioned by others, the main issue appears to be using range instead of range in Python 2.7.  Using %timeit, both functions are almost the same if one were to use xrange (Python 2.7).
%timeit isPrimeRange(n)
100000 loops, best of 3: 15.2 µs per loop

%timeit isPrimeWhile(n)
100000 loops, best of 3: 15.8 µs per loop

%load_ext line_profiler
%load_ext memory_profiler

from isPrimeRange import isPrimeRange
from isPrimeWhile import isPrimeWhile

n = 353591872901

isPrimeRange: Line Profiler
%lprun -f isPrimeRange isPrimeRange(n)
Timer unit: 1e-06 s

**Total time: 5.5e-05 s**
File: isPrimeRange.py
Function: isPrimeRange at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def isPrimeRange(n):
     2        82           25      0.3     45.5      for i in xrange(2,n/2+1):
     3        82           29      0.4     52.7          if(n%i == 0):
     4         1            1      1.0      1.8              return i
     5                                               return n

isPrimeWhile: Line Profiler
%lprun -f isPrimeWhile isPrimeWhile(n)
Timer unit: 1e-06 s

**Total time: 9e-05 s**
File: isPrimeWhile.py
Function: isPrimeWhile at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           def isPrimeWhile(n):
     4         1            1      1.0      1.1      i = 2
     5        82           34      0.4     37.8      while(i <= n/2+1):
     6        82           31      0.4     34.4          if(n%i == 0):
     7         1            0      0.0      0.0              return i
     8        81           24      0.3     26.7          i += 1
     9                                               return n

Using iPython's memory profiler, you can see that both use the same amount of memory.
isPrimeRange: Memory Profiler
%mprun -f isPrimeRange isPrimeRange(n)
('',)
Filename: isPrimeRange.py

Line #    Mem usage    Increment   Line Contents
================================================
     1     24.2 MiB      0.0 MiB   def isPrimeRange(n):
     2     24.2 MiB      0.0 MiB       for i in xrange(2,n/2+1):
     3     24.2 MiB      0.0 MiB           if(n%i == 0):
     4     24.2 MiB      0.0 MiB               return i
     5                                 return n

isPrimeWhile: Memory Profiler
%mprun -f isPrimeWhile isPrimeWhile(n)
('',)
Filename: isPrimeWhile.py

Line #    Mem usage    Increment   Line Contents
================================================
     3     24.2 MiB      0.0 MiB   def isPrimeWhile(n):
     4     24.2 MiB      0.0 MiB       i = 2
     5     24.2 MiB      0.0 MiB       while(i <= n/2+1):
     6     24.2 MiB      0.0 MiB           if(n%i == 0):
     7     24.2 MiB      0.0 MiB               return i
     8     24.2 MiB      0.0 MiB           i += 1
     9                                 return n

A: you might as well try using
import time

def isPrimeWhile(n):
    i = 2
    while(i <= n/2+1):
        if(n%i == 0):
            return i
        i += 1
    return n

def isPrimeRange(n):
    for i in xrange(2,n/2+1):
        if(n%i == 0):
            return i
    return n

n = 353591872901

start = time.time()
isPrimeWhile(n)
print("%s while seconds"%(time.time() - start))

start = time.time()
isPrimeRange(n)
print("%s while seconds"%(time.time() - start))

1.28746032715e-05 while seconds
6.91413879395e-06 while seconds


text:
Q: Set progress in ProgressWheel for download files I have a list view. When user selects an item of my list view, I open DetailActivity that user can download a file in that activity and I show the user download percentage using ProgressWheel.
My problem is when user closes the activity and then returns back to activity, the ProgressWheel doesn't update anymore.
Here is my code:(I download the file using AsynchTask)
/**
 * Background Async Task to download file
 * */
class DownloadTask extends AsyncTask<String, String, Boolean> {
    /**
     * Downloading file in background thread
     * */
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            URL url = null;
            try {
                String link = params[0];
                fileExtention = getFileExtention(link);
                url = new URL(link);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            // set some parameters for httpUrlConnection
            connection.setConnectTimeout(JSONConstants.CONNECTION_TIMEOUT);
            connection.setReadTimeout(JSONConstants.READ_TIMEOUT);
            connection.connect(); // Connection Complete here.!
            // Get from Server and Catch In Input Stream Object.
            InputStream inputStream = connection.getInputStream();
            int lenghtOfFile = connection.getContentLength();

            String PATH = Environment.getExternalStorageDirectory()
                    + "/download/";
            File file = new File(PATH);
            if (!file.exists()) {
                file.mkdirs();
            }
            File outputFile = new File(file, "fileTitle"
                    + ".mp3" );
            FileOutputStream fileOutputStream = new FileOutputStream(
                    outputFile);

            byte[] buffer = new byte[4096];
            int length = 0;
            long total = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                total += length;
                // publishing the progress....
                // After this onProgressUpdate will be called
                if (lenghtOfFile > 0)
                    publishProgress(""
                            + (int) ((total * 100) / lenghtOfFile));

                // Write In FileOutputStream.
                fileOutputStream.write(buffer, 0, length);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();

        }  catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void publishProgress(String percent) {
        // Sets the progress indicator to a max value, the
        // current completion percentage, and "determinate"
        // state
        downloadProgressWheel.setProgress(Integer.valueOf(percent));

    }

How can I set my ProgressWheel still updated when user returns back to it's associated activity.


text:
Q: how to fix this error ? ionic 3
(node:10624) UnhandledPromiseRejectionWarning: Error: Source path does
  not exist: google-services.json
      at updatePathInternal (D:\ion\Event\platforms\android\cordova\node_modules\cordova-common\src\FileUpdater.js:145:19)
      at D:\ion\Event\platforms\android\cordova\node_modules\cordova-common\src\FileUpdater.js:223:19
      at Array.forEach ()
      at Object.updatePaths (D:\ion\Event\platforms\android\cordova\node_modules\cordova-common\src\FileUpdater.js:221:33)
      at updateFileResources (D:\ion\Event\platforms\android\cordova\lib\prepare.js:431:17)
      at D:\ion\Event\platforms\android\cordova\lib\prepare.js:51:9
      at _fulfilled (D:\ion\Event\platforms\android\cordova\node_modules\q\q.js:854:54)
      at D:\ion\Event\platforms\android\cordova\node_modules\q\q.js:883:30
      at Promise.promise.promiseDispatch (D:\ion\Event\platforms\android\cordova\node_modules\q\q.js:816:13)
      at D:\ion\Event\platforms\android\cordova\node_modules\q\q.js:624:44
  (node:10624) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection. This error originated either by throwing inside of an async
  function without a catch block, or by rejecting a promise which was
  not handled with .catch(). (rejection id: 1) (node:10624) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code.

ionic cordova plugin add cordova-plugin-fcm

cordova plugin add cordova-plugin-fcm --save
  Plugin "cordova-plugin-fcm" already installed on android.

Adding cordova-plugin-fcm to package.json
Saved plugin info for "cordova-plugin-fcm" to config.xml
(node:11704) UnhandledPromiseRejectionWarning: Error: cordova-plugin-fcm: You have installed platform android but file 'google-services.json' was not found in your Cordova project root folder.
    at Object.<anonymous> (D:\ion\Event\plugins\cordova-plugin-fcm\scripts\fcm_config_files_process.js:84:9)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Module.require (internal/modules/cjs/loader.js:650:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at runScriptViaModuleLoader (C:\Users\DINESH\AppData\Roaming\npm\node_modules\cordova\node_modules\cordova-lib\src\hooks\HooksRunner.js:178:20)
    at runScript (C:\Users\DINESH\AppData\Roaming\npm\node_modules\cordova\node_modules\cordova-lib\src\hooks\HooksRunner.js:164:16)
(node:11704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.` <platform name="android">
        <resource-file src="google-services.json"
         target="platforms/android/app/google-services.json" />
    </platform>`


text:
Q: Angular - Update value of a slider from another slider My usecase is as follows:
<ion-row *ngFor="let ag of assetGroupsInScope" >
        <ion-col>
                  <ion-range
                  style="padding-left: 16px; padding-right: 16px;"
                  #sliderGroup
                  class="ion-no-padding"
                  [ngModel]="assetGroupCurrentValue(ag)"
                  #range="ngModel"
                  name="group-{{ ag }}"
                  min="0"
                  [max]="assetGroupMap.get(ag)"
                  pin
                  color="tertiary"
                >
                </ion-range>
            <ion-row *ngFor="let asset of assetGroupIds.get(ag)" class="ion-no-padding">
              <ion-col class="ion-no-padding">

                      <ion-range
                        #sliderAsset
                        class="ion-no-padding"
                        [ngModel]="assetContributionMap.has(asset.id) ? assetContributionMap.get(asset.id) : 0"
                        #range="ngModel"
                        name="value-{{ asset.id }}"
                        min="0"
                        [max]="allAssetvalueMap.get(asset.id)"
                        pin
                        tick
                        color="tertiary"
                        (ionChange)="onChangeSlider(asset, sliderAsset)"
                      >
                      </ion-range>

              </ion-col>
            </ion-row>
        </ion-col>
      </ion-row>

I have an array called assetGroupsInScope. For each assetGroup, I have one slider (Say master slider) for the overall value, and multiple sliders (say child sliders) for assets of the group.
What I want is when the user changes the master slider, code automatically updates the child sliders (some algorithm that ensures the sum of child sliders = master slider) and whenever the user changes any child slider, code automatically update the master slider.
Tried viewchild, elementref, renderer2 and other hacks but can't seem to figure out anything.
What's the best way to solve this?


text:
Q: Shutting down Redis I started up Redis for the first time on my local machine today and then later closed all terminal windows after I shutdown my Rails app. An hour later, I started up the Rails app again and did the following to start the redis server
redis-server /usr/local/etc/redis.conf

However, it told me
# Opening port 6379: bind: Address already in use

I therefore assumed it was still running its earlier instance even though I closed the terminal windows on my Mac.
Looking at this page http://redis.io/commands/shutdown, I tried to run
SHUTDOWN

in the terminal window but I get this response
SHUTDOWN: NOT super-user

I therefore tried (Even though I didn't use sudo to start it)
sudo SHUTDOWN

and after it asked me for my password, it output this
usage: shutdown [-] [-h [-u] [-n] | -r [-n] | -s | -k] time [warning-message ...]

but when I randomly ran shutdown -s it said
 SHUTDOWN: NOT super-user

What's the proper way to shutdown Redis when I close up my app?

A: This is meant to be sent as a command to redis, not to be executed on your terminal.
In this case you can actually just kill redis from the terminal, since upon receiving a SIGTERM signal it will schedule a SHUTDOWN instead of simply exiting.
For reference see the signal handling doc page.

A: Use the built-in redis client: redis-cli shutdown

A: Find out the process id of the Redis instance running on your machine...
> ps aux | grep redis

impadmin 23277  0.0  0.0  35044  1976 pts/2    Sl+  14:19   0:00 src/redis-server

... and then run:
> kill 23277


text:
Q: How to create spark-sql database from jdbc connection I'm using spark-sql, I want to create queries to join different tables from database.
Apache spark and connection is already working
Example:
CREATE TEMPORARY VIEW jdbcTable
USING org.apache.spark.sql.jdbc
OPTIONS (
  url "jdbc:mysql://XXX.XXX.XXX.XXX/mydatabase",
  driver "com.mysql.cj.jdbc.Driver",
  dbtable "mydatabase.mytable1",
  user "XXXX",
  password "xxx"
);
spark-sql> SELECT * FROM jdbcTable;
1       my_data
Time taken: 3.91 seconds, Fetched 1 row(s)

What I need is is something like USE or CREATE mydatabase USING the jdbc connection to be able to run queries with join tables.
Based of the Spark SQL Syntax, I tried the following options:
spark-sql> USE DATABASE mydatabase
         > USING org.apache.spark.sql.jdbc
         > OPTIONS (
         >   url "jdbc:mysql://XXX.XXX.XXX.XXX/mydatabase",
         >   driver "com.mysql.cj.jdbc.Driver",
         >   user "XXXX",
         >   password "xxx"
         > );
Error in query:
mismatched input 'mydatabase' expecting {<EOF>, ';'}(line 1, pos 13)

spark-sql> CREATE DATABASE mydatabase
         > USING org.apache.spark.sql.jdbc
         > OPTIONS (
         >   url "jdbc:mysql://XXX.XXX.XXX.XXX/mydatabase",
         >   driver "com.mysql.cj.jdbc.Driver",
         >   user "XXXX",
         >   password "xxx"
         > );
Error in query:
mismatched input 'USING' expecting {<EOF>, ';'}(line 2, pos 0)

Is there a way to USE or CREATE a database from a jdbc connection in spark-sql command line?

A: The answer is no. Refer to spark official documentation:

The Spark SQL CLI is a convenient tool to run the Hive metastore
service in local mode and execute queries input from the command line.

It cannot directly connect to external mysql service using JDBC.


text:
Q: ctx.fillText isn't doing anything I'm making a website where I want to have text written in the middle of a rectangle. The text will be a number from 1 to 100. For some reason ctx.fillText() isn't doing anything. My canvas isn't small. It's as big as the image that's being drawn on it.
Code:
const ctx = editCanvas.getContext("2d");

const backgroundImage = new Image();

backgroundImage.src = "some random path";

backgroundImage.onload = () => {
    editCanvas.width = backgroundImage.width;
    editCanvas.height = backgroundImage.height;

    ctx.drawImage(backgroundImage, 0, 0);
};

function drawSelectionRect(
    text,
    { x, y, width, height },
    { strokeWidth, lineDash, strokeColor },
    fillColor
) {
    ctx.lineWidth = strokeWidth;
    ctx.setLineDash(lineDash);
    ctx.strokeStyle = strokeColor;

    ctx.strokeRect(x, y, width, height);

    ctx.fillStyle = fillColor;

    ctx.fillRect(x, y, width, height);

    const { width: textWidth, height: textHeight } = ctx.measureText(text);

    ctx.fillStyle = "#000";
    ctx.font = "16px sans-serif";

    ctx.fillText(
        text,
        x + width / 2 - textWidth / 2,
        y + height / 2 - textHeight / 2,
        width
    );
}

A: You might want to double check the return of measureText:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText#return_value
there is nothing height related there...
If we remove those textWidth & textHeight your drawSelectionRect function works.
I believe what you are trying to accomplish is to align the text, perhaps with these, you can do it:

*

*https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign

*https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline
Here is your code with those

const editCanvas = document.getElementById('c');
const ctx = editCanvas.getContext("2d");

function drawSelectionRect(
    text,
    { x, y, width, height },
    { strokeWidth, lineDash, strokeColor },
    fillColor
) {
    ctx.lineWidth = strokeWidth;
    ctx.setLineDash(lineDash);
    ctx.strokeStyle = strokeColor;

    ctx.strokeRect(x, y, width, height);
    ctx.fillStyle = fillColor;
    ctx.fillRect(x, y, width, height);

    console.log(ctx.measureText(text))

    ctx.fillStyle = "#000";
    ctx.font = "16px sans-serif";
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    ctx.fillText(
        text,
        x + width / 2,
        y + height / 2,
        width
    );
}

drawSelectionRect(
  "ooo",
  {x:2, y:2, width:40, height:40},
  {strokeWidth:3, lineDash:[0], strokeColor: "black"},
  "red"
)
<canvas id="c"></canvas>

Remember console.log( is your friend, when you are not sure what is going on, output the variables you are using and see what is not the way you plan it


text:
Q: git: updating an old repo with all of the changes in a new repo Wondering what the best way to go about updating repo B with the changes in repo A.
I have repo A in a Stash repo, which was last updated 1 year 9 months ago.
I have repo B in a BitBucket repo, which was last updated several months ago. In the git logs I can see that the last commit to repo A is contained within the logs of repo B.
So far, what I've tried is cloning repo B, changing the git remote origin to that of repo A, git pull origin master, and then push the changes. However, I get a remote rejected: pre-receive hook declined.
I definitely want to transfer all of the commit logs from repo B into repo A.


text:
Q: Input value from a specialized controller isn't being sent back to the main controller I'm building an application that's making use of Angular UI Bootstrap's datepicker in several spots. I've included some other enhancements to this, such as validation styling, and wanted to propagate it everywhere so I put it in a directive.
app.controller('DateController', function () {

    var vm = this;

    vm.status = {
        opened: false
    };

    vm.open = open;

    function open($event) {
        vm.status.opened = true;
    }
});

app.directive('customDatePicker', function () {
    return {
        restrict: 'E',
        scope: {
            name: '=',
            bindingProperty: '=',
            minDate: '=',
            maxDate: '=',
            maxMode: '=',
            format: '=',
            isRequired: '=',
            form: '='
        },
        templateUrl: "/Scripts/SharedAngular/Templates/datePicker.html"
    };
});

With the template URL code looking like:

        <input type="text" id="{{ name }}_datePicker" name="{{ name }}_datePicker" class="form-control" max-mode="maxMode" datepicker-popup="{{format}}" ng-model="bindingProperty" min-date="minDate" max-date="maxDate" ng-required="isRequired" close-text="Close" is-open="datePicker.status.opened" />

            <button type="button" class="btn btn-default" ng-click="datePicker.open($event)"></button>

I'm including this directive in a couple places. It is placed on a page within the scope of a different controller like this:

    <custom-date-picker name="'somePrefix'" form="myForm" binding-property="ctrl.date" max-mode="'month'" max-date="ctrl.currentDate" format="'yyyy/MM/dd'" is-required="true"></custom-date-picker>

So, I want to take a property from myController and two-way bind it to the directive's date picker. However, what ends up actually happening is that the current value for ctrl.date property is passed to the datepicker, but any changes to that value that happen in the directive are not sent back. So, it seems that myController and DateController only pass the value one-way, and only when the directive is loaded onto the page. To be clear, the directive doesn't seem to be the source of my issue, since putting the HTML code from the template directly onto my page results in the same behavior. So, it appears that the issue is specifically due to the use of two different controllers.
Previously, I was using ng-model both in the template code and the directive on my primary page. Neither option seems to work. I'm open to any ideas on how to get the input from my directive to be sent back to the myController.

A: I figured out how to ditch the DateController entirely. I put my expressions directly into the template elements via ng-click and ng-init. The input creates a property called opened and uses ng-init initializes it to false. It then uses that property for the is-open attribute of the datepicker. Then the button just uses ng-click="opened=true". Definitely simplifies things and removes the nesting of controllers.
Directive:
app.directive('customDatePicker', function () {
    return {
        restrict: 'E',
        scope: {
            name: '=',
            bindingProperty: '=ngModel',
            minDate: '=',
            maxDate: '=',
            maxMode: '=',
            format: '=',
            isRequired: '=',
            form: '='
        },
        require: 'ngModel',
        templateUrl: "/Scripts/SharedAngular/Templates/datePicker.html"
    };
});

Template:

    <input type="text" id="{{ name }}_datePicker" name="{{ name }}_datePicker" class="form-control" max-mode="maxMode" datepicker-popup="{{format}}" ng-model="bindingProperty" min-date="minDate" max-date="maxDate" ng-required="isRequired" close-text="Close" is-open="opened" ng-init="opened=false" />

        <button type="button" class="btn btn-default" ng-click="opened=true"></button>

Using the directive:

    <custom-date-picker name="'somePrefix'" form="myForm" ng-model="ctrl.Date" max-mode="'month'" max-date="ctrl.currentDate" format="'yyyy/MM/dd'" is-required="true"></custom-date-picker>


text:
Q: Having trouble drawing chart using data from JSON and Google Charts I am trying to draw a line graph using google charts and a JSON that I have created from MYSQL. I have tried to use the examples provided on Google Visualization API but haven't been successful.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

function drawChart() {
    var selectedValue = $("select option:selected").val()
    var jsonData = $.ajax({
        type: 'get',
        url: '/social_scores/'+selectedValue,
        dataType:"json",
        success: function(response, status, jqXHR) {
             /* Create the charts after operation succeeded */
             var data = new google.visualization.DataTable(response);
             data.addColumn('string', 'Week');
             data.addColumn('number', 'Overall');
             data.addColumn('number', 'Presence');
             data.addColumn('number', 'Popularity');
             data.addColumn('number', 'Engagement');
             data.addColumn('number', 'Reputation');
             data.addRows([
                 ['Week 1', response.overall_score, response.presence_score, response.popularity_score, response.engagement_score, response.reputation_score ],
                 ['Week 2', response.overall_score, response.presence_score, response.popularity_score, response.engagement_score, response.reputation_score ]
             ]);
            var options = {
                title:'Key Success Metrics over time across all channels',
                'backgroundColor': 'transparent',
                'width': 620,
                'vAxis': {minValue:"0", maxValue:"100", gridlines:{count: 7} },
                'chartArea': {top:"50", left: "40"},
                'legend':{position: 'top', alignment: 'start' }
           };
           var chart = new google.visualization.LineChart(document.getElementById('line_graph'));
           chart.draw(data, options);
          ("select").change(function(){
            alert($("select option:selected").val())

           });

        }
    });
};

Here is the graph span that should be update:

Here is the drop down html:
<select id="social_entity_id" name="social_entity[id]">
<option value="1">DataSimply</option>
<option value="2">mbonat</option>
<option value="3">OpenLabel</option>
<option value="4">scrible</option>
<option value="5">jivesoftware</option>
<option value="6">lithiumTech</option>
<option value="7">getsatisfaction</option>
<option value="8">tumblr</option>
<option value="9">nytimes</option>
<option value="10">gilt</option>
<option value="11">groupon</option>
<option value="12">Bloombergnow</option>
<option value="13">NWSCorp</option>
<option value="14">etsy</option>
<option value="15">foursquare</option>
<option value="16">Yelp</option>
<option value="17">businessinsider</option>
</select>

Where should I put the change event so that the numbers changed based on the selected value of the dropdown?

A: The AJAX operation works asynchronously, so you need to wait until the operation has completed before initializing your charts.
$(function() {
    var chart;

    var drawChart = function {
        var selectedValue = $("select#social_entity_id option:selected").val();
        $.ajax({
            type: 'get',
            url: '/social_scores/'+selectedValue,
            dataType:"json",
            success: function(response, status, jqXHR) {
                 /* Create the charts after operation succeeded */
                 var data = new google.visualization.DataTable(response);
                 data.addColumn('string', 'Week');
                 data.addColumn('number', 'Overall');
                 data.addColumn('number', 'Presence');
                 data.addColumn('number', 'Popularity');
                 data.addColumn('number', 'Engagement');
                 data.addColumn('number', 'Reputation');
                 data.addRows([
                     ['1', response.overall_score, 1, 1, 1, 1 ],
                     ['1', 1, 1, 1, 1, 1 ]);

                var options = {
                    title:'Key Success Metrics over time across all channels',
                    'backgroundColor': 'transparent',
                    'width': 620,
                    'vAxis': {minValue:"0", maxValue:"100", gridlines:{count: 7} },
                    'chartArea': {top:"50", left: "40"},
                    'legend':{position: 'top', alignment: 'start' }
               };
               chart = new google.visualization.LineChart(document.getElementById('line_graph'));
               chart.draw(data, options);
            }
        });
     }

     google.load("visualization", "1", {'callback': drawChart, packages:["corechart"]});

     $('#social_entity_id').change(drawChart);

});


text:
Q: How to find the cost of stored procedures before executing in big query? I wanted to know the data processed by a stored procedure before executing it in bigquery?
Whenever I build and call a sored procedure in bigquery, It says "WARNING: Could not compute bytes processed estimate for script"
How can someone knows how much data he's going to process also if stored procedure get failed, still data will be processed and cost is involved there?


text:
Q: How to get the Sudoku 2D-array index, given its "sub-grid" and "cell-in-the-sub-grid" indexes? I'm working on a sudoku thing, and I'm having trouble reducing one part of it.
I'm designing a SudokuBoard object to have an underlying 2D byte array, and three different views of that array: row-units, column-units and grid units. A grid is the nine-by-nine blocks, indexed like this:
        GRID INDEX

        |         |
   0    |    1    |    2
        |         |
 -------------------------
        |         |
   3    |    4    |    5
        |         |
 -------------------------
        |         |
   6    |    7    |    8
        |         |

Where each grid has nine cells, indexed like this
CELL INDEX

   0 1 2
   3 4 5
   6 7 8

Here is the 2d array coordinates for the board:
                    2D-ARRAY COORDINATE

[0,0] [0,1] [0,2]  |  [0,3] [0,4] [0,5]  |  [0,6] [0,7] [0,8]
[1,0] [1,1] [1,2]  |  [1,3] [1,4] [1,5]  |  [1,6] [1,7] [1,8]
[2,0] [2,1] [2,2]  |  [2,3] [2,4] [2,5]  |  [2,6] [2,7] [2,8]
-------------------+---------------------+-------------------
[3,0] [3,1] [3,2]  |  [3,3] [3,4] [3,5]  |  [3,6] [3,7] [3,8]
[4,0] [4,1] [4,2]  |  [4,3] [4,4] [4,5]  |  [4,6] [4,7] [4,8]
[5,0] [5,1] [5,2]  |  [5,3] [5,4] [5,5]  |  [5,6] [5,7] [5,8]
-------------------+---------------------+-------------------
[6,0] [6,1] [6,2]  |  [6,3] [6,4] [6,5]  |  [6,6] [6,7] [6,8]
[7,0] [7,1] [7,2]  |  [7,3] [7,4] [7,5]  |  [7,6] [7,7] [7,8]
[8,0] [8,1] [8,2]  |  [8,3] [8,4] [8,5]  |  [8,6] [8,7] [8,8]

I've created a function to get the array-coordinate, given the grid and cell indexes. Determining the column index was a brain-buster, but I figured it out to be
int colIdx = (cell_idx % 3) + ((grid_idx % 3) * 3);

I also figured out do determine the row index, but I am unhappy with how complicated this is.
int rowIdx = -1;
if(grid_idx < 3)  {
   rowIdx = ((cell_idx < 3) ? 0
      :  ((cell_idx < 6) ? 1 : 2));
}  else if(grid_idx < 6)  {
   rowIdx = ((cell_idx < 3) ? 3
      :  ((cell_idx < 6) ? 4 : 5));
}  else  {
   rowIdx = ((cell_idx < 3) ? 6
      :  ((cell_idx < 6) ? 7 : 8));
}

If anyone has ideas on how to reduce this, ideally to a mathmatical formula, I'd appreciate it.
Here's a working application that demonstrates it. Thanks for any help.
  import  java.util.Arrays;
/**
   <P>{@code SudokuGridUnitCoordinates}</P>
 **/
public class SudokuGridUnitCoordinates  {
   public static final void main(String[] idxZeroGridIdx_0to8)  {
     int gridIdx = -1;
     try  {
        gridIdx = Integer.parseInt(idxZeroGridIdx_0to8[0]);
        if(gridIdx < 0  ||  gridIdx > 8)  {
           throw  new IllegalArgumentException();
        }
     }  catch(IllegalArgumentException | ArrayIndexOutOfBoundsException  x)  {
        throw  new IllegalArgumentException("The first element in idxZeroGridIdx_0to8 must be a digit zero through 8: " + Arrays.toString(idxZeroGridIdx_0to8));
     }

     printCellCoordinates(gridIdx, 0);
     printCellCoordinates(gridIdx, 1);
     printCellCoordinates(gridIdx, 2);
     printCellCoordinates(gridIdx, 3);
     printCellCoordinates(gridIdx, 4);
     printCellCoordinates(gridIdx, 5);
     printCellCoordinates(gridIdx, 6);
     printCellCoordinates(gridIdx, 7);
     printCellCoordinates(gridIdx, 8);
  }
  private static final void printCellCoordinates(int grid_idx, int cell_idx)  {
     int rowIdx = -1;
     if(grid_idx < 3)  {
        rowIdx = ((cell_idx < 3) ? 0
           :  ((cell_idx < 6) ? 1 : 2));
     }  else if(grid_idx < 6)  {
        rowIdx = ((cell_idx < 3) ? 3
           :  ((cell_idx < 6) ? 4 : 5));
     }  else  {
        rowIdx = ((cell_idx < 3) ? 6
           :  ((cell_idx < 6) ? 7 : 8));
     }
     int colIdx = (cell_idx % 3) + ((grid_idx % 3) * 3);

     System.out.println("grid=" + grid_idx + ", cell=" + cell_idx + " --> sudoku2DGridArray[" + rowIdx + ", " + colIdx + "]");
  }
}

A: That chunk with all the ?: operators is just grid_idx - grid_idx % 3 + cell_idx / 3

A: What about
rowIdx = 3*(grid_idx/3) + cell_idx/3

all division being integer divisions


text:
Q: List directories with a specified depth in Python I'm want a function to return a list with directories with a specified path and a fixed depth and soon realized there a few alternatives. I'm using os.walk quite a lot but the code started to look ugly when counting the depth etc.
What is really the most "neat" implementation?

A: If the depth is fixed, glob is a good idea:
import glob,os.path
filesDepth3 = glob.glob('*/*/*')
dirsDepth3 = filter(lambda f: os.path.isdir(f), filesDepth3)

Otherwise, it shouldn't be too hard to use os.walk:
import os,string
path = '.'
path = os.path.normpath(path)
res = []
for root,dirs,files in os.walk(path, topdown=True):
    depth = root[len(path) + len(os.path.sep):].count(os.path.sep)
    if depth == 2:
        # We're currently two directories in, so all subdirs have depth 3
        res += [os.path.join(root, d) for d in dirs]
        dirs[:] = [] # Don't recurse any deeper
print(res)

A: This is not exactly neat, but under UNIX-like OS, you could also rely on a system tool like "find", and just execute it as an external program, for example:
from subprocess import call
call(["find", "-maxdepth", "2", "-type", "d"])

You can then redirect the output to some string variable for further handling.

A: A simple, recursive solution using os.scandir:
def _walk(path, depth):
    """Recursively list files and directories up to a certain depth"""
    depth -= 1
    with os.scandir(path) as p:
        for entry in p:
            yield entry.path
            if entry.is_dir() and depth > 0:
                yield from _walk(entry.path, depth)

A: I really like phihag's answer.  I adapted it to suit my needs.
import fnmatch,glob
def fileNamesRetrieve( top, maxDepth, fnMask  ):
    someFiles = []
    for d in range( 1, maxDepth+1 ):
        maxGlob = "/".join( "*" * d )
        topGlob = os.path.join( top, maxGlob )
        allFiles = glob.glob( topGlob )
        someFiles.extend( [ f for f in allFiles if fnmatch.fnmatch( os.path.basename( f ), fnMask ) ] )
    return someFiles

I guess I could also make it a generator with something like this:
def fileNamesRetrieve( top, maxDepth, fnMask  ):
    for d in range( 1, maxDepth+1 ):
        maxGlob = "/".join( "*" * d )
        topGlob = os.path.join( top, maxGlob )
        allFiles = glob.glob( topGlob )
        if fnmatch.fnmatch( os.path.basename( f ), fnMask ):
            yield f

Critique welcome.

A: Here's a simple function to do this
import os
from glob import glob
from pathlib import Path

def find_sub_dirs(path, depth=2):
    path = Path(path)
    assert path.exists(), f'Path: {path} does not exist'
    depth_search = '*/' * depth
    search_pattern = os.path.join(path, depth_search)
    return list(glob(f'{search_pattern}'))

A: Note that @phihag's great suggestion also works with pathlib.Path.glob:
from pathlib import Path
from typing import List

def get_subitems(folder: Path, level: int) -> List[Path]:
    if level == 0:
        return [item]
    pattern = "/".join(["*"] * level)
    return sorted(item for item in item.glob(pattern))


text:
Q: Passing on function with switch dynamically I am new to javascript and I am trying to figure out how to dynamically pass on functions with switch?
For example, I can pass on function manually like following

var select =1 ;
function add (val){ return val+512};
function subtract(val) {return val-300};
function multiply(val){return val*584};
var value = 290;

var text = `the value is ${add(value)}`

console.log(text);

How can I pass on a function with a switch based on the select value? The following does not work.

var select =1 ;
function add (val){ return val+512};
function subtract(val) {return val-300};
function multiply(val){return val*584};
var value = 290;

//switch statement
switch(select){ case 1: add(value); break; case 2: subtract(value); break; case 3: multiply(value); break};

var string = `this value is ${switch(select){ case 1: add(value); break; case 2: subtract(value); break; case 3: multiply(value); break};}`

console.log(string)

A: I suggest moving the switch bloc inside a function, like the following:
var select = 1;
function add(val) { return val + 512 };
function subtract(val) { return val - 300 };
function multiply(val) { return val * 584 };
var value = 290;

var string = `this string in ${chooseFunction(select, value)}`

console.log(string)

function chooseFunction (select, value) {
  // switch statement

  // Note that the break statement is optional
  // if you return a value at the end of a case block
  switch (select) {
    case 1: return add(value);
    case 2: return subtract(value);
    case 3: return multiply(value);
  }
}

A: You write a function that has the switch returning the result of calling functions based on the input, and use that in the template string.

function add(val) {
  return val + 512;
}

function subtract(val) {
  return val - 300;
}

function multiply(val) {
  return val * 584;
}

function run(value, select) {
  switch (select) {
    case 1: return add(value);
    case 2: return subtract(value);
    case 3: return multiply(value);
  }
}

const value = 290;

const string1 = `This string is ${run(value, 1)}`;
const string2 = `This string is ${run(value, 2)}`;
const string3 = `This string is ${run(value, 3)}`;

console.log(string1);
console.log(string2);
console.log(string3);

A: You cannot pass a switch directly, as you cannot pass a if statement without a ternary operator. You need to encapsulate your switch statement in a function like this :

var select =1 ;
function add (val){ return val+512};
function subtract(val) {return val-300};
function multiply(val){return val*584};
var value = 290;

const getValue = (s, v) => {
switch(s) {
  case 1:
    return add(v);
  case 2:
    return subtract(v);
  case 3:
    return multiply(v);
   };
}

var string = `this value is ${getValue(select, value)}`

console.log(string)

An other way to do this is to put your functions into an array with the index referencing the choice :

var select =1 ;
function add (val){ return val+512};
function subtract(val) {return val-300};
function multiply(val){return val*584};
var value = 290;

const fn = [add, subtract, multiply];

var string = `this value is ${fn[select - 1](value)}`

console.log(string)


text:
Q: Getting only public data from Firebase reference's children I have the following Firebase code:
https://gist.github.com/balazsorban44/52c2858aa10f6269c7a9b3c0cfa247d5
I would like to get a js object of all the reservations', but only the public parts, since the details are only viewable for the admins.
I tried the following:
let reservations = {}
firebase.database().ref('reservations').once('value', snapshot => {
    snapshot.forEach(reservation => {
      reservations[reservation] = reservation.val().public
    })
})

But it does not work. Where am I failing?
Should I create a reservationsPublic and a reservationsPrivate object, so I can more easily fetch the info I need? In this case, when a user fills out a reservation form, should I split the input into two and put half of it into the reservationsPublic and the rest to the reservationsPrivate?
EDIT:
I think I found the solution for my problem here:
https://stackoverflow.com/a/38649032/5364135
So I have to write to the database twice, to improve the read performance, if I understood it correctly.


text:
Q: Puppet module resource attributes Is there a way to print the value of an attribute in a puppet module?  For example, if you have a file resource:
file {'myfile':
      path => '/this/is/my/path',
      ensure => present,
      owner => 'someuser',
      group => 'somegroup'
}

can you print the value of the 'path' attribute?  Perhaps using a notify?
notify {"the value of path is: " __________}

A: Not if you pass your attributes as literal strings.
However, you can re-use the attribute if you assign it to a variable. Example:
$file_path = '/this/is/my/path'

file { 'myfile':
  path   => $file_path,
  ensure => present,
  owner  => 'someuser',
  group  => 'somegroup'
}

notify { "the value of path is: ${file_path}": }

Note the final colon that separates the resource name and the parameters (in this case there are none, so the resource is just terminated). The notify above could also be written as this (reference):
notify { 'my_notify':
  message =>  "the value of path is: ${file_path}",
}

Also, note the correct use of single and double quotes. According to Puppet Lint, double quotes should only be used when the string contains an interpolated variable, and such variables should be enclosed within curly braces.


text:
Q: Resolve IP to Hostname using PHP How can I resolve an IP address to a hostname using PHP?

A: Use gethostbyaddr()
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

echo $hostname;

You might find that this function can hang for some time when an address is not found - if this becomes a performance issue for you, check this manual comment which details a hand-coded method which supports a timeout.

A: gethostbyaddr()

A: You can use the gethostbyaddr() function.
$hostname = gethostbyaddr($ipAddress);

A: You should give gethostbyaddr() a shot.


text:
Q: Scriptaculous load parameter in FF 2.0.x Greetings all,
I am attempting to explicitly load the effects.js and builder.js Scriptaculous libraries on a page, using this code:
<script type="text/javascript" src="/javascripts/scriptaculous.js?load=builder,effects"></script>

This works like a charm in FF 3.0.x, IE7 and Opera 9.6.x. It does not work in Firefox 2.0.x, however. The libraries never become loaded. In order to get them to load in FF 2.0.x, I must explicitly reference them with two extra <script /> tags, i.e.:
<script type="text/javascript" src="/javascripts/scriptaculous.js?load=builder,effects"></script>
<script type="text/javascript" src="/javascripts/builder.js"></script>
<script type="text/javascript" src="/javascripts/effects.js"></script>

Does anyone happen to know what the discrepency between FF 2.0 and 3.0 is that causes this behavior? Is there a better solution to my problem?
Thanks for your help!

A: I've had too much coffee today, so I figure I will give this a go.
One possibility is the load function in scriptaculous.js does not correctly do the processing to include the libraries passed to it as parameters (scriptaculous.js?load=builder,effects).
Try putting in an alert to see if the load function in scriptaculous.js is being entered into, if it is, then the process probably doesn't do what it's supposed to on FF2:
load: function() {
    alert('In the load function!');
    ...rest of code here...

If it isn't, then (maybe) firefox 2 does not want to execute load.
The last part of load seems to do the work for including other libs:
$A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });

From the above code, I can see that the includes variable should parse out the library names, see if that's being assigned anything, replace it with something like:
var includes = s.src.match(/\?.*load=([a-z,]*)/);
alert(includes[0] + ' ' + includes[1]);

That should give you a better idea of what's going on. While this is an interesting little problem, I would definitely go with the solution you proposed:
<script type="text/javascript" src="/javascripts/scriptaculous.js"></script>
<script type="text/javascript" src="/javascripts/builder.js"></script>
<script type="text/javascript" src="/javascripts/effects.js"></script>


text:
Q: Running into a hang in SWIG generated code at SWIGRegisterExceptionCallbacks_ I have a C# DLL which calls methods generated via SWIG that translate into calls into my C++ DLL (Native). In Release mode it seems to work, however in debug it hangs at SWIGRegisterExceptionCallbacks_%Module. I've tried everything I can think of to figure what the problem is but SWIG is very opaque and stepping into it does not help any.
I'm using the latest version of swig. I would post my code but the solution I'm working with possesses more than a million lines of code.
I've run Dependency Walker to figure out if there's some dependency dll missing. It does complain that the C++ DLL was not found. However, the DLL is in that directory. All the C++ DLLs have been retargeted to 10.0.17763.0 and all the C# is based on .NET Framework 4.7.2.
I can't figure out how to move forward. Anybody have any good advice on how to proceed?


text:
Q: How to loop through array and ignore selected value String response = "[\n" +
        "  {\n" +
        "    \"id\": 1,\n" +
        "    \"name\": \"What is your your father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 2,\n" +
        "    \"name\": \"What is your mother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 3,\n" +
        "    \"name\": \"What is your brother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 4,\n" +
        "    \"name\": \"What is your father's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 5,\n" +
        "    \"name\": \"What is your sister's father name\"\n" +
        "  }\n" +
        "]";

I have this set of questions and I wanted to loop through it to show in Dialog list. There are going to be 2 AlertDialog and if user select the value from one of the AlertDialog. The questions wont show in the other AlerDialog. For the loops, this is my code:
public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.q1:
                try {
                    JSONArray jsonArray = new JSONArray(response);
                    if (selected2>-1)
                        q1 = new String[jsonArray.length()-1];
                    else
                        q1 = new String[jsonArray.length()];
                    int index = 0;

                    for (int x = 0; x<jsonArray.length(); x++){
                        idQuestion[index] = jsonArray.getJSONObject(x).getInt("id");
                        if (selected2==x)
                            continue;
                        q1[index]= jsonArray.getJSONObject(x).getString("name");
                        index++;
                    }

                    AlertDialog alertDialog =new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question1.setText(q1[which]);
                                    if(selected == -1) {
                                        selected = which;
                                    } else {
                                        selected = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.q2:
                try {
                    JSONArray ja = new JSONArray(response);
                    if (selected>-1)
                        q2 = new String[ja.length()-1];
                    else
                        q2 = new String[ja.length()];
                    int index = 0;
                    for (int x = 0; x<ja.length(); x++){
                        if (selected==x)
                            continue;
                        q2[index] = ja.getJSONObject(x).getString("name");
                        index++;
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q2, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question2.setText(q2[which]);
                                    selected2 = which;
                                    if(selected2 == -1) {
                                        selected2 = which;
                                    } else {
                                        selected2 = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }

But I found that this logic is wrong.Questions are form server, that's why its is JSON format. If possible I want to use the id of the questions., since I'll have to return the value of id, not the question.

A: To ignore values inside a loop use if(id==id_ignored) continue;

A: It's not the complete solution but I am giving some idea on how to achieve it.
at first convert your all questions to ArrayList for that you can do manually or you can use gson as well.
public Question
{
  int id;
  String name;
}

First create a list of all questions
i.e. ArrayList<Question> all
then create another list for ArrayList<Question> filteredList
and store selected id in variables selected_1, selected_2;
as you select items you put assign it to selected_1 or selected_2
and filter items and put in filteredList
for (Question q : all)
{
 if (id in selected_1 or selected_2) //based on your alertdialog
    ignore;
else
  filteredList.add(q);
}

Use this everytime you select something
and to show the list in AlertDialog use this filteredList.


text:
Q: Modules as function arguments I have a python script that starts with importing a python module that contains data. A very simplified example is given below:
my_data1.py
bar = 10
baz = [1, 5, 7]
...

my_func.py
from my_data1 import *

def foo():
    '''
    function that uses the things defined in data (scalar, list, dicts, etc.)
    in my_data
    '''
    return [bar] + baz

This works great for one set of data; however, I have my_data1.py, ..., my_data36.py.
my_data36.py
bar = 31
baz = [-1, 58, 8]
...

that I want to import and then run foo() with that data. I wanted to do something like this:
def foo(my_data):
    from my_data import *

results = []
for i in range(1,37):
    results.append(foo('my_data{}'.format(i)))

This doesn't work. Ideas?

A: Use __import__. It takes a string as parameter identifying the module to be imported, and returns the module, which then you can pass as an argument to your functions.
def processDataSet (module):
    print (module.baz)

for m in ['data1.py', 'data2.py', 'data69.py']:
    processDataSet (__import__ (m) )

A: "from module import * is invalid inside function definitions." from http://docs.python.org/2/howto/doanddont.html#inside-function-definitions


text:
Q: Non-virtual interface design pattern in C#/C++ When designing an interface, someone recommended to use the non-virtual interface pattern. Can someone briefly outline what the benefits of this pattern are?

A: The essence of the non-virtual interface pattern is that you have private virtual functions, which are called by public non-virtual functions (the non-virtual interface).
The advantage of this is that the base class has more control over its behaviour than it would if derived classes were able to override any part of its interface. In other words, the base class (the interface) can provide more guarantees about the functionality it provides.
As a simple example, consider the good old animal class with a couple of typical derived classes:
class Animal
{
public:
    virtual void speak() const = 0;
};

class Dog : public Animal
{
public:
    void speak() const { std::cout << "Woof!" << std::endl; }
};

class Cat : public Animal
{
public:
    void speak() const { std::cout << "Meow!" << std::endl; }
};

This uses the usual public virtual interface that we're used to, but it has a couple of problems:

*

*Each derived animal is repeating code -- the only part that changes is the string, yet each derived class needs the whole std::cout << ... << std::endl; boilerplate code.

*The base class can't make guarantees about what speak() does. A derived class may forget the new line, or write it to cerr or anything for that matter.

To fix this, you can use a non-virtual interface that is supplemented by a private virtual function that allows polymorphic behaviour:
class Animal
{
public:
   void speak() const { std::cout << getSound() << std::endl; }
private:
   virtual std::string getSound() const = 0;
};

class Dog : public Animal
{
private:
   std::string getSound() const { return "Woof!"; }
};

class Cat : public Animal
{
private:
   std::string getSound() const { return "Meow!"; }
};

Now the base class can guarantee that it will write out to std::cout and end with a new line. It also makes maintenance easier as derived classes don't need to repeat that code.
Herb Sutter wrote a good article on non-virtual interfaces that I would recommend checking out.

A: Here is a wiki article it a bit more in details with some examples. The essence is that you can ensure important conditions (like obtaining and releasing locks) in a central place in your base class while still allowing to derive from it to provide different implementations by using private or protected virtual functions.
Users of any class of the class hierarchy will always call the public interface which dispatches the calls to the not externally visible implementations.


text:
Q: Update limited number of rows (Syntax error in UPDATE statement) is there any way how to update limited number of rows using OleDb connection in C# (I am connectiong to Excel file)?
I tried following:
private static string GetConnectionString = (string path)
{
  var connectionDictionary = new Dictionary<string, string>();
  connectionDictionary["Provider"] = "Microsoft.ACE.OLEDB.12.0";
  connectionDictionary["Extended Properties"] = "Excel 12.0 XML";
  connectionDictionary["Data Source"] = path;

  var sb = new StringBuilder();

  foreach (var property in connectionDictionary)
  {
    sb.Append(property.Key);
    sb.Append("=");
    sb.Append(property.Value);
    sb.Append(";");
  }

  return sb.ToString();
}

public static void DoTheMagic(string path)
{
  var connectionString = GetConnectionString(path)

  using (var connection = new OleDbConnection(connectionString))
  {
    try
    {
      connection.Open();
      var cmd = new OleDbCommand { Connection = connection };
      cmd.CommandText = "UPDATE TOP (1) [TableName]
                         SET [Column] = 'value'
                         WHERE [Column] IS NULL";
      cmd.ExecuteNonQuery();
}
    finally
    {
      connection.Close();
    }
  }
}

but this throws an error:

SystemData.OleDb.OleDbException occured in SystemData.Dall
Additional information: Syntax error in UPDATE statement

A: No. OLEDB doesn't offer row numbering or limiting functionalities in combination with Excel as 'database engine'. It has a very stripped down SQL engine.
You could add an ID field in your worksheets and update with steps of X. The problem is that if you have gaps, it might not update anything.


text:
Q: How to Read from Registry "Name" using VC++? I want to Read from Registry the Name.how i can do this using VC++ ?
Ex : I have one folder called ABC in Registry under that i have 3 enteries
Name , Type, Data.
Now i want to read all Name one by one
Name     Type        Data
V:\      REG_SZ      \\124.158.14.74\CIFS
J:\       REG_SZ       \\124.158.14.74\CIFS

In my case Name is nothing but drive name's i want to read it one by one.
Any help is appreciated.

A: I think RegEnumValue is the API you are looking for.

A: See the SHEnumKeyEx function for simplicity

A: See the following link, in enumerating registry in windows. Hope this helps.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724256%28v=vs.85%29.aspx


text: Q: How do I run a cluster analysis on customer store visit data to identify clusters that consist of both location and time? I have data from customer visits to a number of different stores over the course of a few months. In one column I have the time/date of the visit, in another the location of the visit, and in other columns other variables (amount spent during the visit, how many items purchased, what type of items were purchased, etc.). I'm looking to identify different clusters from this data that consist of both location and time information - for example, Saturday afternoon may be one cluster, Christmas holiday another, etc. What is the best way to do this kind of analysis in R?


text:
Q: Explain how XMLBeans Handles '-' Character I have a file with an XSD element which contains a '-' character.  This is a recent change to the XSD file and after compiling the file I am seeing no change to the accessor method used in my java code.  Additionally when I attempt to call this element in my java code it throws a null pointer exception.  I receive no errors compiling the xsd file, I have restarted and cleaned my project multiple times.
Can someone please explain how XMLBeans is handling the addition of the '-' character, or how I can better handle this situation?
Example:
Old:
<xs:element minOccurs="0" maxOccurs="1" name="FooBoo">

Old Accessor Method:
getFooBoo();

New:
<xs:element minOccurs="0" maxOccurs="1" name="Foo-Boo">

New Accessor Method:
getFooBoo();

Expected New Accessor Method:
    getFoo_Boo();

A: XmlBeans generates the getter and setter method names by splitting the XSD property name into word parts, capitalizing each part, and the combining the words together.  Any non-word characters are considered word part boundaries and will be skipped.
The exact details of the algorithm can be found in StscJavaizer.pickJavaPropertyName() and NameUtil.upperCamelCase().


text:
Q: Dynamic markup with MVC I have markup stored in a database, which I am pulling out and placing onto a page.
below is a basic sample of what I have, without any db calls for ease of example;
The controller:
ViewData["testMarkup"] = "I was here <%= DateTime.Now.Year %>";

The View:
<%= ViewData["testMarkup"] %>

now this out puts: I was here
and no date, this is because it is ignoring the <%= %> part, is there anyway I can output the above said string and woudl include the year?
Many thanks,

A: Just do the following:
ViewData["testMarkup"] = "I was here " + DateTime.Now.Year.ToString();

Or am I missing something? Code blocks, such as <%= DateTime.Now.Year %> are only valid when they are part of the markup:

The year is <%= DateTime.Now.Year %>

A: The markup in the database is being treated as a string, not as code in your view language, so it is simply writing it out as text, c# and all.
Two alternate methods:
1 - Use a templating system, such as
ViewData["testMarkup"] = "I was here #YEAR#";

and have a method that replaces your tokens (e.g. #YEAR#) with their values at render time, e.g.,
<%= ReplaceTokens((string)ViewData["testMarkup"]) %>

Where ReplaceTokens looks like:
public static ReplaceTokens(string s)
{
    return s.Replace("#YEAR#", DateTime.Now.Year)
}

2 - Store your markup in a partial view, and save the name of the partial view in the database if necessary.

A: I do believe Phil Haack has the answer to my issue. http://haacked.com/archive/2009/04/22/scripted-db-views.aspx
I will have to check this out and see what happens


text:
Q: Is it possible to hold down element.click for a certain amount of time? Context: Creating a keyboard element in svelte, i want to emulate a user click to show the animation, but btn.click() is to short to show the transition.
Using btn.click() does fire a click element, but it's too short for the user to notice.
Ive tried using btn.focus() and btn.blur() but it doesn't play the animation, it only causes a border to show up.
Is there a way for me to emulate a click for X amount of time?
This is my code (per key)
<script lang=ts>
    import { addLetter, enter, removeLetter, onKeyPress } from "./state";
    export let key: string;
    let btn: HTMLButtonElement;
    function handle(e: MouseEvent) {
        if(!e.isTrusted) return
        if(key === "DELETE") {
            removeLetter(false)
        } else if(key === "ENTER") {
            enter(false)
        } else {
            addLetter(key, false)
        }
    }

    onKeyPress((k, kb) => {
        if(!(k === key) || !kb) return
        btn.click() //! LOOK HERE
    })
</script>

<button class="btn kbd transition-all" bind:this={btn} on:click={handle}>{key}</button>

A: You could run an animation rather than using transitions, e.g.
<script>
    let button;
    function onKeyDown(e) {
        if (e.key == 'f') {
            animate();
        }
    }

    function animate() {
        button.animate(
            [{ background: 'red' }],
            { duration: 200, direction: 'alternate', iterations: 2 },
        )
    }
</script>

<svelte:window on:keydown={onKeyDown}/>

<button bind:this={button} on:click={animate}>F</button>

Single Key
Full Keyboard

A: What you are looking for is mousedown and mouseup events
<script lang=ts>
    import { addLetter, enter, removeLetter, onKeyPress } from "./state";
    export let key: string;
    let btn: HTMLButtonElement;
    let mousedownTime: Date;
    function handle(e: MouseEvent) {
        if(!e.isTrusted) return
        if(key === "DELETE") {
            removeLetter(false)
        } else if(key === "ENTER") {
            enter(false)
        } else {
            addLetter(key, false)
        }
    }

    function mouseDown() => {
       mousedownTime = new Date().getTime();
    }
    function mouseUp() {
        const mouseupTime = new Date().getTime(),
        timeDifference = mouseupTime - mousedownTime;
        alert(`Button held down for ${timeDifference}ms`);
    }

    onKeyPress((k, kb) => {
        if(!(k === key) || !kb) return
        btn.click() //! LOOK HERE
    })
</script>

<button class="btn kbd transition-all" bind:this={btn} on:mousedown={mouseDown} on:mouseup={mouseup}></button>


text:
Q: YAML data exchange issues between Perl and Ruby I'm having trouble with data being exchanged between Perl and Ruby via YAML. I have some values that look like number:number, such as 1:16.
Perl's YAML libraries (Tiny and XS) encode this as 1:16 without quotes. Ruby's YAML library (Psych) does not interpret this as a string, but instead somehow becomes the Fixnum value 4560. I can't figure out how to fix this conversion issue on either side.
Every value in the YAML for my use case should be an object or string.  So, I could tell the Perl YAML library to quote all values, if such an option existed. Or is there any way to tell the Ruby YAML library to interpret all values as strings? Any ideas?
Changing the language on either side is not logistically an option.
Perl:
use YAML::XS qw(DumpFile);
my $foo={'abc'=>'1:16'};
DumpFile('test.yaml',$foo);

Ruby:
require('yaml')
foo=YAML.load_file('test.yaml')
puts(foo['abc'])

The Ruby code will print 4560. One of the comments figured out how you get 4560 from 1:16, it's 1 hour, 16 minutes converted to seconds.  Uh, okay.

A: According to the Yaml 1.1 spec, 1:16 is an integer in sexagesimal (base 60) format.
See also http://yaml.org/type/int.html, which says:

Using ":" allows expressing integers in base 60, which is convenient for time and angle values.

The Yaml parser included in Ruby, Psych, recognises this format and converts the value into an integer (wrongly, 1:16 shoud be 71 – the Psych code seems to asume that all such values will be in the form a:b:c but the regex doesn't enforce that). The Perl  emitter (at least YAML::XS which I tested) doesn't recognise this format, so doesn't quote the string when writing the file. YAML::XS does recognise and quote some integers, but not all. YAML::XS also doesn't recognise many other formats (e.g. dates) that Psych does.
(It appears that the sexagesimal format has been removed from the Yaml 1.2 spec.)
Psych allows quite a deal of flexibility in its parsing – YAML.load_file is just a simple interface for the common use cases.
You could use the parse methods of Psych to create a tree representation of the yaml, then convert this into a Ruby data structure using a custom ScalarScanner (which is the object that converts strings of certain formats to the appropriate Ruby type):
require('yaml')

class MyScalarScanner < Psych::ScalarScanner
  def tokenize string
    #this is the same regexp as Psych uses to detect base 60 ints:
    return string if string =~ /^[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+$/
    super
  end
end

tree = YAML::parse_file 'test.yaml'
foo = Psych::Visitors::ToRuby.new(MyScalarScanner.new).accept tree

This is basically the same process that occurs when you use YAML.load_file, except that it uses the customised scanner class.
A similar alternative would be to open up ScalarScanner and replace the tokenize method with the customised one. This would allow you to use the simpler load_file interface, but with the usual caveats about monkey patching classes:
class Psych::ScalarScanner
  alias :orig_tokenize :tokenize
  def tokenize string
    return string if string =~ /^[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+$/
    orig_tokenize string
  end
end

foo = YAML.load_file 'test.yaml'

Note that these examples only take into consideration values with a format like 1:16. Depending on what your Perl program is emitting you may need to override other patterns too.  One in particular that you might want to look at is sexagesimal floats (e.g. 1:16.44).

A: There's a bug in the parser you are using. It seems to think 1:16 is some kind of time (since 4560 is the number of seconds in one hour and 16 minutes), but I find nothing that validates that interpretation.
The best solution would be to use a parser that isn't buggy.

*

*libyaml, used by YAML::XS, supposedly has Ruby bindings.

*libsyck, used by YAML::Syck, supposedly has Ruby bindings.

An alternative is to generate YAML where the strings are always quoted (or at least when they would be treated as as time).
YAML::Syck has an option to do exactly that.
$ perl -e'
   use YAML::Syck qw( Dump );
   local $YAML::Syck::SingleQuote = 1;
   print(Dump({abc=>"1:16"}));
'
---
"abc": '1:16'

(Don't know how I missed this option earlier!)

A: Ruby interprets all YAML entries as strings, unless they fit a handful of special formats.  The entry 1:16 looks like it matches the special format for a time, so Ruby is mis-interpreting it.
You need to force Ruby to interpret the field as a string.  There are two ways to do this.  Either of the following YAML outputs should give you the result that you want:
abc: !str 1:16
abc: '1:16'

To generate this output, try the following Perl code:
my $foo={'abc'=>'!str 1:16'};
my $foo={'abc'=>"'1:16'"};

Update:
I was able to pass data between Perl and Ruby using the following code:
Perl:
use YAML::XS qw(DumpFile);
my $foo={'abc'=>'1:16'};
DumpFile('test.yaml',$foo);

Ruby:
require 'yaml'
foo=YAML.parse_file('test.yaml')
foo['abc'].value
=> "1:16"
foo['abc'].value.class
=> String

The result is a bit more complicated to use than the simple hash that load_file returns, but it looks like it's at least parsing the file as expected.


text:
Q: How do I fix my reducer to return the property value of an object? I have a reducer in my react native app which ideally should check the state and return if the recipe has been favourited or not. I've tried to create a reducer to return if isFav is true or false for a recipe object in the state. If the recipe is not found in the state it should return false.
I've hit a brick wall trying to figure out how to write the reducer. This is what I have so far.
This is my favids.js reducer
import { TOGGLE, IS_FAVOURITE } from '../actions'

export const favids = (state = [], action) => {
    const { type, recipeid } = action

    const newRecipe = {
        recipeid,
        is_fav: true,
    }

    switch (type) {
        case TOGGLE: {
          //   console.log(`Toggle State = ${JSON.stringify(state)}`)
           //  console.log(`Toggle recipe id : ${recipeid}`)
            return state.findIndex(recipe => recipe.recipeid === recipeid) === -1 ?
                [...state, newRecipe] :
                state.map(recipe =>
                    recipe.recipeid === recipeid ?
                        { ...recipe, is_fav: !recipe.is_fav } : recipe
                )
        }
        case IS_FAVOURITE: {
            //console.log(`Is Favourite state =${JSON.stringify(state)}`)
            return state.map(recipe =>
                recipe.recipeid === recipeid ?
                    recipe.is_fav : state
            )
        }
        default:
            return state
    }
}

This is my actions.js
export const TOGGLE = 'TOGGLE'
export const toggleFavId = id => ({
    type: 'TOGGLE',
    recipeid: id
})

export const IS_FAVOURITE = 'IS_FAVOURITE'
export const isFavourite = id => (
    {
        type: 'IS_FAVOURITE',
        recipeid: id
    }
)

I'm trying to modify the is_favourite reducer to return a true or false which is the value of the is_fav property of the recipe object saved down in the state.
I'm trying to call this in the useEffect of the visible component while rendering the component.
This is the favicon.js file
import React, {useState, useEffect} from 'react'
import { FontAwesome } from '@expo/vector-icons'
import { View, TouchableOpacity,StyleSheet, Text, Alert } from 'react-native'

const FavIcon = ({recipeid, onToggle, isFavourite, text}) => {

  const [isFavNew, setFavNew] = useState(false)

  const toggleFav = (recipeid) =>{
    setFavNew(!isFavNew)
    onToggle(recipeid)
  }

  useEffect(() => {
    console.log("Entered useEffect")
    console.log(`Recipeid = ${recipeid}`)

    console.log(`Favicon UseEffect IS Favourtie Recipe id:> ${JSON.stringify(isFavourite(recipeid))}`)
    **// if (recipeid > 0)
    //   setFavNew((isFavourite(recipeid))
    // else {
    //   setFavNew(false)
    // }**
  },[])

 // console.log(`Is Favourite in Favicon is = ${isFavourite(recipeid)}`)

   return (
        <View>
            <TouchableOpacity style={styles.favItem} onPress={() => toggleFav(recipeid)}>
                <FontAwesome name={isFavNew === true ? 'heart' : 'heart-o'} size={40} color='red' />
               <Text> {text}</Text>
            </TouchableOpacity>
        </View>
    )
}

export default FavIcon

A: If I understand your issue correctly, it's due to a misunderstanding about Redux.  You are looking for a selector, not an action handled by a reducer.
Redux is nothing but a big, fancy object.  Reducers modify the object's properties.  Actions tell the reducers how to do that.  Selectors return those properties to you.
You can remove the TOGGLE action and the case in your reducer with the same name.  Then you'd create a selector like the following:
const isRecipeFavorited = (recipeId) => (state) => {
    const recipe = state.find(recipe => recipe.id === recipeId;
    return recipe ? recipe.is_fav : false;
};

A selector is a function that takes your whole state as an argument and returns a subset.  Redux passes in your whole state for you when you use useSelector.  So a function like this is a "selector factory", where you would invoke it with the recipe ID and it would return the selector for that recipe.  You would use it like this:
import { useSelector } from 'react-redux';
import { isRecipeFavorited } from '{selectors path}';

...

const recipeIsFavorited = useSelector(isRecipeFavorited(recipeId));

On a side note, there are a couple of optimizations you could make that will help if you end up with a large amount of information in state.  The most important would be to store your recipes in an object instead of an array.  I assume you get an array of recipes back from an API.  Assuming you can count on unique recipe IDs, you can iterate through the array and store each one in an object:
const recipesState = {};

returnedRecipes.forEach(recipe => {
    recipesState[recipe.id] = recipe;
};

Then, when you're selecting recipes in your reducers, you don't have to iterate through the whole list to get the one you want, or to store the results.  You can do these operations in O(1) time because you already know the recipe ID.
Then your IS_FAVOURITE case in your reducer could look something like:
        case TOGGLE: {
            const tempRecipes = { ...state };
            const currentRecipe = tempRecipes[recipeId];

            currentRecipe
                 ? currentRecipe.is_fav = !currentRecipe.is_fav
                 : tempRecipes[recipeId] = newRecipe;

            return tempRecipes;
        }

You could then design the selector I described above like this:
const isRecipeFavorited = (recipeId) => ({ recipe }) => recipe[recipeId]
    ? recipe[recipeId].is_fav
    : false;


text:
Q: POSIX Queue Configuration I want to know how can I configure posix queue on linux OS.
I know the ways I can edit in sysctl.conf and in code by
mq_open(**,**,**);

Is there any other way I can configure the number of messages per queue and the number of queues.

A: You are mixing different layers of the onion.

*

*On the individual queue layer, the queue attributes (mq_maxmsg and mq_msgsize) are fixed at the time of the queue creation and can't be changed.  mq_curmsgs doesn't make any sense to change unless you are looking to mangle your queue and can only be queried through mq_getattr.  The mq_flags can be changed through mq_setattr` but the only flag to be changed is to toggle the blocking/non-blocking state of the queue.
As practical matter it is easy to write simple command line utilities to do most of the above and many organizations will already have them.  They are usually among the first programs using queues that developers write for themselves anyway.  Some systems will incorporate these little utilities into startup and shutdown scripts for their applications.

*On the process layer, there are limits on message priorities (MQ_PRIO_MAX) and the number of queues a process can have open (MQ_OPEN_MAX).  In linux neither of these are a real concern.  The max priority is like 32k - sysconf(_SC_MQ_PRIO_MAX) - and if you are using that many priorities you have some real design issues.  And because mqd_t types in linux are file descriptors the real limiting factors on the number of open queues is the total number of file descriptors to which a process is limited.

*At the system level, there are limit files in /proc/sys/fs/mqueue that can be changed with appropriate permissions.  (a) queues_max is the upper limit on the number of queues allowed on a system in toto but a privileged user can still create queues once this limit has been hit. (b) msgsize_max is the max message size of a message created by an unprivileged process.  (c) msg_max is the largest message size allowed for a queue.  (d) Linux also has two files msg_default and msgsize_default in /proc/sys/fs/mqueue that should be self-evident.


text:
Q: Reshaping an image I was searching for an online tool or tutorial to reshape an image. What i exactly want is something like this.

So that i can reshape it into something like this

I found this functionality in this website!.. But i couldn't trace how they did it. I've googled for hours but ended up with some broken urls. I'm not a designer to start with but i have to do this. Someone please tell me how to do this..

A: You can have a closer look to html5 canvas tutorials like THIS.
In this tutorial for example "Part 2: Drawing Shape With Paths" will be interesting for you. To have those "handles" you will need to draw some simple rectangles at every point in your path.
Everything more about this would go too much in detail. I think this is a good place to start for you.