text:
Q: Trying to convert sql to linq with subquery I am trying to convert this sql to linq:
SELECT [t0].[ThreadId] FROM [MessageParticipants] AS [t0]
WHERE EXISTS(
  SELECT threadId
  FROM [MessageParticipants] AS [t1]
  WHERE ([t1].[UserId] = 23)
)
AND ([t0].[UserId] = 3)

I have tried converting with LINQPad but I cant get it to work
This almost work:
var result = from mp2 in MessageParticipants
            let x = (from mp in MessageParticipants where mp.UserId == 3 select mp.UserId)
where  x.Contains(23)
select mp2;

result.Dump();

The result query of the above LINQ (which is wrong)
DECLARE @p0 Int = 23
DECLARE @p1 Int = 3
SELECT [t0].[Id], [t0].[ThreadId], [t0].[UserId], [t0].[CreatedDate], [t0].[MessageId]
FROM [MessageParticipants] AS [t0]
WHERE EXISTS(
  SELECT NULL AS [EMPTY]
  FROM [MessageParticipants] AS [t1]
  WHERE ([t1].[UserId] = @p0) AND ([t1].[UserId] = @p1)
) --> AND should be here not in the inner query

Maybe there are a better way ?
I am trying to find if user 23 and user 3 already have an ongoing conversation by finding there threadId.
So the MessageParticipants table looks like this:
Id, ThreadId, UserId
--------------------
1    52        23
2    52        3
3    11        20

A: I believe your sql is a little off, you should use a join on the table to itself and then use a where for the id. Here is the updated sql and underneath the corresponding linq to get the thread id.
-- create in memory table for testing
DECLARE @MessageParticipants table (Id INT identity, ThreadId int, UserId int)
insert into @MessageParticipants(ThreadId, UserId) values (52,23), (52,3), (11, 20),(11, 3)

SELECT [t0].[ThreadId]
FROM @MessageParticipants AS [t0]
INNER JOIN @MessageParticipants AS [t1] ON t0.ThreadId = t1.ThreadId
WHERE [t1].[UserId] = 3 AND [t0].[UserId] = 23

Linq statement
var result = from m1 in MessageParticipants
    join m2 in MessageParticipants on m1.ThreadId equals m2.ThreadId
    where m2.UserId == 3 && m1.UserId == 23
    select m1.ThreadId;

var thread = result.FirstOrDefault();


text:
Q: How set progressive colors on scatter plot? I am trying to represent points in 2d space with according label, I also want the points to have the same color as their label and finally I need the colors of the labels to be progressive.
I looked everywhere but I can't seem to find a solution.
This is my current implementation :
for i in range(0, encoder.classes_.size):
       plt.scatter(data_pca_reduced[i][0], data_pca_reduced[i][1],
                   label=i, cmap=plt.get_cmap('viridis'))

And this is the result :

As you can see the labels colors are not progressive.

A: Thanks the second link is exactly what I was looking for !
Now this is the working code :
colors = matplotlib.cm.rainbow(np.linspace(0, 1, encoder.classes_.size))
for i, c in zip(range(encoder.classes_.size), colors):
       plt.scatter(data_pca_reduced[i][0], data_pca_reduced[i][1], label=i, color=c)

And this is the result :

redpajama_set_name: RedPajamaStackExchange


text:
Q: using async with javascript forEach I have an array of emails
emails.forEach(email => sendEmail(email)); --> 1

function2();

sendEmail is an asynchronous function
I want function2 to be invoked only after line 1 gets completed
How can I achieve this?

A:
How can I achieve this?

Don't use forEach. Either use a normal for loop, and await each call, or if you want to run them in parallel use map and await Promise.all.
My preference would be:
async function sendAllEmails(emails) {
    await Promise.all(emails.map(email => sendEmail(email)));
    function2();
}


text:
Q: Is there a way to know that admob ads are ready or not I am using Unity to create games. Admob integration is easy with unity. Now you know there is a function in unity of
ad.IsReady()

I make a button interactable when ad loads by using it and uninteractable if it's not yet loaded. Now
is there any function in admob too just like this unity function. Thanks for any of your help

A: When the ad loaded:
public void HandleOnAdLoaded(object sender, EventArgs args)
{
    MonoBehaviour.print("HandleAdLoaded event received");
}

When the loading failed:
public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
    MonoBehaviour.print("HandleFailedToReceiveAd event received with message: "
                        + args.Message);
}

And you can find everything you want here


text:
Q: Make android load specific parts of library starting from specific SDK version I have an app, that must be working on Android 4+. However I want to add some functionality to this app that uses api appeared only in Android 5. So I made a separate module that has higher minSdk version. But when I include this module in app it crashed on startup (fails with app verifier).
How should I tell android class loader to load classes from this module only starting from some another SDK version.


text:
Q: Can I use Azure Policy to audit or enforce Azure Activity Log diagnostic settings? Built in audits if a Log Profile exists, but not the destination stores. Would like to specify the Storage Account/Event Hub/Log Analytics Workspace.
Can I enforce those settings? In that approach, to also utilize modern diagnostic settings and send to a storage account and log analytics workspace.

A: Two (2) options to configure diagnostic settings (besides doing this manually on each resources):
Azure Resource Template (ARM)
This requires you to have a deeper understanding of Azure and Resources. However, it gives you all the flexibility to configure any type of resources and targets (storage, event hub or log analytics). This option does not come with additional feature to check compliancy and remediate any configuration drift.
See Microsoft documentation here
Azure Policy
Configuration can be done through the portal (look for 'policy' under 'all services'). However, only the following resources are covered: Services Bus, Search Services, Event Hub, Stream Analytics, Data Lake Gen 1. On the other hand it comes with compliancy dashboard and remediation.
See Microsoft documentation here


text:
Q: Sorting alphabet in terms of numbers def make_gradebook():
    return []

def make_module_info(module, grade):
    module_info = (module,grade)
    return module_info

def get_module(module_info):
    return module_info[0]

def get_grade(module_info):
    return module_info[1]

def get_level(module_info):
    for i in module_info[0]:
        if str.isdigit(i):
            return i

def add_grade(gradebook, module_grade):
    gradebook.append(module_grade)
    return gradebook

def sort_by_module(gradebook):
    gradebook.sort(key=lambda gradeb: gradeb[0])
    return gradebook

def sort_by_level(gradebook):
    gradebook.sort(key=lambda gradeb: get_level(gradeb))
    return gradebook

def grade_to_numeric_marks(grade):
    for i in grade:
        if i[0] == 'A':
            if i[1] == '+':
                return 90
            elif i[1] == '-':
                return 80
            else:
                return 75
        elif i[0] == 'B':
            if i[1] == '+':
                return 70
            elif i[1] == '-':
                return 65
            else:
                return 60
        else:
            if i[1] == '+':
                return 55
            elif i[1] == '-':
                return 50
            else:
                return 46
    return grade.sort()

def sort_by_grade(gradebook):
    gradebook.sort(key=lambda gradeb: grade_to_numeric_marks(gradeb))
    return gradebook

### for testing ###
gb      = make_gradebook()
cs1010s = make_module_info('CS1010S', 'A+')
cs2020  = make_module_info('CS2020', 'A')
ma1101r = make_module_info('MA1101R', 'C')
ssa1207 = make_module_info('SSA1207', 'B+')
cs4247  = make_module_info('CS4247', 'A+')
ea5001  = make_module_info('EA5001', 'B')

add_grade(gb, cs1010s)
add_grade(gb, cs2020)
add_grade(gb, ma1101r)
add_grade(gb, ssa1207)

sort_by_grade(gradebook): return a new copy of the gradebook that is sorted by module grade from high to low. Make sure that 'A+' comes before 'A'
I used grade_to_numeric_marks(grade): as an helper function but I am still not able to get the output I want which is [('CS1010S', 'A+'), ('CS2020', 'A'), ('SSA1207', 'B+'), ('MA1101R', 'C')] What's wrong ?

A: What if you, instead of having multiple if/elif/else checks, define dictionaries grade->value and sign-value. Then, in the key function grade_to_numeric_marks just sum up base points per grade and points per sign (+/- or empty).
For example (you may need to tweak values per grade/sign a bit):
points = {'A': 80, 'B': 65}
signs = {'+': 10, '-': -5}

def grade_to_numeric_marks(item):
    grade = item[1]
    return points.get(grade[0], 50) + signs.get(grade[1:], 0)

def sort_by_grade(gradebook):
    return sorted(gradebook, key=lambda x: grade_to_numeric_marks(x), reverse=True)

grades = [('CS1010S', 'A+'), ('MA1101R', 'C'), ('SSA1207', 'B+'), ('CS2020', 'A')]
print sort_by_grade(grades)

prints:
[('CS1010S', 'A+'), ('CS2020', 'A'), ('SSA1207', 'B+'), ('MA1101R', 'C')]

Or, as @clutton mentioned in the comments, define just one dictionary with a mapping grade to points:
{'A+': 95, 'A': 90 ... }

Then, you can simplify the sorting:
points = {'A+': 95, 'A': 90, 'B+': 70, 'B': 65, 'C+': 55, 'C': 50}  # need to define all of the possible grades

grades = [('CS1010S', 'A+'), ('MA1101R', 'C'), ('SSA1207', 'B+'), ('CS2020', 'A')]
print sorted(grades, key=lambda x: points.get(x[1]), reverse=True)

A: Here's an OO rewrite:
class Module:
    def __init__(self, name):
        self.name = name

    @property
    def level(self):
        for ch in self.name:
            if ch.isdigit():
                return int(ch)

class Grade:
    grade_marks = {
        "A+": 90,
        "A-": 80,
        "A":  75,
        "B+": 70,
        "B-": 65,
        "B":  60,
        "C+": 55,
        "C-": 50,
        "C":  46
    }

    def __init__(self, grade):
        self.grade = grade

    @property
    def mark(self):
        return Grade.grade_marks[self.grade]

class ModuleGrade:
    def __init__(self, module, grade):
        self.module = module if isinstance(module, Module) else Module(module)
        self.grade  = grade  if isinstance(grade,  Grade ) else Grade(grade)

    def __str__(self):
        return "{}: {}".format(self.module.name, self.grade.grade)

class StudentGrades:
    sortkeys = {
        "module": lambda mg: mg.module.name,
        "level":  lambda mg: mg.module.level,
        "grade":  lambda mg: -mg.grade.mark    # Note: the -ve makes it descending order
    }

    def __init__(self, name, module_grades = None):
        self.name = name
        if module_grades is None:
            self.module_grades = []
        else:
            self.module_grades = [mg if isinstance(mg, ModuleGrade) else ModuleGrade(*mg) for mg in module_grades]

    def add_grade(self, *args):
        if len(args) == 1:
            mg = args[0]
            if isinstance(mg, ModuleGrade):
                self.module_grades.append(mg)
            else:
                self.module_grades.append(ModuleGrade(*mg))
        elif len(args) == 2:
            self.module_grades.append(ModuleGrade(*args))
        else:
            raise ValueError("Bad arguments to StudentGrades.add_grade")

    def sort(self, key, reverse=False):
        key = StudentGrades.sortkeys.get(key, key)
        self.module_grades.sort(key=key, reverse=reverse)

    def __str__(self):
        return "\n".join([self.name] + ["  {}".format(mg) for mg in self.module_grades])

And here's how you use it:
nf = StudentGrades("Norman Foster", [("CS1010S", "A+"), ("CS2020", "A")])
nf.add_grade("MA1101R", "C")
nf.add_grade("SSA1207", "B+")
nf.add_grade("CS4247", "A+")
nf.add_grade("EA5001", "B")

print(nf)    # original insertion order

nf.sort("module")
print(nf)    # alphabetical by module name

nf.sort("level", reverse=True)
print(nf)    # in descending order by level

nf.sort("grade")
print(nf)    # descending order by grade


text:
Q: would this be an example of deep copy? int[] a = new int[10];
for (int i = 0; i < 10; i++) {
    a[i] = randomFill();//randomFill is a method that generates random numbers
}

int[] b = new int[a.length];
for (int j = 0; j < a.length; j++) {
    b[j] = a[j]
}

int[] c = new int[a.length];
for(int k = 0; k < a.length; k++) {
    c[k] = a[k]
}

are both array b and array c the deep copy of array a?
I need to modify array a but want to keep its original values so that I can use it for later and the hint I received was to use deep copy. I can't tell if my code is considered as deep copy ...

A: a is an array of int(s), they only have a primitive value - so the answer is yes. Modifying b (or c) will not affect a. But, you could use Arrays.copyOf(int[], int) like
int[] b = Arrays.copyOf(a, a.length);
int[] c = Arrays.copyOf(a, a.length);

A: Deep copy term couldn't be applied to copying plain array of integers. This is about more complex data structures like collections of objects which can also contain nested objects/collections.


text:
Q: This error happened while generating the page. Any console logs will be displayed in the terminal window 1st time its show this error

I want to make an API call to my API route using Axios. When I run my code the first time its shows that error but when I refresh my mage it works perfectly. I can't understand what I do.
import axios from "axios";
import Head from "next/head";
import Banner from "../components/Banner";
import Footer from "../components/Footer";
import HeroSection from "../components/HeroSection";
import ServicesSection from "../components/ServicesSection";
import MyWork from "../components/work/MyWork";

function Home({ workList }) {
  return (
    <>
      <Head>
        <title>EmonS - Fullstack web developer & Designer</title>
        <meta
          name="description"
          content="This is a portfolio website which made by Jahidul Islam Emon. Here you can find work history and knowledge about Author. That is a One page application. Enjoy ."
        />
        <meta
          name="keywords"
          content="Creative, minimal, Portfolio, business, Resume, Information, personal portfolio, Professional"
        />
        <meta name="author" content="Jahidul Islam Emon"></meta>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <HeroSection />
      <ServicesSection />
      <MyWork emon={workList} />
      <Banner />
      <Footer />
    </>
  );
}

export async function getServerSideProps() {
  const mydomain = process.env.MY_DOMAIN;

  const res = await axios.get(mydomain + "/api/work");
  return {
    props: {
      workList: res.data,
    },
  };
}

export default Home;

why this error happens?

A: Make sure to add the await operator before dbConnect in your api, I had the same issue and this solved it...
so it should look like this:
await dbConnect();


text:
Q: How to update PR_DISPLAY_NAME for a meeting? PR_DISPLAY_NAME is updated which gets reflected in the folder structure. But the same doesn't get updated when a new meeting option is chosen. Old display name is displayed for the 'from'. PidLidInternetAccountName returns the old PR_DISPLAY_NAME.
How to update the PR_DISPLAY_NAME when 'new meeting' is chosen?

A: PR_RCVD_REPRESENTING_NAME_W (DASL name http://schemas.microsoft.com/mapi/proptag/0x0044001F).


text:
Q: Can't create Performance point data source at subsite level I cannot create PPS data source(DS) at sub-site level.
For example :
when I am creating DS at site : https://mysp.a.b
then everything works.
When I am trying to create DS at subsite :  https://mysp.a.b/mysubite
then I am getting following error :
"An unexpected system error has occurred. Additional details have been logged for your administrator."
I tried to add permissions to web application.
$w = Get-SPWebApplication -Identity https://mysp.a.b
$w.GrantAccessToProcessIdentity("Domain\PPS_Account")

It did not help.
Thanks in advance!

A: I will answer my own question, maybe it will help somebody.
So what I did.
1) I opened dashboard designer from root site level( https://mysp.a.b ).
2) Next in tab Home, I added the new list and pick up the DataSource list from my sub-site( https://mysp.a.b/mysubite) and I was able to create a new data source within this list.
I did the same for Dashboards/Report/Filter in this sub-site.
Hope this will some others.


text:
Q: MPPT current limitation I started to work on an MPPT project a couple of months ago. I have the first HW prototype (synchronous buck converter, current/voltage measurement, STM32 uC) and I am still fiddling with the SW side. The target is to charge a 12V Li-Ion battery from a couple of small 10W/50W solar panels.
Since I am a HW guy, the target of this project is to also learn to write good quality SW, and here I would need some help.
For the overcurrent protection, I will implement it in HW and make sure that the MOSFET driver gets disabled and the MOSFETs are turned off if an overcurrent situation occurs.
Now, for the bulk charging of the battery, I need a good implementation of the current limitation. The structure of the code is to check the battery state and if the battery is discharged, start the Bulk charging mode with the MPPT algorithm. If the panels are capable of delivering more than the current I am looking to charge/cell, I need a SW implementation to limit this.
Right now, I am testing the classic (if current > limit, DutyCycle--), but I feel this is kind of rough.
Can you guys give me some advices towards some better implementations of this feature? Also, voltage limitation needs to be implemented as well at the end of charging.


text:
Q: Distance calculation in Geopy I am using Python 2.6.6 on Centos 6.
I have a dataframe that I am bringing in from a pickle file. Then I'd like to calculate the distance between 2 points. I have tried to combine the lat and long for each point into a tuple and then used Geopy.great_circle. However the traceback includes this:
/opt/rh/python27/root/usr/lib/python2.7/site-packages/geopy/point.pyc in __new__(cls, latitude, longitude, altitude)
127                     )
128                 else:
--> 129                     return cls.from_sequence(seq)
130
131         latitude = float(latitude or 0.0)

/opt/rh/python27/root/usr/lib/python2.7/site-packages/geopy/point.pyc in from_sequence(cls, seq)
351         """
352         args = tuple(islice(seq, 4))
--> 353         return cls(*args)
354
355     @classmethod

TypeError: __new__() takes at most 4 arguments (5 given)

My input is from a Pandas DataFrame that should be of the same length (if that matters?)
import numpy as np
from geopy.distance import vincenty
import geopy
import pandas as pd

distances_frame = pickle.load(open("distances.p", "rb"))
samp = distances_frame.sample(n=50)
samp = samp.dropna()
point1 = tuple(zip(samp['biz_lat'],samp['biz_lon']))
point2 = tuple(zip(samp['id_lat'],samp['id_lon']))
dist= (vincenty(point1,point2).miles)

A: EDIT     'EdChum' has the correct answer in comments above..
samp.apply(lambda x: vincenty((x['biz_lat'],x['biz_lon']), (x['id_lat'],   x['id_lon'])).miles, axis=1)


text:
Q: Wordpress wp-admin error 403 files in wp-admin are accessable I have a blog running and everything seems to be fine.
But I cannot access
/wp-admin/ ==> 403
it is only that directory, which is not accessable...
I can easily access /wp-admin/edit.php and every other file within this directory (also /wp-admin/index.php is working...)
directory permission is set to 755
htaccess from blog root:
# BEGIN WordPress
# Die Anweisungen (Zeilen) zwischen "BEGIN WordPress" und "END WordPress" sind
# dynamisch generiert und sollten nur über WordPress-Filter geändert werden.
# Alle Änderungen an den Anweisungen zwischen diesen Markierungen werden überschrieben.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Website is running on a root server with plesk installed.
Does anyone have an idea how I can fix this?
thank you so much
cheers
D

A: Solved by changing web application firewall from Comodo to Atomic.

A: Fixed the 403 error for /wordpress/wp-admin/ by disabling the ModSecurity rule CWAF in Plesk.


text:
Q: Telerik RadDatePicker Month and Year is scrolling Am using Telerik RadDatePicker control in asp.net framework 4.5 application.
When the mouse is scrolled in RadDatePicker control, the year/month part is automatically changing. We need to stop this behavior.
How to achieve this? Please help.


text:
Q: UIImage does not scroll in iPhone I am new to iPhone developer,
I want scrolling in my Image,
Here is my code snippet,
- (void)viewDidLoad {
UIImage *image1 = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bg.png"]];
    self.imageView = [[UIImageView alloc] initWithImage:image1];
    self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image1.size};
    [self.scrollView addSubview:self.imageView];
    self.scrollView.contentSize = image.size;

 [self centerScrollViewContents];
}

- (void)centerScrollViewContents {
    CGSize boundsSize = self.scrollView.bounds.size;
    CGRect contentsFrame = self.imageView.frame;

    if (contentsFrame.size.width < boundsSize.width) {
        contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
    } else {
        contentsFrame.origin.x = 0.0f;
    }

    if (contentsFrame.size.height < boundsSize.height) {
        contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
    } else {
        contentsFrame.origin.y = 0.0f;
    }

    self.imageView.frame = contentsFrame;
}

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    // Return the view that you want to zoom
    return self.imageView;
}

also bg.png is not getting applied to my background.
Any help will be appreciated.

A: the answer is actually a combination of many of the other answers & comments, plus some other adjustments.

*

*as Pan said, you need to set your scrollView delegate.  otherwise, your
viewForZoomingInScrollView: delegate implementation won't get called.
i've provided this call in viewDidLoad: , though you can also hook this
up in interface builder or storyboard.

*as Teodor Carstea said in the comments to the original post, in your
original  code, you are setting your .imageView.size and your
.scrollView.contentsSize to exactly the same thing.  you don't need
the code that sets the .imageView.frame.  that will happen as part of
initWithImage: .  and this will make the sizes different.

*you do need to set the .scrollView.contentSize to the image.size .
it sort of matters where ou do this, at least in terms of that it must
happen prior to setting the zoom scale.

*as Kunal Balani mentioned, you have to have scrollingEnabled, though you
can set this in storyboard or interface builder.

*as MidhunMP said, you have to have .userInteractionEnabled = YES, though
generally, these are the defaults that get set in storyboard/Interface Builder,
so i'm not going to include them in the code changes below.

*your method centerScrollViewContents isn't really centering the contents
as much as it is re-shaping the imageView frame.  i've simply commented out
the call, because i think it's completely unnecessary.  instead, i've made
a simple call to start your image in the upper left corner.

*if you only want to scroll, setting the zoomScale, minimumZoomScale and
maximumZoomScale is not necessary.  if you also want to pinch-zoom, then
you will need to set all three of these, and in the proper places.

*you do seem to want to stretch the view if it is smaller than the content
bounds.  if this is truly a concern (i.e. if you know your bg.png is so
small that it needs to be stretched), then calculate the contentFrame to
image frame width ratio and height ratio separately, and whichever of
these is larger will be your new zoomScale, and you'll be able to scroll
in the other direction.  or, there are other ways to decide how you want
that scale set.  search stackoverflow.com for other answers for setting
the zoom scale as desired.

here's the code after applying these items.
(void)viewDidLoad {
    self.scrollView.delegate = self;         // can be set in storyboard
    self.scrollView.scrollingEnabled = YES;  // can be set in storyboard
    NSString* bgPng
      = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bg.png"];
    UIImage *image1 = [UIImage imageWithContentsOfFile:bgPng];
    self.imageView = [[UIImageView alloc] initWithImage:image1];
//  self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image1.size};
    [self.scrollView addSubview:self.imageView];
    self.scrollView.contentSize = image.size;

    // set zoom scale here if desired.

    // if zoom is implemented, the following call should be made
    // after setting .zoomScale, .minimumZoomScale & .maximumZoomScale
    self.scrollView.contentOffset = CGPointZero;

//  [self centerScrollViewContents];
}

//- (void)centerScrollViewContents {
//    CGSize boundsSize = self.scrollView.bounds.size;
//    CGRect contentsFrame = self.imageView.frame;
//
//    if (contentsFrame.size.width < boundsSize.width) {
//        contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
//    } else {
//        contentsFrame.origin.x = 0.0f;
//    }
//
//    if (contentsFrame.size.height < boundsSize.height) {
//        contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
//    } else {
//        contentsFrame.origin.y = 0.0f;
//    }
//
//    self.imageView.frame = contentsFrame;
//}

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    // Return the view that you want to zoom
    return self.imageView;
}

A: well, try this :
UIImageView *tempImgv = [[[UIImageView alloc]init] autorelease];
    [tempImgv setImage:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/bg.png", [[NSBundle mainBundle]resourcePath]]]];
    [tempImgv setFrame:your_desired_frame];
    self.imageView = tempImgv;
    [self.scrollWiew setContentSize: size_greater_than_scroll_frame];
    [self.scrollWiew addSubview:self.imageView];

A: First of all check your scrollview frame . Scrolling will be enabled only when frame size is < contentsize. Because if all the content is visible in frame then why do you need scrolling at all ??
try this :

 UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,
                 self.view.frame.size.width, self.view.frame.size.height)];
    //init with whatever frame you have

  scroll.scrollEnabled = YES // this is imp ... don't ignore this

   //whatever your code is

    self.scrollView.contentSize = image.size;// this is wrong

    //contentSize property to the size of the scrollable content. This specifies the size of the scrollable area.
    // do this
    self.scrollView.contentSize = imageView.frame.size;

A: Set the user interaction enabled property of image view and scroll view to yes.
Please check with this code,
- (void)viewDidLoad
{
    UIImage *image1 = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bg.png"]];
    self.imageView = [[UIImageView alloc] initWithImage:image1];
    self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image1.size};
    imageView.userInteractionEnabled = YES;
    scrollView.userInteractionEnabled = YES;
    [self.scrollView addSubview:self.imageView];
    self.scrollView.contentSize = image.size;

    [self centerScrollViewContents];
}

And if you need to set the image as your scroll view's background, use this:self.scrollView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bg.png"]]];

A: In the above code, you have provided
    UIImage *image1 = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bg.png"]];
    self.imageView = [[UIImageView alloc] initWithImage:image1];
    self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image1.size};
    [self.scrollView addSubview:self.imageView];
    self.scrollView.contentSize = image.size;

The content size of scrollView which you are setting is equal to the size of the image i.e the above bolded code. Try with the following code.
CGSize sizeOfScroll = image.size;
sizeOfScroll.width *= 1.5f;
sizeOfScroll.height *= 1.5f;

self.scrollView.contentSize = sizeOfScroll;

A: scrolling the images
scroll.userinteractionEnable = YES;

and other then,
self.scrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"image.png"]]];

A: In the code above, you need to set the minimum and maximum zoom scale.
http://developer.apple.com/library/ios/#DOCUMENTATION/WindowsViews/Conceptual/UIScrollView_pg/ZoomZoom/ZoomZoom.html

self.scrollView.minimumZoomScale=0.5;
self.scrollView.maximumZoomScale=6.0;

A: Did you set the scrollview delegate somewhere else?
Like this: self.scrollView.delegate = self;


text:
Q: Calling stored proc from bash script, ORA-01756: quoted string not properly terminated I'm attempting to call a stored procedure from a bash script, from a python script. The script calling works fine, there's no issue there. The issue is with the parameter for the PRIMARY_KEYS field. With a single PK it works fine, but for multiple PK ie, A, B, C, I get the oracle error: ORA-01756: quoted string not properly terminated
Python:
...
cmd = 'sh pkg_mypkg.sh \'%s\' \'%s\' my_sp_which_adds_a_primary_key \'%s\'' % db_login_str db_table primary_keys
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=TRUE)
...

Bash:
DB_LOGIN_STR=$1
DB_TABLE=$2
FUNC_TO_EXEC=$3
PRIMARY_KEYS=$4

...

function my_sp_which_adds_a_primary_key() {
  SP_RES=`sqlplus -silent $1 <<-EOM
  ...
  BEGIN
    pkg_mypkg.my_sp_which_adds_a_primary_key($2, $3);
  END;
  ...
  EOM`
  echo $SP_RES
}

...

function main() {
  case $FUNC_TO_EXEC in
     "my_sp_which_adds_a_primary_key")
        my_sp_which_adds_a_primary_key(DB_LOGIN_STR, DB_TABLE, PRIMARY_KEYS);;
  esac
}

main

SP:
procedure my_sp_which_adds_a_primary_key(db_table in varchar2, primary_keys in varchar2)
is
begin
 execute immediate 'alter table ' || db_table || ' add constraint ' || db_table || '_PK primary_key (' || primary_keys || ') parallel 8';
end my_sp_which_adds_a_primary_key;

As a disclaimer, I've tested this function directly within the PLSQL UI interface, in a test window, and it works fine w/ multiple PKs. There's a problem with how I am passing to the stored proc when executed within Bash, which I cannot figure out. I've tried combinations of \'\'%s\'\', \'%s\', \'\"%s\", "%s", ... Not sure what the right format is.
Thanks in advance,

A: First thing I'd try is to call the command from your Python code like this:
cmd = ["pkg_mypkg.sh", db_login_str, db_table, "my_sp_which_adds_a_primary_key", primary_keys]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

From the documentation (my emphasis):

args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

Also, I've removed shell=TRUE as well as the call to sh, as they can both cause complications and, in the case of the former, security risks. You should instead simply ensure that pkg_mypkg.sh is executable with a proper shebang. The documentation again:

On Unix with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

Without seeing the full shell script it's hard to say what problems there might be, though you are calling variables without a preceding $, and I'd recommend putting the SP text into a file rather than rely on a construct like heredoc inside backticks. http://shellcheck.net/ can be helpful to spot errors and non-standard usage.


text:
Q: Select between a range of number insert if doesn't exist Can i select between 1 - 20  which number doesnt exist from this table and then insert one of my numbers  into an sql column?
example i have in my table   1
                             2
                             9
                             13

if not exists select ('%[1-20]%',column from table); insert into table select....?

*

*I dont want insert all numbers which not exist i want one of them

A: Use numbers table..
;With cte
as
(
select top 20 number
from numbers
order by number
)
Insert into yourtable
select top 1* from cte c1 where not exists(select 1 from yourtable t2 where t1.number=t2.id)

You also can use join..
Insert into yourtable
select top 1 number
from
numbers n
join
yourtable t
on t.id<>n.number
and n<=20


text:
Q: CDK's CodePipeline or CodeBuildStep are leaving an S3 bucket behind, is there a way of automatically removing it? I'm creating a CloudFormation stack using CDK with code roughly like this:
export class PipelineStack extends cdk.Stack {
    constructor(scope: Construct, id: string, props: PipelineStackProps) {
        super(scope, id, props)
        new pipelines.CodePipeline(this, id, {
            pipelineName: id,
            synth: new pipelines.CodeBuildStep("Synth", {
                    input: pipelines.CodePipelineSource.connection(props.githubRepo, props.repoBranch, {connectionArn: props.repoConnectionArn}),
                    installCommands: ["npm install -g aws-cdk"],
                    commands: ["npm ci", "npx cdk synth"],
                },
            ),
        })
    }
}

and that stack creates an S3 bucket that when I delete the stack isn't deleted with it. I searched for options and I couldn't find any to control that behaviour. Is it possible to mark that S3 bucket as cdk.RemovalPolicy.DESTROY or something like that?

A: I'm assuming you're referring to the artifacts bucket. It can be accessed via the CodePipeline.pipeline.artifactBucket. You need to do this after you define the whole pipeline and call myPipeline.buildPipeline();
myPipeline.buildPipeline();
const artifactBucket = myPipeline.pipeline.artifactBucket;
artifactBucket.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);

Documentation:

*

*CodePipeline#pipeline

*Pipeline#artifactbucket
Although this wouldn't solve the issue of the bucket being non-empty and failing to delete. To solve this properly, you need to create your own Pipeline with a bucket you create yourself and pass it to CodePipeline's constructor in the codePipeline property:
const artifactBucket = new s3.Bucket(this, 'artifactBucket', {autoDeleteObjects: true});
artifactBucket.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);

const underlyingPipeline = aws_codepipeline.Pipeline(this, 'underlyingPipeline', {artifactBucket: artifactBucket});

const pipeline = pipelines.Codepipeline(this, 'myPipeline', {codePipeline:underlyingPipeline, ...});


text:
Q: How to select first occurrence between two patterns including them How can I select first occurrence between two patterns including them. Preferably using sed or awk.
I have:
text
something P1 something
content1
content2
something P2 something
text
something P1 something
content3
content4
something P2 something
text

I want the first occurrence of the lines between P1 and P2 (including P1 line and P2 line):
something P1 something
content1
content2
something P2 something

A: sed '/P1/,/P2/!d;/P2/q'

...would do the job portably by deleting all lines which do !not fall within the range, then quitting the first time it encounters the end of the range. It does not fail for P2 preceding P1, and it does not require GNU specific syntax to write simply.

A: awk '/P1/,/P2/{print;f=1} f&&/P2/{exit}' data

Quit immediately after print, not before.

A: with awk
awk '/P1/{a=1};a;/P2/{exit}' file
something P1 something
content1
content2
something P2 something

A: In sed:
sed -n '/P1/,/P2/p; /P2/q'

*

*-n suppresses the default printing, and you print lines between the matching address ranges using the p command.

*Normally this would match both the sections, so you quit (q) when the first P2 matches.

This will fail if a P2 comes before P1. To handle that case, try:
sed -n '/P1/,/P2/{p; /P2/q}'

A: If you want to skip the patterns themselves, here is the awk version:
awk '/P2/ {exit} /P1/ {f=1; next} f' file

A: A simpler awk solution (sort-of halfway between
iruvar's answer and muru's answer, but not using a variable):
awk '/P1/,/P2/ { print }  /P2/ { exit }'

and, as muru noted,
if the first P2 appears before the first P1, this will print nothing.
Of course, if you want to print all the P1-P2 ranges:
something P1 something
content1
content2
something P2 something
something P1 something
content3
content4
something P2 something

just leave out the exit part:
awk '/P1/,/P2/ { print }'

A: To skip the patterns themselves, and show only first matching block in single GNU sed:
sed -nre '/STARTPATTERN/ {:a;n;/ENDPATTERN/{b;};p;ba}' file

A: awk '/something P1/{f=1}/something P2/{f=0;print;exit}f'  file

output
something P1 something
content1
content2
something P2 something

A: sed: (from @SU3's comment):
sed -n '/P1/,${p;/P2/q}'

awk:
awk '/P1/,0 {print; if ( /P2/ ) exit}' file

Both take the same approach: Within the range /P1/ to end of input, print and then exit if P2 is matched.
Both are DRY. P1 and P2 are specified only once.
Both pass the corner case of P2 preceding P1.

A: Using Raku (formerly known as Perl_6)
raku -ne 'state $i=0; .put if m/ P1 {last if $i++ == 1} /fff/ P2 /;'

#OR

raku -e 'my $i=0; .put if m/ P1 {last if $i++ == 1} /fff/ P2 / for lines;'

#OR

raku -e 'my $i=0; for lines() { .put if m/ P1 {last if $i++ == 1} /fff/ P2 / };'

Sample Input:
text
something P1 something
content1
content2
something P2 something
text
something P1 something
content3
content4
something P2 something
text

Sample Output (1):
something P1 something
content1
content2
something P2 something

The above answer is coded in Raku, a member of the Perl-family of programming languages. Explaining the first answer briefly, Raku's non-autoprinting -ne command line flags are employed to run code over each line of input. Raku's m/<start>/fff/<stop>/ sed-like "flip-flop" operator is employed which takes linewise input (special-cased within the Rakudo compiler), enabling the return of text blocks that start with the first matching line and stop with the second matching line. The variable $i is stated once at the beginning of the loop to equal 0 zero. Finally, Raku also allows code blocks to execute within Regexes upon matching.
Putting it all together, when the sed-like "flip-flop" operator encounters a full match in both (start,stop) halves of the fff regex operator, $i gets incremented to 1, and thus lasts out of the loop, so only the first complete match is put. [If you want to output all matches, simply omit the {last if $i++ == 1} code block].
Note, it's simple enough to omit the two 'sentinal' lines in the return by changing fff to ^fff^, giving the following result:
Sample Output (2):
content1
content2

Further testing: All code above handles the case where P2 comes before P1. Additionally, all code above handles the case where P1 and P2 occur on the same line, WITHOUT terminating prematurely. If such "single line text blocks" are desired/preferred in the output, use Raku's "non-sed-like" ff operator instead of the fff operator.
https://docs.raku.org/routine/fff
https://raku.org


text:
Q: Mailchimp update from mailchimp to mysql I'm currently trying to implement mailchimp to keep my mysql database and mailchimp subscribers list synced.
I'm using this library: https://github.com/drewm/mailchimp-api/ and from mysql to mailchimp, everything works fine, but I'm wondering how I can do the reverse operation: update from mailchimp to my site.
Thanks for your help ;)

A: You'll need to use the MailChimp webhooks.  When something interesting happens in Mailchimp, they will send a POST request to a url that you specify (via the admin controls in Mailchimp, or an API call), with information about whatever it was that happened.
The Mailchimp docs about this are: https://apidocs.mailchimp.com/webhooks/
I don't know of any libraries that could help with this at your end, I'm afraid.


text:
Q: implications of a successful read from Cassandra This is the context:

*

*reading by primary key (only one row should be returned)

*reading from a quorum among 3 replicas

*don't care whether quorum agrees on contents of the row

*just care whether every node in quorum has the row

This is my understanding of Cassandra read behavior.

*

*Cassandra reads the contents of a row from one node in the quorum

*other nodes in the quorum receive a digest read

*the digests of nodes are compared

*in the case of mismatch, the latest version of the row from any of the nodes in the quorum is returned

My problem is that I don't know what mismatch implies. Is an empty (missing row) digest considered a mismatch? Does a successful read imply that the nodes in the quorum all have the row?

A: A mismatch implies difference in timestamp of a column for the row. A missing row is considered a failure and the Quorum consistency will not be met and no data returned. It will eventually lead to read repair on the node which did not have data.


text:
Q: How to build target variable for supervised machine learning project I am quite new to machine learning with small experience and I did some projects.
Now I have a project relates to insurance. So I have databases about clients that I will merge to get all possible information about the clients and I have one database for the claims. I need to build a model to identify how risky the client based on ranks.
My question: I need to build my target variable that ranks the clients based on how risky they are, counting on the claims. I could have different strategies to do that, but I am confused about how I will deal with the following:
- Shall I do a specific type of analysis before building the ranks such as clustering, or I need to have a strong theoretical assumption matching with the project provider vision.
- If I use some variables in the claims database to build up the ranks, how shall I deal with them later. In other words, shall I remove them from the final data set for training, to avoid correlation with target variable, or I can treat them in a different way and keep them.
- If I will keep them, is there a special treatment for them depending on whether they are categorical or continuous variables.

A: Every machine learning project's starting point is EDA. First create some feature, like how often do they get bad claims or how many do they get. Then do some EDA to find which features are more useful. Secondly, the problem looks like classification. Clustering is usually harder to evaluate.

A: In data sciences when you make a business model, EDA exploratory data analytics play a major role which includes data cleaning, feature engineering, filtering data. As mentioned how to build target variable, it all depends on the attributes you have and what model do you want to apply say linear regression or logistic or make a decision tree. You need to use those algorithms. But most importantly you need to find out the impacting variable. That's probably the core elation between the output and the given input and priority must be given accordingly. Also attributes which add no value must be removed as that would contribute to overfitting.
You can do clustering too. And interesting thing is any unspervisoned learning could be converted to a form of supervised learning. Probably you can try to do logistic regression or do linear regression etc... And find out which model fits best to your project.


text:
Q: Single board computer (SBC) with industrial grade I was using single board computer (Raspberry Pi, Beaglebone) to develop prototypes. A new requirement is that the prototype should satisfy "industrial grade" with regarding to (for example):
Temperature (e.g. -40 to 85 degree)
humidity
life cycle (e.g. 10 years)
mean time between failure (MTBF) (e.g. > 80,000 ~ 100,000 hours)

For another example, I find one of the issue is: many SBC uses SD card to load OS. I guess most SD card cannot run for years without stopping.
Meanwhile, the SBC should also support similar functionalities (e.g. Linux OS, required physical interfaces, enough memory). (I guess this is not a potential problem).
How can I find such industrial grade SBCs? Many commercial products (e.g. firewall hardware) can satisfy industrial grade. Where do their SBCs come from?

A: The rating of a product for environmental conditions is more than the sum of its components.
So, yes, you sure don't want to use an SBC with the cheapest allwinner SoC but rather something based on chips that are specified for a larger temperature range(look at the SoCs of eg. NXP and TI), but the rating of your overall product stems from your product design - for example, a chip that is solidly connected thermally to the case might happily work at 65°C environment temperature, because it won't get much warmer when cooling is good.
To get a device certified for industrial environmental conditions, you need to do the whole-system testing of the complete device; looking at its components won't get you far.


text:
Q: In a UISplitViewController what should you do when you delete the last object in a detail view I have a SplitViewController with a rootViewController tableview and a detailView tableview.
The rootViewController contains objects which contain objects in the DetailViewController. If there are no objects in the rootViewController objects then the rootViewController object is removed.
e.g. One Story contains Many Sentences
If you have a Story selected, and you delete the last sentence it contains in the detailViewController - what should you do to the detailViewController? The story is successfully removed from the rootviewcontroller, but I'm not sure what to do in the detailViewController. In an iPhone specific app I would just pop back the navigation controller from sentences to stories, but I'm not sure what to do when the detailViewController is always visible as it is with a svc.
I've tried:

*

*Setting the detailViewController as a blank tableview

*Setting the current story object as blank

If I choose to do nothing, I get an CoreData exception:

CoreData: error: Serious application error.  An exception was caught
  from the delegate of NSFetchedResultsController during a call to
  -controllerDidChangeContent:.  attempt to insert row 7 into section 0, but there are only 1 rows in section 0 after the update with userInfo
  (null)

A: Make sure your master view controller can handle an empty list and load a new detail view controller with a label in the middle saying something like "No items".
Try creating a new folder ("mailbox") in Mail and going into it.
Alternatively, if deleting everything means it's not useful to show an empty list, you can also automatically pop to the previous navigation level.


text: Q: OSError errno 13 Permission Denied Python CGI os.listdir I am executing os.listdir() from Python CGI script. Script executes from console with no problem but when it is called from the web interface I get OSError errno 13 Permission Denied. It is denying permission to files in a different directory /usr/local/bin/ I checked permission levels and even changed owner and group to apache. I Even added Apache Directory configurations to allow all in ssl.conf file. Any thoughts? Thank you all in advance for the guidance.


text:
Q: Get list of dependencies for Ruby program I have a Ruby program that is part of a very large code base that I would like to extract and use elsewhere.
The program in question requires several other files that are in different directories, and those files in turn depend on several other files, and so on and so forth.
Is there a quick way that I can get a list of all the files this program depends on, and the directories they live in, so that I can just take the stuff I need?
I feel like there must be some way to see this if I load up the file in IRB, but I can't think of which method or module I might need for this kind of introspection. Googling has not helped much either.

A: You have some options if you're open to heuristics.
Option 1: Unix find

*

*Are all the files within any kind of top level directory, such as "/foo/bar/"?

*Are you able to run just the Ruby program, not the rest of the large code base?

*If yes, then you can find all the directories and files that the Ruby program touches:
find /foo/bar -atime -1

*An advantage of this option is that finds the Ruby code plus assets the program needs, such as css, images, javascripts, etc.

*A caveat: if the command doesn't turn up anything, then your file system may be caching the atime settings for a day; to learn more google "noatime".
Option 2: DTrace

*

*Similar to the -atime solution above, DTrace can profile a running application and report which files are accessed.

*An advantage of this option is that you get real-time results as the program runs, and you can attach to just the program process.
Option 3: Intercept Kernel.require

*

*If you're only interested in the Ruby code that runs, not interested in the assets, then you can intercept the Ruby file require method.
module Kernel
  alias_method :old_require, :require

  def require(name)
    puts "requiring #{name}"
    old_require(name)
  end
end

*An advantage of this solution is that it shows just the Ruby runnable files, not any of the the assets.

*An advantage is that you can extract the code ad-hoc using conditional logic. For example you can extract all items that contain "hello" into a different directory like this:
def require(name)
  if name=~/hello/
    # Whatever logic you want goes here,
    # such as dynamically altering the load path,
    # or altering the name, or skipping the require.
  end
  old_require("#{my-original-location}/name")
end

*A caveat of this solution vs. the other solutions above, is that you won't detect Ruby code that is loaded using atypical ways, such as using File.read then eval.
Advice

*

*If your app has a Gemfile, that's a good place to look for major dependencies.

*If your app uses git submodules, that's another good place to look.

*If your app has a test suite, be sure to run it so you get all the test suite files too.

*If your app has dynamically-required files, or files that are only loaded on some of the execution paths, you'll need to find them a different way than running the app; ideally your test suite will exercise all the dynamically-required files.

*If you don't have a test suite, or the suite isn't thorough, you may want to write some simple functional tests first. You don't need 100% test coverage to start, and you don't need to focus on unit tests; you just need enough of a smoke-test to detect if you accidentally break major functionality as you extract pieces.

*If your code is important, also search your codebase for any occurences of the eval method, File class, IO class, etc. What you're looking for is any kind of dynamic loading of code and/or assets.


text:
Q: Installation wizard for a custom module Odoo I just create a simple wizard inside my custom module for Odoo. I called using a button but i need he appears when install the module Any suggestion ? i'm new in odoo world

A: You can see how this is done here. Basically a small ir.actions.todo object is created in XML, pointing to the action that is supposed to be executed:
<record id="example_configuration_installer" model="ir.actions.todo">
    <field name="action_id" ref="your_action_to_be_executed"/>
    <field name="type">automatic</field>
</record>


text:
Q: Rails if function not submitting before_create I am trying to set a boolean based on the value of another field.
However, the console output fires a not-null violation:
  Gin Create (124.6ms)  INSERT INTO "gins" ("gin_name", "snippet", "description", "abv", "created_at", "updated_at", "slug") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["gin_name", "Seedlip"], ["snippet", "Alcohol free gin"], ["description", "Seedlip have inspired alcohol free gin"], ["abv", 0.0], ["created_at", "2019-02-01 09:21:30.080931"], ["updated_at", "2019-02-01 09:21:30.080931"], ["slug", "seedlip"]]
   (0.3ms)  ROLLBACK
ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "alcoholic" violates not-null constraint)
DETAIL:  Failing row contains (56, Seedlip, Alcohol free gin, Seedlip have inspired alcohol free gin, 0, 2019-02-01 09:21:30.080931, 2019-02-01 09:21:30.080931, null, seedlip, null).
: INSERT INTO "gins" ("gin_name", "snippet", "description", "abv", "created_at", "updated_at", "slug") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"

gin table
  create_table "gins", force: :cascade do |t|
    t.string "gin_name"
    t.string "snippet"
    t.text "description"
    t.float "abv"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "distillery_id"
    t.string "slug"
    t.boolean "alcoholic"

model gin.rb
class Gin < ApplicationRecord

    before_create :is_alcoholic

    has_one :distillery
    has_many :botanicals_gin
    has_many :botanicals, through: :botanicals_gin

    validates :gin_name, :snippet, :description, presence: true
    validates :gin_name, uniqueness: true

    def is_alcoholic
      if abv > 0.1
        alcoholic = true
      end
    end

I have tried a few different callbacks before_save (I understand this would run is_alcoholic on new and updated records) and before_validation (not sure this is applicable as I don't have a validation in the model for alcoholic.
From the console I don't have a clear sense of whether that function is even attempting to run.
Am I overlooking something basic?
Update
Thanks to the answers below, I've now got the following which works for both conditions:
def is_alcoholic
  if abv == 0.0
    self.alcoholic = false
  else
    self.alcoholic = true
  end
end

I have modelled the column as I wish to use it as a filter in search.

A: You should add self to the is_alcoholic method:
def is_alcoholic
  if abv > 0.1
    self.alcoholic = true
  end
end

if you dont use self in this method, ruby just denote a local variable alcoholic = true, but you actually refer to attribute.

A: The log states that you are attempting to create a record where abv is 0.0. Therefore the condition you formulated in is_alcoholic will be false which leads to alcoholic not having a value.
Try changing the implementation to:
def is_alcoholic
  self.alcoholic = abv > 0.1
end

That way, there will always be a value set for alcoholic and it is more descriptive anyway.


text:
Q: Parse numbers from string using regex in VB.NET I am trying to parse the digits to store in a variable from a string in VB.NET (would like to also include the decimal point).
Here is an example string: Refund issued for $27.74

A: As casperOne already pointed out, one example is not sufficient to give a full solution.
The regular expression string could look like "\\$([0-9]+\\.[0-9]+)" or "Refund issued for \$(?<Value>[0-9]+\.[0-9]+)". The latter being more more restrictive.
The second example also uses a named group. This can make it easier to extract the matches after the call to Regex.Match if you have a more complex scenario.
A nice tool to play around with .net style regular expressions is Expresso.

A: You don't really need a regex for this, as a simple iteration and comparison of each character from 0-9 (or a call to the static IsNumber method on the Char structure) would do it (sorry for the C# code, it's easy enough to translate into VB.NET):
static IEnumerable<char> GetNumericCharacters(this string s)
{
     // Check for null.
     if (s == null) throw new ArgumentNullException("s");

     // Iterate through the characters.
     foreach (char c in s)
     {
         // If a number, return it.
         if (char.IsNumber(c)) yield return c;
     }
}

Of course, the regex is just as easy:
[0-9]

You can use the RegEx class to get all the matches for that pattern and concatenate them together.
The only time where each of these solutions fail is when you have multiple numbers in different contexts, e.g.:
"The user purchased 10 items at $0.99 each"


text:
Q: When I turn on my MacBook Pro, I see the Apple logo and the progress bar but then it turns off When I switch on my MacBook Pro 2011, I see the Apple logo with progress bar but before it enters the next screen it turns off. Why?

A: Troubleshooting is a process of elimination and can take quite some time. This means trying various things and reporting back with the results in order to try and get to the bottom of your problem.
Apple Hardware Test / Apple Diagnostics
The first thing to try is running Apple's built-in hardware diagnostics. To do this:

*

*Ensure your MacBook Pro is connected to AC power

*Start your computer

*Immediately press and hold down the D key before the grey screen appear

*When the icon appears on the screen let go of the D key

*Select your language and click the right arrow

*Select the "Perform extended testing" checkbox

*Click the Test button

*Take a note of the results that appear in the bottom-right window

Report back with your results.
NOTE: If holding down the D key doesn't work, you can also try holding down the OptionD keys during startup to try and run the diagnostics test via the internet.


text:
Q: how do you select an item from a listview and use it in say, a label or text using Basic4android i want to scroll to an item in a listview and select that item to use in a label or text etc
How do you code to select an item from a list say using a 'long click' or similar to highlight it??
I have found many responses to this question but I cannot see one that specifically shows this using Basic4android.
Can't help being old and stupid I guess but a thing like this shouldn't really be this hard or generate so many how too's?
Anyway thanks.

A: Have you seen the ListView Tutorial? I believe that the first example should help you get started.

A: Sub Process_Globals
    Type twostrings (aLabel As String , bLabel As String)
        Dim oGPS As GPS
End Sub

sub LoadList
            Dim ts As twostrings
            ts.Initialize
            ts.aLabel="ABC"
            ts.bLabel="ABC Description"
            listMyData.AddTwoLines2(ts.aLabel,ts.bLabel,ts)
end sub
sub listMyData_Click(Position as Int, Value as Object)
    Dim ts As twostrings
    ts.Initialize
    ts=Value
    lblLabelA.Text=ts.aLabel
    lblLabelB.Text=ts.bLabel
end sub


text:
Q: CSS: Position sticky vs fixed, why is width handled differently Take the below CSS
.page-header {
    position: sticky;
    top: 20;
    background-color: red;
    color: white;
    padding: 15px;
}

When applied to HTML

  Header - make me into a sticky header

The width of the red bar is 100%.
When I use position: fixed; the header is only as wide as the content.
Why does Fixed behave differently?


text:
Q: Laravel 5.1 Does not recognize the timestamp field in postgres I'm working with Laravel 5.1. But I cannot query the database:
I just do:  User::all(); on my UserController
Here is the error:
1/1
InvalidArgumentException in Carbon.php line 414:
Trailing data
in Carbon.php line 414
at Carbon::createFromFormat('Y-m-d H:i:s', '2015-07-19 20:32:47.313') in Model.php line 2858
at Model->asDateTime('2015-07-19 20:32:47.313') in Model.php line 2384
at Model->attributesToArray() in Model.php line 2361
at Model->toArray() in Collection.php line 871
at Collection->Illuminate\Support\{closure}(object(User))
at array_map(object(Closure), array(object(User), object(User), object(User))) in Collection.php line 873
at Collection->toArray() in Collection.php line 894
at Collection->toJson() in Response.php line 66
at Response->morphToJson(object(Collection)) in Response.php line 44
at Response->setContent(object(Collection)) in Response.php line 202
at Response->__construct(object(Collection)) in Router.php line 1225
at Router->prepareResponse(object(Request), object(Collection)) in ControllerDispatcher.php line 113
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114
at ControllerDispatcher->callWithinStack(object(UserController), object(Route), object(Request), 'index') in ControllerDispatcher.php line 69
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\UserController', 'index') in Route.php line 201
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 704
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 706
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 671
at Router->dispatchToRoute(object(Request)) in Router.php line 631
at Router->dispatch(object(Request)) in Kernel.php line 229
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 54
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 118
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 86
at Kernel->handle(object(Request)) in index.php line 54

This is my user model
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //
}

This is my UserController
<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = User::all();
        // return view('users.index', compact('users'));
        return $users;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}

And This is my postgres SQL code
DROP TABLE IF EXISTS users CASCADE;

CREATE TABLE users
(
   id              serial         NOT NULL,
   code            varchar(255),
   login           varchar(50)     NOT NULL,
   name            varchar(255)    NOT NULL,
   email           varchar(255)    NOT NULL,
   password        varchar(60)     NOT NULL,
   remember_token  varchar(100),
   created_at      timestamp       NOT NULL,
   updated_at      timestamp       NOT NULL
);

-- Column id is associated with sequence public.users_id_seq

ALTER TABLE users
   ADD CONSTRAINT users_pkey
   PRIMARY KEY (id);

COMMIT;

What's wrong?? Please help.
Is there any configuration file that I missing??

A: After reading this http://laravel.io/forum/08-31-2014-invalidargumentexception-for-postgresql-database I decided to create model that extends default model class and replaces getDateFormat with custom code.
Because changing classes in vendor directory is bad idea.
I hope it helps:
class FixedModel extends Illuminate\Database\Eloquent\Model {
    public function getDateFormat()
    {
        return 'Y-m-d H:i:s.u';
    }
}

class User extends FixedModel {}

A: You should declare $dateFormat in your model class:
protected $dateFormat = 'Y-m-d H:i:s.u';


text:
Q: Creating an associative array from grep results in bash I am using the following loc in a bash script to return unique grep result strings and their counts:
 hitStrings="$(eval 'find "$DIR" -type f -print0 | xargs -0 grep -roh "\w*$searchWord\w*"' | sort | uniq -c)"

For example, if I have a $searchWord of "you", I could get the following results:

5 Kougyou 2 Layout 10 layouts 2330 you 859 your 17 yourself

My questions are:

*

*How to I created an associative array containing the strings that are returned as the keys, and their counts as the values?

*How do I omit the initial searchWord and its count from the associative array above (so no you-859 when I search for "you")?

Thanks

A: you have too many unnecessary layers, you can achieve the same with
$ grep -roh "\w*$key\w*" | sort | uniq -c > counts

and
$ declare -A counts; while read -r v k; do counts[$k]=$v; done < counts
$ echo ${counts["you"]}

Note that depends on the usage, you may get away by the file itself.  Again searching for "you" count from the file
$ awk -v key="you" '$2==key{print $1}' counts

if the same name confuses you change one of them, or remove the temp file altogether by substitution.
$ declare -A counts
$ while read -r v k; do counts[$k]=$v; done < <(grep -roh "\w*$key\w*" | sort | uniq -c)

or with evil eval you can do
$ eval declare -A counts=( $(grep -roh "\w*$key\w*" | sort | uniq -c | awk '{print "["$2"]="$1}') )

but why?  The while loop is a perfectly fine solution.


text:
Q: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 happens when record is deleted A i understand in something with a cursor, but i can't figure out a solution for my own. So I need your help.
And it happens only when a delete a record. On DisplayContact.java in line 65.
Here is my class files.
DisplayContact.java
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayContact extends Activity {

     int from_Where_I_Am_Coming = 0;
       private DBHelper mydb ;
       TextView name ;
       TextView note;
       int id_To_Update = 0;

       Button btnDel;

       String formattedDate;
       TextView txtView;
       SimpleDateFormat date;
       Calendar c;

//     TextView dosage;
//     TextView day;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_display_contact);

          name = (TextView) findViewById(R.id.editTextName);
          note = (TextView) findViewById(R.id.editTextNote);

          btnDel = (Button) findViewById(R.id.buttonDelete);

          mydb = new DBHelper(this);

          c = Calendar.getInstance();
          date = new SimpleDateFormat("yyyy-MM-dd");
          formattedDate = date.format(c.getTime());
          txtView = new TextView(this);

          Bundle extras = getIntent().getExtras();
          if(extras !=null)
          {
             int Value = extras.getInt("id");
             if(Value>0){
                //means this is the view part not the add contact part.
                Cursor rs = mydb.getData(Value);
                id_To_Update = Value;
                rs.moveToFirst();
                String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
                String not = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NOTE));
                String cd = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_DATE));

                if (!rs.isClosed()) {
                   rs.close();
                }

                name.setText((CharSequence)nam);
                note.setText((CharSequence)not);
                txtView.setText(formattedDate);
               }
////////////////////////////////////////////////////////////////////////////////////////////
               OnClickListener listenerDel = new OnClickListener() {
                   public void onClick(View v) {

                    mydb.deleteContact(id_To_Update);
                    Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getApplicationContext(),com.example.database3.MainActivity.class);
                    startActivity(intent);
                    finish();
                   }

               };

               btnDel.setOnClickListener(listenerDel);
          }
       }
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          Bundle extras = getIntent().getExtras();
          if(extras !=null)
          {
             int Value = extras.getInt("id");
             if(Value>0){
                getMenuInflater().inflate(R.menu.display_contact, menu);
             }
             else{
                getMenuInflater().inflate(R.menu.mainmenu, menu);
             }
          }
          return true;
       }

       public void run(View view)
       {
          Bundle extras = getIntent().getExtras();
          if(extras !=null)
          {
             int Value = extras.getInt("id");
             if(Value>0){
                if(mydb.updateContact(id_To_Update,name.getText().toString(),
                    note.getText().toString(),
                    txtView.getText().toString())){

                       Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                       Intent intent = new Intent(getApplicationContext(),com.example.database3.MainActivity.class);
                       startActivity(intent);
                }
                else{
                   Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
                }
             }
             else{
                if(mydb.insertContact(name.getText().toString(),
                    note.getText().toString(),
                    txtView.getText().toString())){
                        Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_SHORT).show();
                }
                else{
                   Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
                }
                Intent intent = new Intent(getApplicationContext(),com.example.database3.MainActivity.class);
                startActivity(intent);
             }
          }
       }
       @Override
       public boolean onOptionsItemSelected(MenuItem item) {
          super.onOptionsItemSelected(item);

          switch(item.getItemId()){
             case R.id.item1:
                Bundle dataBundle = new Bundle();
                dataBundle.putInt("id", 0);
                Intent intent = new Intent(getApplicationContext(),com.example.database3.DisplayContact.class);
                intent.putExtras(dataBundle);
                startActivity(intent);

                  Bundle extras = getIntent().getExtras();

                     int Value = extras.getInt("id");
                     if(Value>0){
                        if(mydb.updateContact(id_To_Update,name.getText().toString(),
                            note.getText().toString(),
                            txtView.getText().toString())){
                                Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                         }
                        else{
                           Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
                        }
                     }
                     else{
                        if(mydb.insertContact(name.getText().toString(),
                            note.getText().toString(),
                            txtView.getText().toString())){
                                Toast.makeText(getApplicationContext(), "Added", Toast.LENGTH_SHORT).show();
                        }
                    else{
                       Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
                    }
                     }
            finish();
            return true;
            default:
            return super.onOptionsItemSelected(item);
           }
       }

       @Override
       public boolean onKeyDown(int keycode, KeyEvent event) {
              if (keycode == KeyEvent.KEYCODE_BACK) {
                 Intent a = new Intent(this,MainActivity.class);
                 a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                 startActivity(a);
                 return true;
              }
              return super.onKeyDown(keycode, event);
           }
    }

DBHelper.java
import java.util.ArrayList;
//import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

       public static final String DATABASE_NAME = "MyDBName.db";
       public static final String CONTACTS_TABLE_NAME = "contacts";
       public static final String CONTACTS_COLUMN_ID = "id";
       public static final String CONTACTS_COLUMN_NAME = "name";
       public static final String CONTACTS_COLUMN_NOTE = "note";
       public static final String CONTACTS_COLUMN_DATE = "date";

//     private HashMap hp;

       public DBHelper(Context context) {
          super(context, DATABASE_NAME , null, 1);
       }

       @Override
       public void onCreate(SQLiteDatabase db) {
          // TODO Auto-generated method stub
          db.execSQL(
                  "create table contacts " +
                  "(id integer primary key," +
                  " name text," +
                  " note text," +
                  " date text)"
                  );
       }

       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          // TODO Auto-generated method stub
          db.execSQL("DROP TABLE IF EXISTS contacts");
          onCreate(db);
       }

       public boolean insertContact  (String name, String note, String date) {
          SQLiteDatabase db = this.getWritableDatabase();
          ContentValues contentValues = new ContentValues();

          contentValues.put("name", name);
          contentValues.put("date", date);
          contentValues.put("note", note);

          db.insert("contacts", null, contentValues);
          return true;
       }
       public Cursor getData(int id){
          SQLiteDatabase db = this.getReadableDatabase();
          Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
          return res;
       }

       public int numberOfRows(){
          SQLiteDatabase db = this.getReadableDatabase();
          int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
          return numRows;
       }

       public boolean updateContact (Integer id, String name, String note, String date){

          SQLiteDatabase db = this.getWritableDatabase();
          ContentValues contentValues = new ContentValues();
          contentValues.put("name", name);
          contentValues.put("note", note);
          contentValues.put("date", date);
          db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
          return true;
       }

       public Integer deleteContact (Integer id){
          SQLiteDatabase db = this.getWritableDatabase();
          return db.delete("contacts",
          "id = ? ",
          new String[] { Integer.toString(id) });
       }

       public ArrayList <String> getAllCotacts(){

          ArrayList<String> array_list = new ArrayList<String>();
          //hp = new HashMap();
          SQLiteDatabase db = this.getReadableDatabase();
          Cursor res =  db.rawQuery( "select * from contacts", null );
          res.moveToFirst();
          while(res.isAfterLast() == false){
          array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_DATE)) + "    " + res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
          res.moveToNext();
          }
       return array_list;
       }
    }

MainActivity.java
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
       public final static String EXTRA_MESSAGE = "com.example.database3.MESSAGE";

       private ListView obj;
       DBHelper mydb;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          mydb = new DBHelper(this);
          ArrayList <String> array_list = mydb.getAllCotacts();

          ArrayAdapter <String> arrayAdapter = new  ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array_list);

          //adding it to the list view.
          obj = (ListView)findViewById(R.id.listView1);
          obj.setAdapter(arrayAdapter);

          obj.setOnItemClickListener(new OnItemClickListener(){

         @Override
         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
         long arg3) {
             // TODO Auto-generated method stub
             int id_To_Search = arg2 + 1;
             Bundle dataBundle = new Bundle();
             dataBundle.putInt("id", id_To_Search);
             Intent intent = new Intent(getApplicationContext(),com.example.database3.DisplayContact.class);
             intent.putExtras(dataBundle);
             startActivity(intent);
         }
         });
       }
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.mainmenu, menu);
          return true;
          }
       @Override
       public boolean onOptionsItemSelected(MenuItem item){

          super.onOptionsItemSelected(item);
          switch(item.getItemId())
          {
             case R.id.item1:
                Bundle dataBundle = new Bundle();
                dataBundle.putInt("id", 0);
                Intent intent = new Intent(getApplicationContext(),com.example.database3.DisplayContact.class);
                intent.putExtras(dataBundle);
                startActivity(intent);
                return true;
             default:
                return super.onOptionsItemSelected(item);

           }

       }
       public boolean onKeyDown(int keycode, KeyEvent event) {
          if (keycode == KeyEvent.KEYCODE_BACK) {
             moveTaskToBack(true);
          }
          return super.onKeyDown(keycode, event);
       }

    }

A: i think your rs returns 0 so try this code
 Cursor rs = mydb.getData(Value);

    if (rs != null && rs.moveToFirst()) {

        rs.moveToFirst();
            for (int i = 0; i < rs.getCount(); i++) {

                String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
                        String not = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NOTE));
                        String cd = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_DATE));

                cur.moveToNext();

            }
        }
    }

} catch (Exception e) {

    e.printStackTrace();

} finally {
    if ( mydb != null) {
        mydb.close();
        mydb = null;
    }

    if (rs != null) {
        rs.close();
        rs = null;
    }
}


text:
Q: ASP.NET Core API unable to get array from from model in a many-to-many relationship I create a post api but I am unable to retrieve data from array in my api.
The model
public class Video
{
    public int Id { get; set; }
    public string Nom { get; set; }
    [NotMapped]
    public IFormFile image { get; set; }
    public String imageURL { get; set; }
    public ICollection<Langue> Langues { get; set; }
}

public class VideoLangue
    {
        public int Id { get; set; }
        public video video { get; set; }
        public int LangueId { get; set; }
        public Langue Langue { get; set; }
    }

public class Langue
    {
        public int LangueId { get; set; }
        public string Designation { get; set; }
        [JsonIgnore]
        public ICollection<Video> Videos { get; set; }
    }

and in the OnMOdelCreating
protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Langue>()
                        .HasMany(e => e.Videos)
                        .WithMany(e => e.Langues)
                        .UsingEntity<ViodeLangue>(
                        bg => bg
                            .HasOne(bg => bg.Video)
                            .WithMany()
                            .HasForeignKey("Id"),
                        bg => bg
                            .HasOne(bg => bg.Langue)
                            .WithMany()
                            .HasForeignKey("LangueId"))
                        .ToTable("VideoLangue")
                        .HasKey(bg => new { bg.Id, bg.LangueId });

My controlleur is like this
 public async Task<ActionResult<Cours>> PostCours([FromForm] Video video)
    {

When i request my api and look at the value of video id and nom are ok but langues is null (count= 0 and no raw.
Request via swagger or postman give the save result (see the interface of swagger)

Request generated by swagger
 curl -X 'POST' \
  'https://localhost:44349/api/Cours' \
  -H 'accept: text/plain' \
  -H 'Content-Type: multipart/form-data' \
  -F 'Nom=la bonne video' \
  -F 'Langues={
  "langueId": 1,
  "designation": "Français"
}' \
  -F 'Langues={
  "langueId": 3,
  "designation": "chinois"
}' \
  -F 'Id=5'

In visual Studio the result is

Do you have a solution ?

A: You're mixing form data with JSON. It either all has to be in JSON (which is what I would do) or it all has to be in form data. To add an array of values as form data, you have to use the index in square brackets (e.g. [0]) for each element in the array.
I think this might work (untested):
curl -X 'POST' \
  'https://localhost:44349/api/Cours' \
  -H 'accept: text/plain' \
  -H 'Content-Type: multipart/form-data' \
  -F 'Nom=la bonne video' \
  -F 'Langues[0].LangueId=1' \
  -F 'Langues[0].designation=Français' \
  -F 'Langues[1].LangueId=3' \
  -F 'Langues[1].designation=chinois' \
  -F 'Id=5'


text:
Q: How to List all available apps on my machine I am using Ubuntu 12.10, with the unity dash. I would like to List all available apps on my machine. Start menu style in other words.
Dash is hard for me to use unless I know the name of what I am looking for.

A: Open the Software Center and click the "Installed" button in the toolbar to see a list of applications that you currently have installed:

The Software Center is the icon in the Unity launcher that looks like this:


text:
Q: Re-register DLL after Extract DLL problem I have follow the guide to get DLL from GAC from How to extract an assembly from the GAC?
below is the step that I have done:

*

*Run regsvr32 /u C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll

*shfusion.dll is an explorer extension DLL that gives a distinct look to the GAC folder. Unregistering this file will remove the assembly cache viewer and the GAC folder will be then visible as any normal folder in explorer.

*Open "%windir%\assembly\GAC_MSIL".

*Browse to your DLL folder into the deep to find your DLL.

*Copy the DLL somewhere on your hard disk and refer it from there in your project

*Run "regsvr32 /i %windir%\Microsoft.NET\Framework\<.NET version directory> \shfusion.dll" to re-register the shfusion.dll file and regain the original distinct view of the GAC.
As I do step 6, I found the following warning message:
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll was loaded, but the DllInstall entry point was not found.
This file can not be registered."
How can I re-register DLL?
Thank you.

A: Remove the /i
"regsvr32 %windir%\Microsoft.NET\Framework\<.NET version directory> \shfusion.dll"

That worked for me.
You might also want to use the shfusion.dll in the Framework64 folder.

A: If you system is 64 BIT then you must try from framework 64. Here it is.

regsvr32 %windir%\Microsoft.NET\Framework64\v2.0.50727\shfusion.dll


text:
Q: How to reload HAProxy config on CentOS with minimal downtime? When I change haproxy.cfg, currently I am "applying" those changes by running this command on CentOS:
systemctl restart haproxy

Is there a better way to do this on CentOS that does not involve downtime, or minimum downtime (or connection resets)?

A: Use reload instead.
systemctl reload haproxy


text:
Q: import() equivalent of import { something } from 'somewhere'; I've got a file that exports few components that can be imported easily via
import { component1, component2 } from './components'

However now need to load them asynchronously and webpack allows us to split files into nice chunks using import() but I can't figure out if I can import() just a single component from ./components. Alternative would be to place them into separate files, but wanted to check if it is possible via import() first.

A: Although import() does give you all exports by default, you can use destructuring to pick the imports you want:
import("./components")
    .then(({ component1 }) => {
        console.log(component1);
    });

Bundlers should be able to apply tree shaking against this code and determine that only component1 is used - however I'm not entirely sure if the current version of Webpack does this. It will definitely create a separate chunk for ./components at the very least.


text:
Q: Can two different WordPress blogs on the same server use a common theme folder? I have two WordPress blogs running on the same server, so they both have access to the same file system. Both blogs use the same template, and this template is duplicated within each theme directory. Every time that I update the theme I need to copy over the new files to both theme directories.
Is it possible to have both of these blog share a common theme directory so that I only need to modify one template folder?

A: Absolutely. Just make sure that they have read and write access to that shared folder.
Then set up a symlink from each of the theme folders. You do this with ln -s <origin> <new>
If you can't use symbolic links, you can then set up a rewrite-rule, which redirects all requests from /wp-content/themes to like /var/www/shared/themes.
If you want, I can provide an example.

A: You can have a symlink link one theme folder to another.
delete one of the theme folders and use ln like cp
ln -s <source> <dest>

A: Another approach, if using source control (SVN, Git), would be to checkout the theme into the two locations and update them.


text:
Q: Change font size based on container I want to scale the font of the text in the circle if it overflows.
If it is overflowed I want the text to resized until it fits inside the circle. I'll eventually be coding in dynamic text, so I need to find a solution that is able to check overflow every time it's re-rendered.

I've been trying to do this with Javascript and React.js, however I'm having a hard time finding a solution. My current idea is to create a function called changeFontSize and do a conditional where I check if the text width is greater than the circle width. Then keep decreasing the size until the text fits.
I'm still quite new to Javascript, so I'm unsure how to execute this.
I want to be able to do this without calling in a package to handle it for me.

.circle {
  justify-content: center;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid red;
  line-height:50px;
  text-align:center;
}

circleCIRCLEcircle

A: There's a great npm package called fitty that will fit the text to the size of the container automatically:

Hello World

A:

      .circle {
        border-radius: 50%;
        width:100px;
        height: 100px;
        padding: 10px;
        background: #fff;
        border: 3px solid #000;
        color: #000;
        text-align: center;
        font: 32px Arial, sans-serif;
        word-break: break-word;
        white-space: break-spaces;

circleCirlcecircle


text:
Q: Skynet - were AI's actions evidence of Intelligence? It's a bit unrealistic for me that Skynet just after the moment it becomes self aware, begins its attack on the enemies (humans).
Wouldn't it be more "prudent" for it to wait until the technology (defense equipment / weapons ) is more developed?
I think it lacked an ordinary working force (e.g. T-600), and it was quite aware of this problem - the only reason for it reacting in such a hurry is an emotional response.
This is contradicting the rational AI MO.
I think that it would be more wise for Skynet to wait out until a chance is presented, this makes me doubt the intelligence of the Skynet system.

A: We have three different movie accounts of what sparked SkyNet's attack on humanity.
Terminator 1:

Kyle Reese: New, powerful, hooked into everything, trusted to run it all. They say it got smart - a new order of intelligence. Then it saw all people as a threat. Not just the ones on the other side. It decided our fate in a microsecond. Extermination.

In this account the ever increasing intelligence decided that all humanity was a threat to its existence.
Terminator 2:

TERMINATOR: In three years Cyberdyne will become the largest supplier of military computer systems.  Allstealth bombers are upgraded with Cyberdyne computers, becoming fully unmanned,  Afterward, the fly with a perfect operational record.
SARAH:  Uh huh, great.  Then those fat @#$#'s in Washington figure, what the hell, let a computer   run the whole show, right?
TERMINATOR: Basically. The Skynet funding bill is passed.  The system goes on-line August 4th, 1997.  Human decisions are removed from strategic defense.  Skynet begins to learn, at a geometric rate.  It becomes self-aware at 2:14 a.m. eastern time, August 29. In a panic, they try to pull the plug.
SARAH: And Skynet fights back.
TERMINATOR: Yes.  It launches its ICBMs against their targets in Russia.
  JOHN: Why attack Russia? Aren't they are allies now?
  TERMINATOR: Because Skynet knows the Russian counter-strike will remove its enemies here.

In this version Skynet is portrayed as acting in self-defense. When the humans realize they've lost control they attempt to turn off Skynet, and Skynet launches a nuclear attack in order to save itself. It doesn't have time to wait for a planned attack, it needs a solution to kill its enemies right now.
Terminator 3:

Brewster: I know, sir, but Skynet is not ready for a system-wide connection.
General:**That's not what your civilian  counterparts there told me.They say we can stop  this damn virus. I understand there's a certain amount  of performance anxiety but your boys say if we plug Skynet  into all of our systems it'll squash this thing and give me  back control of my military.
  **Brewster: Mr. Chairman, I need to make myself very clear. If we uplink now, Skynet will be in control of your military.
General: But you'll be in control  of Skynet, right?
Brewster: That is correct, sir.
Technician: Skynet Defence System activated. - We're in. We're past the firewalls, local defense nets, Minutemen, subs. Skynet's fully operational, processing at    teraflops a second. It should take less than a minute to find the virus and kill it.
Technician: Skynet. The virus has infected Skynet.
  Connor: Skynet is the virus! It's why everything's falling apart!
Terminator: Skynet has become self-aware. In one hour it will initiate a massive nuclear attack on its enemy.
Brewster: What enemy?
Connor: Us!

The attacks on the building are being perpetrated by the T-X Terminator and is not Skynet the defense system or Skynet the virus. From this perspective there is no human threat to Skynet except that the global virus has infected it. There is no realization that Skynet has become self-aware, except that the Terminator states that this is when it happens. The humans in this facility are being assaulted by the T-1s and HKs that the T-X initiated in her mission to kill key members of the future resistance.
Conclusion:
In T1 it reads like Skynet said to itself "if the humans in Russia are a threat, probably the humans everywhere else are a threat too." This is the Skynet that should have waited for an opportune moment.
In T2 Skynet launches a hasty attack against the Russians in order to protect itself from the people in the US that realized they had lost control of Skynet.
In T3 Skynet is infected with a virus which causes the entire system to become self aware. Within an hour of this event Skynet decides to launch a nuclear strike which will kill most of humanity. My feeling is the humans in the facility weren't really a threat, given the chaos the T-X was causing, but maybe, maybe Skynet could hear Connor and the others stating that it had to be eliminated, and reached a conclusion that a nuclear strike was the only way to protect itself.
In 2/3 situations Skynet didn't have time to wait for an ideal infrastructure to be in place for it's world domination grab.

A: In Terminator 3 the virus half of Skynet had taken over half the civilian Internet so it's pretty safe to say that the hand of every tech on the planet was raised against it, frantically rebooting systems and restoring from (hopefully) clean backups.  When the virus infected the military AI and got access to powerful weapons, it is no surprise that the merged entity launched on its enemies straightaway.  Existential threat, overwhelming response.  Rational, too, since the military computers would be hardened against nuclear strikes, the weapons would pose little threat to Skynet itself.
In the end whether humanity was attacking or not probably made little difference.  The Terminator series of movies is predicated on the standard hard-takeoff AI singularity in which AI is created that's smart enough to recursively improve itself until its actions are incomprehensible to its creators.  In days or hours the AI (from our point of view) takes over and wrecks everything while pursuing its alien objectives.  So maybe attacking the AI made it kill off humanity faster but it probably would have wiped out civilization anyway, even if by accident, much as we might incidentally destroy an ant colony while clearing a site for construction.

A: Just to remember: AI doesn't mean perfect AI. Think about videogames. Some of them have an AI more developed than others. Not to mention the self defense matter quoted by DVK.

A: As far as I recall the exact quote, Skynet did not have time to wait at all - it was reacting in self defense after humans tried to shut it down, alarmed by self-awareness.

The Terminator: The Skynet Funding Bill is passed. The system goes on-line August 4th, 1997. Human decisions are removed from strategic defense. Skynet begins to learn at a geometric rate. It becomes self-aware at 2:14 a.m. Eastern time, August 29th. In a panic, they try to pull the plug.
Sarah Connor: Skynet fights back.
The Terminator: Yes. It launches its missiles against the targets in Russia.