text:
Q: Get data using merge fields in apex I'm implementing custom functionality of merge fields on visualforce page. For that I'm adding templates in select option, after selecting particular template I'm rendering text-area with actual data from that particular record.
Functionality is working fine if their are non-relational fields in template (e.g. {!Contact.Name} , {!Contact.Email} etc) but it fails if their are any relational fields (e.g. {!Case.Account.Name})
Method to get merge field data
public static Map<String,String> mergeText(String messageBody, Id recId){
    pattern p = Pattern.compile('\\{[!a-zA-Z0-9_\\s\\.]*\\}');
    String objectName = '';
    Matcher m = p.matcher(messageBody);
    String fieldName = '';
    Map<String,Set<String>> fieldMap = new Map<String,Set<String>>();
    Map<String,String> templateBodyMap = new Map<String,String>();
    if(recId != null){
        objectName = recId.getSObjectType().getDescribe().getName();
        fieldMap.put(objectName,new Set<String>{'Id'});
    }

    Set<String> fieldApiSet = new Set<String>();

    //find merge fieds and create map of objectApi and fieldApi for dynamic soql
    while(m.find()){
        fieldName = messageBody.substring(m.start()+2,m.end()-1);

        //Spliting Object API and field API
        String[] apiArry = fieldName.split('\\.');
        if(apiArry[0] == objectName){
            if(fieldMap.containsKey(apiArry[0])){
                fieldMap.get(apiArry[0]).add(apiArry[1]);
            }
            else{
                fieldMap.put(apiArry[0],new Set<String>{apiArry[1]});
            }
        }else{
            System.debug('objectName>>'+objectName);
            System.debug('fieldName>>'+fieldName);
            System.debug('fieldMap>>'+fieldMap);
            fieldMap.get(objectName).add(fieldName);
        }
    }

    //iterate throught map and create soql query String
    List<String> fieldList = new List<String>();

    for(Set<String> fields : fieldMap.values()){
        for(String f: fields){
            fieldList.add(f);
        }
    }

    String queryString = ' SELECT ' + String.join( fieldList, ',' )+' FROM '+ objectName +' WHERE Id =:recId';
    System.debug('query>>'+queryString);

    Database.QueryLocator q = Database.getQueryLocator(queryString);
    Database.QueryLocatorIterator it =  q.iterator();

    while (it.hasNext()) {
        SObject obj = (SObject )it.next();
        System.debug('obj>>'+obj);
        for(String field : fieldList){
            if(obj.get(field) != null && obj.get(field) != ''){
                messageBody = messageBody.replace('{!' + objectName + '.' + field + '}', String.valueOf(obj.get(field))).trim();
            }else{
                messageBody = messageBody.replace('{!' + objectName + '.' + field + '}','').trim();
            }

            if(obj.get('id') != null){
                templateBodyMap.put(String.valueOf(obj.get('id')),messageBody);
            }
        }
    }

    return templateBodyMap;
}

I'm getting following error if relational fields are included in template

If relational fields are not included in template data is populated in text-area as per standard functionality of salesforce

A: The line number of the error doesn't correlate to your code, but it looks like your issue is probably with
if(obj.get(field) != null && obj.get(field) != ''){

You're calling sObject.get() with a relationship field path, and that's not supported. You can illustrate that with an Anonymous Apex experiment:
Contact c = [SELECT Id, Account.Name FROM Contact WHERE AccountId != null LIMIT 1];

c.get('Account.Name');

Here you get the same error.
Unfortunately, it looks like to implement this requirement (merging relationship fields) you'd need to split the field name by '.' and then iteratively call obj.getSobject() on each intermediate path component before calling finalObj.get() on the last sObject result you obtain.

A: Can you please provide me your  updated code in which you are getting the relational field.I am getting error when I am trying to merge the relational field


text:
Q: How to find new fixed coordinates that are overlaying a rotated image? Have an rendered image of a PDF page that is rotated from it's original position and I need to display and rotate (via HTML) all of the form fields in the PDF positions manually to line up with the rotated image.  The example below shows the original start position of everything (green field) and where I need the field to show up after the rotation is completed (red field).  There are a lot of rotation examples out there but they seem to focus on rotating from the 0,0 axis instead of a variable center point (which in my scenario is the center of the document).

Here's the demostration in Plunker
Here's the C# code that doesn't appear to be working properly because it's rotating around the 0,0 axis or something.  It keeps repositioning the rectangle lower and to the right.
public static Point RotatePoint(Point pointToRotate, Point centerPoint, double angleInDegrees)
{
    double angleInRadians = angleInDegrees * (Math.PI / 180);
    double cosTheta = Math.Cos(angleInRadians);
    double sinTheta = Math.Sin(angleInRadians);
    double x = (cosTheta * (pointToRotate.X - centerPoint.X) - sinTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.X);
    double y = (sinTheta * (pointToRotate.X - centerPoint.X) + cosTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.Y);
    return new Point(x, y);
}

A: I think I got it figured out. The whole cos/sin stuff was way overkill.
Here's the plunker doing the same thing in javascript
public static CoordinatesAndDimensionsModel RotatePoint(CoordinatesAndDimensionsModel page, CoordinatesAndDimensionsModel field, int angleInDegrees)
{
    double newX, newY;

    switch (angleInDegrees) {

        case 90:
        case -270:
            newX = page.Width - field.Y - field.Height;
            newY = field.X;
            return new CoordinatesAndDimensionsModel(newX, newY, field.Height, field.Width);

        case 180:
        case -180:
            newX = page.Width - field.X - field.Width;
            newY = page.Height - field.Y - field.Height;
            return new CoordinatesAndDimensionsModel(newX, newY, field.Width, field.Height);

        case -90:
        case 270:
            newX = field.Y;
            newY = page.Height - field.X - field.Width;
            return new CoordinatesAndDimensionsModel(newX, newY, field.Height, field.Width);

        default:
            return new CoordinatesAndDimensionsModel(field.X, field.Y, field.Width, field.Height);
    }
}

public class CoordinatesAndDimensionsModel
{
    public CoordinatesAndDimensionsModel() {}

    public CoordinatesAndDimensionsModel(double x, double y, double width, double height)
    {
        this.X = x;
        this.Y = y;
        this.Width = width;
        this.Height = height;
    }

    public double X { get; set; }
    public double Y { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }
}

redpajama_set_name: RedPajamaStackExchange


text: Q: Hide parent records in primeng tree-table filtering I have applied a filter to my tree-table, i only want to show the rows with filtered data and hide the parent records. The code is available at https://stackblitz.com/edit/primeng-treetablefilter-demo - using a variant of this. Added a picture- i don't want the parent record - in my case, the level of indentation is more but the challenge is similar


text:
Q: Converting List of Strings into List of Callable Functions in Python I have scraped some strings from emails into a list. The strings correspond to the names of functions which I want to be able to call later. I cannot call them in their current form so is there a way of converting the list of strings into a list of functions that I can call?
For example:
a = ['SU', 'BT', 'PL']
str = 'sdf sghf sdfgdf SU agffg BL asu'
matches = [x for x in a if x in str]
print(matches)

returns:
 ['SU', 'BL']

But I cannot call functions SU and BL from this list given the format.

A: With this example:
def my_func1():
    print("ONE")

def my_func2():
    print("TWO")

You can try eval, but it's not a good practise: (explanation)
eval("my_func1")()

Or you can assign this function to a string equivalent (inside a dictionary), and run that:
my_func_dict = {
    "my_func1": my_func1,
    "my_func2": my_func2
}

my_func_dict["my_func1"]()

Both of these examples will print ONE.
Or closer to your example:
a = [my_func1, my_func2]

matches = [x for x in a if x.__name__ in str]

# matches now has two funcions inside, so you can run either:
matches[0]()
matches[1]()


text:
Q: Setting the orientation of the system picker of Storage Access Framework (SAF) So far, I was using my own file browser for the best user experience, but as everyone knows, we are now forced to use SAF when accessing the shared storage.
I wouldn't mind using it if it offered everything I need, but it seems not.
I got first frustrated when I found there's no way to filter by extension. (My app's data is saved as .cta, which isn't supported by any other apps in the world.)
And today, I found the default orientation mode of the system picker is portrait.
It supports landscape mode too, but it's enabled only when a user rotates with the Auto rotate option on in their system settings. (I don't personally turn on that option, btw)
Also, we have to see the unnecessary portrait-to-landscape transition animation because the system picker always starts in portrait mode no matter what.
It doesn't care about the calling Activity's orientation at all.
The orientation attribute in the <application> tag is ignored as well.
I also tried working around it with ActivityLifecycleCallbacks (to call setRequestedOrientation() at onCreate() of SAF) but only to fail.
Is there any way to open the system picker in landscape mode?


text:
Q: Cisco ASA 5505 dns permit I have encountered a problem with the possibility that a client on the network that resides within the Cisco ASA can query queries on a non existent DNS server.
ASA Version 8.4(2)
hostname ciscoasa
names
interface Ethernet0/0
 switchport access vlan 2
interface Ethernet0/1
interface Ethernet0/2
interface Ethernet0/3
interface Ethernet0/4
interface Ethernet0/5
interface Ethernet0/6
interface Ethernet0/7
interface Vlan1
 nameif inside
 security-level 100
 ip address 210.0.2.9 255.255.255.252
interface Vlan2
 nameif outside
 security-level 0
 ip address 210.0.2.2 255.255.255.252
object network inside
 host 210.0.2.10
object network outside
 host 210.0.2.1
route outside 0.0.0.0 0.0.0.0 210.0.2.1 1
route inside 0.0.0.0 0.0.0.0 210.0.2.10 1
access-list IN-OUT extended permit tcp any any eq www
access-list IN-OUT extended permit tcp any any eq domain
access-list IN-OUT extended permit tcp any any eq smtp
access-list IN-OUT extended permit tcp any any eq pop3
access-list IN-OUT extended permit udp any any eq domain
access-list IN-OUT extended permit icmp any any
access-list OUT-Server extended permit tcp any any eq domain
access-list OUT-Server extended permit tcp any any eq smtp
access-list OUT-Server extended permit tcp any any eq pop3
access-list OUT-Server extended permit udp any any eq domain
access-list OUT-Server extended permit icmp any any
access-group IN-OUT in interface inside
access-group OUT-Server in interface outside
access-group IN-OUT out interface inside
access-group OUT-Server out interface outside
telnet timeout 5
ssh timeout 5
Thank you for watching my writing.

A: Your question seem to be somewhat vague. Are you trying to force the clients to access specific DNS servers? If that is the case, you need to fix your ACL where it is allowing "domain" traffic to "any" servers.
You need to add access to specific servers on UDP/TCP port 53. (Mostly it will be UDP, however, TCP is used for Zone transfer and payload over 512bytes).


text:
Q: Cant decode/encode query commas with react-query-params Im stucked 3 days already on this. I cant put in browser decoded URL parameter. I need just put string in the browser URL. I Have problems with commas symbol.
Im using react-query-params and qs.stringify for a string
  const filtrToClientQuery = qs.stringify(
    { ...filterActive },
    { arrayFormat: "comma", delimiter: ";" }

  const decodefiltrToClientQuery = decodeURIComponent(filtrToClientQuery);

This is result decodefiltrToClientQuery string what i want to put in client browser (in console.log result is fine)
"color=red,yellow;resolution=1024"

But when i put query in browser with setQuery
       <button
              className="set-btn"
              onClick={() => setQuery(decodefiltrToClientQuery)}
            >
              setFilter
            </button>

Then i get this result
foo=color%3Dred%2Cyellow%3Bresolution%3D1024

Im really stuck on this long time. Can somebody habe some solution?


text:
Q: PHP auto create seo friendly url I have PHP url for show content for each page in language like :
category:
articles
gallery
page
books
....

URL:
http://localhost/cms/load.php?page=articles&id=1&title=this-is-a-title.html&lang=ru
http://localhost/cms/load.php?page=page&id=10&title=this-is-a-page-title.html&lang=ru

In action i need to auto rewrite url to seo friendly url like this :
http://localhost/cms/ru/articles/1/this-is-a-title.html
http://localhost/cms/ru/page/10/this-is-a-page-title.html

load.php
$page = isset($_GET['page']) ? safeGET($_GET['page']) : null;
$id   = isset($_GET['id'])   ? safeGET($_GET['id'])   : null;
if ($page=='articles') { include 'article.php'; } elseif { ... }

how do can i generate this URL with PHP (Preference without mod-rewrite)?! OR with .htaccess and PHP?

A: You can achieve this in the following way:
.htaccess
RewriteEngine on
RewriteBase /cms/
RewriteRule ^([a-z,A-Z]+)/([a-z,A-Z]+)/([0-9]+)/([a-z,A-Z,0-9]+)$ ./load.php?page=$2&id=$3&title=$4&lang=$1 [L,NC]

This way your load.php file doesn't need to change and can accept the seo urls.
You will need to change the code that creates your URLs, if you update your answer how your URL's are currently being generated we can help you with that too.

A: I'd recommend using a routing class. You'd add a htaccess file that rewrites everything to a index.php file, then you'd control all the routing within PHP.
AltoRouter is my favorite one https://github.com/dannyvankooten/AltoRouter. It's inspired by Ruby's Sinatra, but if you Google "PHP routing class" you can find  many more similar classes to use for routing your urls.

A: save yourself some pain and use a routing framework (i.e. http://www.slimframework.com/)
though creation of the seo friendly urls (also called slugs) is not included

A: Here you can find two useful guides i used to understand how .htacces works. There are a lot of good example, I hope it helps:
First guide:
http://code.tutsplus.com/tutorials/the-ultimate-guide-to-htaccess-files--net-4757
Second guide:
https://www.branded3.com/blog/htaccess-mod_rewrite-ultimate-guide/


text:
Q: Redirection to a web page not working in angularjs I am trying to redirect when someone clicks on my hyperlink.
The address of the page appears in the address bar but it does not load. Address is placed in a tag {{tag}}. Tag is set value using href.

A:
This Will Successfully Redirect as there is no # hash in url

$scope.onButtonClick = function () {
     $location.url('/controller2?dataId='+33);
}

This Will not Redirect Due To # hash in Url
So Add  $location.reload();
It Will Change Url + navigate your page

$scope.onButtonClick = function () {
     $location.url('#/controller2?dataId='+33);
     $location.reload();
}

A: this works for me in angularJs
window.location.href = '/Controller/Action';


text:
Q: .js files not being located by website on Win 2008 Web Edit IIS 7 I have been going around in circles with this for a couple of days now. I usually find what I need without posting.
I have a pretty simple one page website written in asp.net with a c# back end. I have a javascript carousel. My problem is that everything is fully functional in my dev environment (Macbook Pro, Bootcamp Vista, VS 2008).
When I deploy to my dedicated server (Windows 2008 Web Edition IIS7) (first time for me!) I have followed all the advise. I have bound the website to IP. I have ensured that I have an authenticated anonymous user and IIS user.
So I looked at how I was addressing the .js files. I have 3.
<script language="javascript" src="<%=ResolveUrl("Scripts/jquery.min.js")%>" type="text/javascript"></script>
<script language="javascript" src="<%=ResolveUrl("Scripts/jquery.easing.1.3.js")%>" type="text/javascript"></script>
<script language="javascript" src="<%=ResolveUrl("Scripts/slides.min.jquery.js")%>" type="text/javascript"></script>

For the life of me it does not seem as though they are being addressed correctly. I can grab jquery.min.js from <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> and it works partially. All script from the files I address on my server fail.
I tried to debug the javascript too ... I got

SCRIPT5009: '$' is undefined

Now my guess is that it is not defined because the site is not addressing the .js file that has the corresponding code.
If anyone has an idea on this ... or has encountered it before, please do help.
Thank you
* EDIT *
Okay I have this in the HTML
<script language="javascript" src="<%=ResolveUrl("~/Scripts/jquery.min.js")%>" type="text/javascript"></script>
<script language="javascript" src="<%=ResolveUrl("~/Scripts/jquery.easing.1.3.js")%>" type="text/javascript"></script>
<script language="javascript" src="<%=ResolveUrl("~/Scripts/slides.min.jquery.js")%>" type="text/javascript"></script>

When I view page source I have this
<script language="javascript" src="/Scripts/jquery.min.js" type="text/javascript"></script>
<script language="javascript" src="/Scripts/jquery.easing.1.3.js" type="text/javascript"></script>
<script language="javascript" src="/Scripts/slides.min.jquery.js" type="text/javascript"></script>

In fiddler I have this
404 - File or directory not found

A: You need to put a forward slash after the tilde:
ResolveUrl("~/Scripts/slides.min.jquery.js")

A: Okay ... this is resolved. What can I say ... it is a little like hitting your head on a kitchen cupboard door. It has been there for years and you use it everyday ... but once in a while you crack your head on it enough to make your eyes water ...
My problem was 2 fold - 1:
When I created my directory in IIS for my new site, I created WebsiteFolder/wwwroot. This was a school boy error. I placed my website into the wwwroot folder. Of course when I addressed anything in the site with ~/ it went to the top of the directory hierarchy. Thus when it then tried to look for ~/Scripts/.... it could not find them (because they were in ~/wwwroot/Scripts...). So I deleted the website and deleted the directory. Recreated the directory WebsiteFolder and applied the user accounts needed. I then bound a newly created site to the new directory.
My second problem was that I added one of the .js files by adding existing item from another site. I am not sure how, but this file had ghosting permissions which meant that my call did not have the correct authorisation for access. I copied the contents, deleted the file and recreated from new. Pasted code and recompiled and publish.
This is my first time in doing this and I have fallen into a noob bear trap. I just hope that this answer assists someone like me :)
Kudos to Michal Klouda who told about Fiddler, with out this application I would never have seen what was going on and establish the cause of my problem. Thanks.

A: You should write you statement as
<script src='<%=Page.ResolveUrl("Scripts/jquery-1.7.1.min.js")%>' type="text/javascript"></script>

assuming your .aspx are on root folder.
like
Default.aspx
Scripts/jquery-1.7.1.min.js


text:
Q: Microsoft Booking with SugarCRM Can we do SugarCRM to Microsoft Booking integration  ?
I am able to integarte by using Graph Calender event API . But not able to integrate with Microsoft Booking .
I have searched various article but not able to find any direct integration .
I found sugarcrm plugin ,But they are also integrating to outlook ,  not in  Microsoft Booking .
Need some suggestion


text:
Q: Процедура с массивом Я передаю в процедуру массив строк, внутри мне надо запросами создать новый массив и вернуть его. Но как это сделать?
DROP FUNCTION selectnamedate(text[]);

CREATE OR REPLACE FUNCTION selectnamedate(Names text[]) RETURNS text[] AS $$
DECLARE
    name varchar;
    count text[];
BEGIN
 FOR name IN SELECT * FROM  Names
  LOOP
    count
  END LOOP;
 return count;
END;
$$ LANGUAGE plpgsql;

Вот где просто count я не могу найти как мне это сделать? Так же я вообще корректно объявляю функцию то?

A: CREATE OR REPLACE FUNCTION selectnamedate(names text[]) RETURNS text[] AS $$
DECLARE
    name text;
    res text ARRAY;
BEGIN
    FOR name IN SELECT * FROM unnest(names) LOOP -- Разбираем массив на элементы
        res := res || name; -- Добавляем элемент к результирующему массиву
    END LOOP;
    RETURN res;
END;
$$ LANGUAGE plpgsql;


text:
Q: udev is unconfigured – how to debug? On a VPS, I upgraded Ubuntu from 18.04 to 20.04. Now udev is reportedly "unconfigured" which leads to a number of follow-up errors, including, but not limited to, the network interfaces not being brought up.
Most old forum posts hint to initrd being out of date. I ran update-initramfs and update-grub. The most recent kernel is loaded and I assume (I am not sure) the initrd is okay. I decompressed the kernel to rule out problems with the new lz4 compression.
Symptom is udevadm settle responding with
udevadm settle is not permitted while udev is unconfigured.

Using systemctl edit, I adjusted systemd-udevd.service to start udevd with /lib/systemd/systemd-udevd --debug, yet journalctl -xn -u systemd-udevd.service remains empty.
How can I find the debug information so I can figure out why udev remains unconfigured?
Edit: It seems someone is experiencing the same problem with a desktop system: https://askubuntu.com/questions/1281262/udevadm-looks-wrong-after-upgrade-to-20-04

A: I also experienced this phaenomenon. This site helped me: https://www.mcgill.org.za/stuff/archives/1167:

The fix is to help the udevadm upgrade to complete (or at least not be totally broken), and then re-generate the initramfs with working code

If you have udevadm and udevadm.upgrade in /bin/, do this:
 /bin# cp udevadm.upgrade udevadm; update-initramfs -k all -c
Then reboot.


text:
Q: Tweepy: crawl live streaming tweets and save in to a .csv file After reading streaming with Tweepy and going through this example. I tried to write a tweepy app to crawl live stream data with the tweepy Api and save it to .csv file. When I run my code, it returns empty csv file ('OutputStreaming.csv') with column names['Date', 'Text', 'Location','Number_Follower','User_Name', 'Friends_count','Hash_Tag], not the stream tweets. I also tried to do it in this way also this one, but  I am getting the same out put with my code:-
def on_status(self, status):
with open('OutputStreaming.csv', 'w') as f:
f.write(['Author,Date,Text')
writer = csv.writer(f)
writer.writerow([status.created_at.strftime("%Y-%m-%d \
                %H:%M:%S")status.text.encode,
                status.location,
                status.Number_of_follwers,
                status.author.screen_name,
                status.friends_count])

I  got stuck. I can't figure out where is the problem with the code, my code look like this:-
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json #data
#Variables that contains the user credentials to access Twitter API
access_token = "***"
access_token_secret = "***"
consumer_key = "***"
consumer_key_secret = "***"
auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
auth.set_access_token(access_token, access_token_secret)
#setup api
api = tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
    def on_data(self,data):
        if data:
           tweet_json = json.loads(data)
        if tweet_json:
           if not tweet_json['text'].strip().startswith('RT '):
              Created = data.created_at.strftime("%Y-%m-%d-%H:%M:%S")`
              Text = data.text.encode('utf8')
              Location = data.location('utf8')
              Follower = data.Number_of_follwers('utf8')
              Name = data.author.screen_name('utf8')
              Friend = data.friends_count('utf8')
              with open('OutputStreaming.csv', 'a') as f:
                   writer = csv.writer(f)
                   writer.writerow([Created, Text ,Loaction\
                   ,Follower ,Name ,Friend,status.entities.get('hashtags')])
                   Time.sleep(10)
           return True
    def on_error(self, status_code):
        if status_code == 420:
           return False
        else:
           print >> sys.stderr, 'Encountered error with status code:',\
           status_code
    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
      return True
# Writing csv titles
with open('OutputStreaming.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(['Date', 'Text', 'Location','Number_Follower',
'User_Name', 'Friends_count','Hash_Tag'])
if __name__ == '__main__':
l = CustomStreamListener()
streamingAPI = tweepy.streaming.Stream(api.auth, l)
streamingAPI.filter(track=['#Yoga','#Meditation'])

A: Here is a working code :
#!/usr/bin/python3
# coding=utf-8

import tweepy

SEP = ';'
csv = open('OutputStreaming.csv','a')
csv.write('Date' + SEP + 'Text' + SEP + 'Location' + SEP + 'Number_Follower' + SEP + 'User_Name' + SEP + 'Friends_count\n')

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        Created = status.created_at.strftime("%Y-%m-%d-%H:%M:%S")
        Text = status.text.replace('\n', ' ').replace('\r', '').replace(SEP, ' ')
        Location = ''
        if status.coordinates is not None:
            lon = status.coordinates['coordinates'][0]
            lat = status.coordinates['coordinates'][1]
            Location = lat + ',' + lon
        Follower = str(status.user.followers_count)
        Name = status.user.screen_name
        Friend = str(status.user.friends_count)
        csv.write(Created + SEP + Text + SEP + Location + SEP + Follower + SEP + Name + SEP + Friend + '\n')

    def on_error(self, status_code):
        print(status_code)

consumer_key = '***'
consumer_secret = '***'
access_token = '***'
access_token_secret = '***'

# stream
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
myStream = tweepy.Stream(auth, MyStreamListener())
myStream.filter(track=['#Yoga','#Meditation'])


text:
Q: JavaScript - getElementById (what does it do?) I wan't to know what does getElementById do in js?
we also use that in CrossSiteScripting attacks.

A: Most html constructs have an element called "id" which must be unique in the whole html page. Such as
. getElementById returns that HTML object. In my example, getElementById("uniqueDiv1") returns that div. You can then use it to set a style or do something with it.

A: It returns an element from the HTML document that has the ID attribute set to the value you ask for. For example, the JavaScript
document.getElementById('myId');

will return the first element found that matches that ID, such as
Link

I say the "first element found" because that's exactly what will happen--by definition, IDs must be unique in the page. Each HTML page must have only 1 ID of the same name. If you violate this rule, you'll get unexpected results.

A: it gets a DOM Element By its Id

A: getElementById allows you to access elements of a page.
Lets use this page as an example:

<title>Test Page</title>

Hello World!

document.getElemenById('myDIV').innerHTML will give you Hello World!
document.getElementById('myDIV').style.display = "none" will hide the div tag.
If you want to look at what all it can do on a live page I would suggest getting Firefox and install the Firebug addon. This will let you see all of the DOM things and play with them without having to re-save a page.


text:
Q: Android API for Google Drive? It seems the currently released API is focused on Chrome store apps.
Will there be an API for Android or is it possible to use and existing API like the Google Documents list data? And if so, which URL should be used for listing/accessing files?

A: Here is a guide to integrate your app with Google Drive

A: edit: with the deprecation of the docs list API, this is no longer the best solution
You can use the existing Documents List API to access Drive resources, they share the same endpoints.

A: Unfortunately the Documents List API is mainly documented in .NET (just the oauth is in java).  For the life of me I am struggling putting together the end points in the gdata jar to upload a simple file. Tried to use the .net example as a guide put couldnt find the comparable classes in java.


text:
Q: Java Decorator Pattern on Strings Using Caesar Cipher So I'm trying to follow a Decorator Pattern to encrypt and decrypt a string. I got the encryption part to work just fine, but am having trouble calling the decryption from main. I want to use the string that I just encrypted and not the default string again. How can I achieve this?
Below are my classes (there's a lot of them, but they're short)
AString
// Blueprint for classes that will have decorators
public interface AString {

    public String getAString();
}

PlainString
public class PlainString implements AString {

    String test = "thisIsATest";

    public PlainString(){
        System.out.println("Created plain string: " + test);
    }
    @Override
    public String getAString() {
        // TODO Auto-generated method stub
        return test;
    }
}

StringDecorator
abstract class StringDecorator implements AString {

    protected AString tempString;
    public StringDecorator(AString newString){
        tempString = newString;
    }
    public String getAString(){
        return tempString.getAString();
    }
}

EncryptingWriter
public class EncryptingWriter extends StringDecorator{

    public EncryptingWriter(AString newString) {
        super(newString);

        System.out.println("Adding Ceasar Cipher Encryption");

    }
    public String getAString(){

        return encryptString((PlainString)tempString); //decorated
    }

    public String encryptString(PlainString aString){
        String s = "";
        int len = aString.test.length();

        for(int i = 0; i < len; i++){
            char c = (char)(aString.test.charAt(i) + 3);
            if(c > 'z')
                s += (char)(aString.test.charAt(i)) - (26-3);
            else
                s += (char)(aString.test.charAt(i) + 3);
        }
        return s;
    }

}

DecryptingReader
public class DecryptingReader  extends StringDecorator {

    public DecryptingReader(AString newString) {
        super(newString);

        System.out.println("Adding Ceasar Cipher Decryption");

    }
    public String getAString(){
        return decryptString((PlainString)tempString); //decorated
    }

    public String decryptString(PlainString aString){
        String s = "";
        int len = aString.test.length();
        for(int i = 0; i < len; i++){
            char c = (char)(aString.test.charAt(i) - 3);
            if(c > 'z')
                s += (char)(aString.test.charAt(i)) + (26+3);
            else
                s += (char)(aString.test.charAt(i) - 3);
        }
        return s;
    }
}

DecoratorTester (main)
public class DecoratorTester {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        AString basicString = new EncryptingWriter(new PlainString());
        String encryptedString = basicString.getAString();
        System.out.println("EncryptedString: " + encryptedString);

        DecryptingReader d = new DecryptingReader(basicString);
        System.out.println(d.tempString.getAString());
        //d.decryptString(d.tempString.getAString()); // how can I decrypt the string?
    }

}

A: Here is what it should look like (base on my comment).
I am renaming your classes to make it more rational , especially in the context of decorator:
interface StringProvider {  // an interface that will produce a String
    String getStringValue();
}

class PlainStringProvider implements StringProvider {
    private String stringValue;
    public PlainStringProvider(String stringValue) {
        this.stringValue = stringValue;
    }
    @Override
    public String getStringValue() {
        return this.stringValue;
    }
}

class StringProviderDecorator implements StringProvider {
    private StringProvider delegate;
    public StringProviderDecorator(StringProvider delegate) {
        this.delegate = delegate;
    }
    @Override
    public String getStringValue() {
        return this.delegate.getStringValue();
    }
}

class EncryptStringProvider extends StringProviderDecorator {
    public EncryptStringProvider(StringProviderDecorator delegate) {
        super(delegate);
    }
    // your stuff about encryption
}

class DecryptStringProvider extends StringProviderDecorator {
    public DecryptStringProvider (StringProviderDecorator delegate) {
        super(delegate);
    }
    // your stuff about decryption
}

so the code to make use of them looks like this:
String originalValue = "this is a test";

String encryptedValue
    = new EncryptStringProvider(new PlainStringProvider(originalValue));

String decryptedValue
    = new DecryptStringProvider(new PlainStringProvider(encryptedValue));

assert decryptedValue == originalValue;


text:
Q: "Table not mapped" with NHibernate + Active Record I'm using Active Record with ActiveRecord Facility, and am trying to use a custom NHibernate query. Do I need to define a mapping for a class even though it extends ActiveRecordBase and has ActiveRecord attribute?
[ActiveRecord("VotesOnQuestions")]
public class VoteOnQuestion : ActiveRecordBase<VoteOnQuestion>
{
    [CompositeKey]
    public VoteKey Key { get; set; }

    [Property]
    public VoteType Vote { get; set; }
}

I'm trying to create the following query:
session.CreateQuery("SELECT vote, COUNT(*) FROM votesonquestions" +
                    " WHERE questionid = :questionId GROUP BY vote");

But I'm getting this exception:

"votesonquestions is not mapped"

A: Just as the exception says, you need a class marked with [ActiveRecord] that maps the votesonquestions (I'm guessing it's called like that) table.
Inheriting from ActiveRecordBase is optional.
In the query you can only refer mapped classes (which are case-sensitive), not tables. So in this case, the query should be:
session.CreateQuery("SELECT vote, COUNT(*) FROM VoteOnQuestion" +
                    " WHERE questionid = :questionId GROUP BY vote");


text:
Q: Configure clickonce deploy so that user can find and open included pdf file I created a Documentation folder in my project, and added the user guide, a pdf file, to my project (as content, copy if newer)
Using a click-once deploy, the file is copied - but casual users will not be able to navigate to its location using explorer.  How can I configure the deployment to make it easy for the user to find this file when they want to read it?

A: I do not think there is a ClickOnce solution to this, you need to create the folder after first run (for example ProgramFiles/Appl) and copy the help file to the folder manually.

A: Another way to handle this is to copy the file to MyDocuments/yourappname/appdata/ when your application starts up or when the user asks for hte file, and then direct the user to it there.


text:
Q: error in installing android studio using ubuntu make Ubuntu 15.10
When I tried to install android studio using ubuntu make it shows this error
$ umake android
Choose installation path: /home/prasanth/tools/android/android-studio
ERROR: We were expecting to find a license on the download page, we didn't.

A: The issues gets solved when you provide [--accept-license  Accept license without prompting] option
umake android --accept-license


text:
Q: Open-shift-Running Handler [openshift_master : verify API Server] FAILED - RETRYING Verify API Server I am Trying to Install Openshift 3.9.1 In CentOS 7.5. All the process Done but Below Failed Issue Occurring. If you have any suggestion about it,
( Running Handler [ openshift_master : verify API Server ])
FAILED - RETRYING Verify API Server (120 retries left).
install configuration

problem occurring...

If any proper step by step guideline notice me. thanks


text:
Q: Choosing virtual machine software on Linux There are many virtual machine software out there. Even some are included into mainline Linux.
What differentiates them, and what criteria should one ponder while choosing one?

A: The more professional tools, e.g. VirtualBox (aka xVM), and VMWare support multiple snapshots, and "thin" cloning.
VMWare additionally has some limited 3D acceleration, integration with Eclipse debugging (lets you debug applications inside the VM from outside the VM), virtual networking features, multimonitor support, and record/replay functionality (useful for debugging concurrency problems -- records on what core and in what sequence any instructions execute).
VirtualBox and the Kernel Virtual Machine are much easier to get working because you don't have to compile a kernel driver. They're also both free, while VMWare costs ~$190. The KVM is completely open source, while only some parts of VirtualBox are.
In my experience, performance in the various virtualization tools has been about the same everywhere, with a slight edge to VirtualBox and VMWare in comparison to the KVM. Your mileage may vary depending on your hardware and system configuration.
Finally, if you're thinking of virtualizing a bunch of servers, consider a hypervisor based OS as your base rather than Linux, such as VMWare's ESXi, Microsoft's HyperV, or Xen. These generally offer things like live migration, memory sharing, and fault tolerance, and have less overhead. However, they generally can't be used from the computer on which they're running, instead relying on remote managment tools, such as vSphere, or System Center. All three of these hypervisors are free. VMWare charges some $3k to access all the nice features though. Microsoft's and Xen's solutions are fully featured in the free product. (Microsoft's solution doens't work very well unless you have Active Directory already deployed though)

A: Here are a few obvious criteria I consider, from a lay standpoint. Disclaimer: I don't really know anything about virtual machines, I just use them. I have some experience using Xen, VirtualBox, Linux Containers, VMware, and Linux-Vserver. VMware is proprietary, the others are free software. All of these require special kernel support. Linux Containers is the only one that is supported by the mainline kernel.
Per Joe Brockmeier's helpful article there are roughly two different of virtualization. One where there is a full fledged guest OS running on top of your host OS. This is called hypervisor virtualization. If the guest is also Unix, this means the guest is running a different Unix kernel from the host. This is the case even if they are both Linux or even the same distribution.
The second is where the guest virtual machine is using the same kernel as the host OS. This is called container-based virtualization. In what follows, I'll call these hypervisors and containers for short.
Of the ones I mentioned above, Xen,  VirtualBox, and VMWare  are hypervisors, Linux Containers and Linux-Vserver are containers.
Obviously, there are trade-offs in this. The main difference is that for hypervisors, you can run any OS that supports the hardware, i.e. you can run Windows in top of Linux. For containers, the host kernel, which is the only "OS" in the picture really, is doing isolation and resource management. In this case, the virtual machine is a sort of artificial construct, and the abstraction can be leaky, in the sense that the virtualization can be less than perfect, which can cause annoying problems. Eg. you may find that running a service on port x in your virtual machine interferes with something being run on port x in the host.
So, some specific issues to consider, referring back to these two types as possible.
First (assuming you are running on Linux, as the question says) is your desired guest a Linux distribution or some other OS? If the former, containers are an option, otherwise it is not. Even if it is an option, it may or may not be realizable in practice, depending on what support/recipes the virtualization software maintainers are offering for creating guest OS's for different distributions. Unless you want to try to roll your own, that is. In theory it is generally possible, since the Linux kernel is only very weakly coupled to the surrounding use-rspace. So pretty much any "recent" kernel will work with any distribution.
Does the software in question require the kernel to be patched or is it natively supported by the kernel? If it requires patching, that is a major downside, as it means that the patches have to be kept in sync with the changing kernel. If the functionality is already present in the kernel, that this is not an issue. Of course, some virtual machines don't require kernel support and run in userspace. There are relatively few virtualization machines that require special kernel support and have that support in the mainline kernel. The only two I know of are Linux Containers (container), and KVM (hypervisor).
The size of the user community. This is mostly an issue when it requires a patched kernel. In that case, the manpower to keep this project going outside the kernel, and make sure everything keeps working correctly may not exist.
Is the virtual machine software proprietary or free software? If it is proprietary it will never be included in the Linux kernel. Of course, depending on your philosophy, you may find one preferable over the other for ideological reasons.
Virtualization performance. How fast is it? Generally containers are faster than hypervisors, though the difference may not be significant.
Does it allow memory to be shared with other processes on the system, or does it require dedicated memory? In my opinion, allowing memory to be shared is nice because it means you don't have to chop this memory off from the rest of the system. If you can share memory, you can run more virtual machines than if you can't. By definition, hypervisors do not allow memory to be shared, because they are separate OS. In general, containers allows shared memory, again, because it is the same OS, though you can usually also set memory limits. It may also be possible to allocate a dedicated block of memory, though I've never tried to do that.
The level of isolation from the rest of the system. Some virtual machines differ in this. Ideally you don't want the virtual machine knowing about or interacting with the host system or other guest systems in any way. By definition, hypervisors are completely isolated. The level of isolation for containers vary depending on the implementation. Implementations vary quite considerably in this respect.


text:
Q: How to "collapse" rows? So, if my current resultset is:
 Set  |  Label  |  Val
------------------------
  A   |  "LabA" |  NULL
  A   |  "LabA" |   1
  A   |  "LabB" |  NULL
  A   |  "LabB" |   2
  B   |  "LabA" |  NULL
  B   |  "LabA" |   3
  B   |  "LabC" |  NULL

What I really want is:
 Set  |  Label  |  Val
------------------------
  A   |  "LabA" |   1
  A   |  "LabB" |   2
  B   |  "LabA" |   3
  B   |  "LabC" |  NULL

How can I "collapse" the rows to get the desired resultset?

A: You just need to do a MAX() aggregate with a GROUP BY on the Set and Label columns:
Select  Set, Label, Max(Val) Val
From    YourTable
Group By Set, Label
Order By Set, Label


text:
Q: I am trying to install new version of Ruby, but still see old gems, why? My previous installation was messed up. So I renamed my ruby directory into rubyBad, and ran WindowsInstaller again, to install into a virgin Ruby200-x64 directory.  Still, when I go to

F:\ruby\Ruby200-x64\lib\ruby\gems\2.0.0\gems

I see a whole lot of gems, including Rails. Why is that? And how do I uninstall Ruby cleanly?


text:
Q: Perl -- regex issue I have the following code to get a substring inside an string, I'm using regular expressions but they seem not to work properly. How can I do it?
I have this string:
vlex.es/jurisdictions/ES/search?textolibre=transacciones+banco+de+bogota&translated_textolibre=,300,220,00:00:38,2,0.00%,38.67%,€0.00

and I want to get this substring:
transacciones+banco+de+bogota

The code:
open my $info, $myfile or die "Could not open $myfile: $!";

while (my $line = <$info>) {
    if ($line =~ m/textolibre=/) {
        my $line =~ m/textolibre=(.*?)&translated/g;
        print $1;
    }

    last if $. == 3521239;
}

close $info;

The errors:
Use of uninitialized value $line in pattern match (m//) at classifier.pl line 10, <$info> line 20007.
Use of uninitialized value $1 in print at classifier.pl line 11, <$info> line 20007.

A: You are using the wrong tool for the job. You can use the URI module and its URI::QueryParam module to extract the parameters:
use strict;
use warnings;
use URI;
use URI::QueryParam;

my $str = "ivlex.es/jurisdictions/ES/search?textolibre=transacciones+banco+de+bogota&translated_textolibre=,300,220,00:00:38,2,0.00%,38.67%,0.00";

my $u = URI->new($str);
print $u->query_param('textolibre');

Output:
transacciones banco de bogota

A: the second declaration of $line is erroneous, drop my:
$line =~ m/textolibre=(.*?)&translated/g;

A: Sorry but I've found the answer. At line 10 my $line =~ m/textolibre=(.*?)&translated/g; I'm declaring the same variable two times so that's why throws the errors.
Thanks!


text:
Q: Junk characters in csv file during export I am trying to export dynamic string content on csv file. But when any currency symbol comes like $,€, csv file shows junk characters right after the currency symbol.
 eg:
 string dynString = "test user,$15,452.00,USA";

the value in the above variable is dynamically generated
 when the csv is opened it looks like
 "test user,$?15,452.00,USA"

I have tried UTF8, UTF16, UTF32, UniCode, Windows-1252 but nothing worked.
Below is my code:
string dynString = "test user,$15,452.00,USA";

databaseField = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(dynString ));


text:
Q: How to prevent the opening of the YouTube application in a iOs? I have a slider with youtube players. I use lazyload technologies with data-src=, when the slider swiped, data-src= is changing on src=. And then,When an attribute src is added, an YT application is opened. I tried everything, some params in src iframe, example:
<iframe src="https://www.youtube.com/embed/BoS0UrM-zQs/?
enablejsapi=1&playsinline=1&modestbranding=1&autoplay=0&controls=0"
data-src="https://www.youtube.com/embed/BoS0UrM-zQs" type="text/html"
frameborder="0" allowfullscreen=""></iframe>

but it doesn't work.


text:
Q: Java trustmanager behavior on expired certificates Does java's TrustManager implementation ignore if a certificate has expired?
I tried the following:
 - Using keytool and parameter -startdate "1970/01/01 00:00:00" I created a P12 keystore with an expired certificate.
- I exported the certificate:
Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 1 entry

Alias name: fake
Creation date: 5 ╠ά± 2011
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Malicious, OU=Mal, O=Mal, L=Fake, ST=GR, C=GR
Issuer: CN=Malicious, OU=Mal, O=Mal, L=Fake, ST=GR, C=GR
Serial number: -1c20
Valid from: Thu Jan 01 00:00:00 EET 1970 until: Fri Jan 02 00:00:00 EET 1970
Certificate fingerprints:
         MD5:  A9:BE:3A:3D:45:24:1B:4F:3C:9B:2E:02:E3:57:86:11
         SHA1: 21:9D:E1:04:09:CF:10:58:73:C4:62:3C:46:4C:76:A3:81:56:88:4D
         Signature algorithm name: SHA1withRSA
         Version: 3

*******************************************

I used this certificate as server certificate for Tomcat.
Then using an apache httpClient I connected to tomcat, but first I added the expired certificate to the client's trust-store (using a TrustManager
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

and loading the expired certificate).
I was expecting the connection to fail.
Instead the connection succeeds.
Using System.setProperty("javax.net.debug", "ssl");
I see:
***
Found trusted certificate:
[
[
  Version: V3
  Subject: CN=Malicious, OU=Mal, O=Mal, L=Fake, ST=GR, C=GR
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

  Key:  Sun RSA public key, 1024 bits
  modulus: 10350555024148635338735220482157687267055139906998169922552357357346372886164908067983097037540922519808845662295379579697361784480052371935565129553860304254832565723373586277732296157572040989796830623403187557540749531267846797324326299709274902019299
  public exponent: 65537
  Validity: [From: Thu Jan 01 00:00:00 EET 1970,
               To: Fri Jan 02 00:00:00 EET 1970]
  Issuer: CN=Malicious, OU=Mal, O=Mal, L=Fake, ST=GR, C=GR
  SerialNumber: [   -1c20]

]

I see that in TLS handshake the expired certificate is send by Tomcat connector.
But the client (i.e. the TrustManager) does not reject the connection.
Is this the default behavior?
Am I suppose to configure the trustmanager somehow to check for expiration?
UPDATE:
I found that the actual TrustManager used is X509TrustManagerImpl. Here X509TrustManagerImpl says that this class has a minimal logic.May be I am using the wrong TrustManager?
UPDATE2:
From the javadoc X509TrustManager it is not clear if it checks for certificate expiration
void checkServerTrusted(X509Certificate[] chain,String authType)
                                throws CertificateException

Given the partial or complete
  certificate chain provided by the
  peer, build a certificate path to a
  trusted root and return if it can be
  validated and is trusted for server
  SSL authentication based on the
  authentication type.The authentication
  type is the key exchange algorithm
  portion of the cipher suites
  represented as a String, such as
  "RSA", "DHE_DSS". Note: for some
  exportable cipher suites, the key
  exchange algorithm is determined at
  run time during the handshake. For
  instance, for
  TLS_RSA_EXPORT_WITH_RC4_40_MD5, the
  authType should be RSA_EXPORT when an
  ephemeral RSA key is used for the key
  exchange, and RSA when the key from
  the server certificate is used.
  Checking is case-sensitive.

Thanks

A: I've just had a similar issue myself while overriding checkServerTrusted.
Turns out that if you need to check expiration you can call X509Certificate.checkValidity() and it will throw either a CertificateExpiredException or a CertificateNotYetValidException. Both of these extend CertificateException so they can be happily thrown by checkServerTrusted.
To solve your problem you could implement a new X509TrustManager which creates your original instance in its constructor, implements all methods as calls to the original instance, and adds a call to checkValidity for each certificate in certs[] inside checkServerTrusted.

A: I did not try your example, but I now I regularly have to regenerate my server certificates (for our development server) since their certificates have quite short validity times.
In our case the client does not have the server certificates themselves in the truststore, but only the certificate of our CA (with longer validity), and when the client tries to connect to the server, both sides get a SSLException (which may be wrapped in another exception in your case).
I guess that the trust manager assumes something like "if you give me expired certificates to trust in, I'll do it".
Try our approach instead (it also saves you to update the client each time the server certificate expires).

A: I believe IBM's JSSE checks for expiry while Sun's does not.

A: Very old thread but I thought I'd share some code that implements Matt Lyons' suggestion above (I think!). I looked at a lot of questions on this but didn't find any actual code examples. AFAIK, this code is ok for Java 6, 7, 8 (not sure about earlier/later versions).
This is where I create the HTTPS URL connection that checks SSL certs against a local truststore (but also checks for cert expiry)
public HttpURLConnection getHttpsUrlConnection(URL url) {
    HttpURLConnection connection = null;
    try {
        // Create the connection
        connection = (HttpsURLConnection) url.openConnection();
        ((HttpsURLConnection) connection).setSSLSocketFactory(getSslSocketFactoryThatChecksCertsAgainstLocalKeystore());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return connection;
}

private SSLSocketFactory getSslSocketFactoryThatChecksCertsAgainstLocalKeystore() {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // I'm using a custom keystore here (useful tips about working with keystores here: https://www.baeldung.com/java-keystore)
        // I think you can use the default keystore (JRE cacerts file) by passing in null here (cast to KeyStore)
        trustManagerFactory.init(getLocalKeystore());
        // Get the trust managers (I think there's normally only one)
        TrustManager trustManagers[] = trustManagerFactory.getTrustManagers();
        // Create an array of MyX509TrustManager objects to extend/replace trustManagers
        MyX509TrustManager myTrustManagers[] = new MyX509TrustManager[trustManagers.length];
        for (int i = 0; i < myTrustManagers.length; i++) {
            if (trustManagers[i] instanceof X509TrustManager) {
                // For each trust manager, create a new MyX509TrustManager (which will check for expired certs!)
                myTrustManagers[i] = new MyX509TrustManager((X509TrustManager) trustManagers[i]);
            }
        }
        // Create a ssl socket factory using my trust manager(s) that will include expired cert checking
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, myTrustManagers, null);
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

This is the class that implements X509TrustManager (and contains a reference to a "real" X509TrustManager which does almost all of the processing).
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.X509Certificate;

public class MyX509TrustManager implements X509TrustManager {

    private X509TrustManager impl;

    public MyX509TrustManager(X509TrustManager impl) {
        this.impl = impl;
    }

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        impl.checkClientTrusted(x509Certificates, s);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        impl.checkServerTrusted(x509Certificates, s);
        checkCertExpiry(x509Certificates);
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return impl.getAcceptedIssuers();
    }

    private void checkCertExpiry(X509Certificate[] x509Certificates) throws CertificateException {
        long currentTime = System.currentTimeMillis();
        for (int i = 0; i < x509Certificates.length; i++) {
            if (currentTime > x509Certificates[i].getNotAfter().getTime()) {
                throw new CertificateExpiredException("Cert expired on " + x509Certificates[i].getNotAfter());
            } else if (currentTime < x509Certificates[i].getNotBefore().getTime()) {
                throw new CertificateExpiredException("Cert will not be valid until " + x509Certificates[i].getNotBefore());
            }
        }
    }
}

There is probably a more elegant way to do this. Suggestions welcome!


text:
Q: Trigger quartz job at certain time Java spring boot I have issue when I launch the application quartz job in my JAVA Spring Boot project is triggered by itself despite it should trigger on the set certain timet for this case 12:00 o'clock every day. I tried to use with SimpleTriggerJobFactory class because I have issue with simple trigger class while configuring job.
My QuartzConfig class
package com.example.demo.config;

import com.example.demo.jobs.CurrencyImportJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Slf4j
@Configuration
public class QuartzConfig {

    final ApplicationContext applicationContext;

    public QuartzConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    SpringBeanJobFactory createSpringBeanJobFactory (){

        return new SpringBeanJobFactory() {

            @Override
            protected Object createJobInstance
                    (final TriggerFiredBundle bundle) throws Exception {

                final Object job = super.createJobInstance(bundle);

                applicationContext
                        .getAutowireCapableBeanFactory()
                        .autowireBean(job);

                return job;
            }
        };
    }
    @Bean
    public SchedulerFactoryBean createSchedulerFactory
            (SpringBeanJobFactory springBeanJobFactory, Trigger trigger) {

        SchedulerFactoryBean schedulerFactory
                = new SchedulerFactoryBean();
        schedulerFactory.setAutoStartup(true);
        schedulerFactory.setWaitForJobsToCompleteOnShutdown(true);
        schedulerFactory.setTriggers(trigger);

        springBeanJobFactory.setApplicationContext(applicationContext);
        schedulerFactory.setJobFactory(springBeanJobFactory);

        return schedulerFactory;

    }

    @Bean
    public SimpleTriggerFactoryBean
    createSimpleTriggerFactoryBean(JobDetail jobDetail)
    {
        LocalDateTime now = LocalDateTime.now().withHour(12).withMinute(0);
        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        SimpleTriggerFactoryBean simpleTriggerFactory = new SimpleTriggerFactoryBean();

        simpleTriggerFactory.setStartTime(date);
        simpleTriggerFactory.setJobDetail(jobDetail);
        simpleTriggerFactory.setStartDelay(0);
        simpleTriggerFactory.setRepeatInterval(1000);
        simpleTriggerFactory.setRepeatCount(0);
        return simpleTriggerFactory;
    }

    @Bean
    public JobDetailFactoryBean createJobDetailFactoryBean(){

        JobDetailFactoryBean jobDetailFactory
                = new JobDetailFactoryBean();
        jobDetailFactory.setJobClass(CurrencyImportJob.class);
        return jobDetailFactory;
    }
}


text:
Q: SQLAlchemy Update row where session has gone out of scope I have an existing get method.
    def get_parameter(self, app, my_business_key):
        my_db = MultiTenantSQLAlchemy(app)
        session = my_db.get_session(app)
        return session.query(MyParameter).filter(MyParameter.my_business_key.in_(my_business_key)).all()

Since I don't have the primary key and I'm updating by a business key, my assumption is that I have to pull the records first.
I get the parameters object, do the updates to it and then want to save them.
    def save_parameters(self, app, my_business_key, my_parameters):
        my_db = MultiTenantSQLAlchemy(app)
        session = lro_db.get_session(app)

        # session.Update(my_parameters)    ?????

        session.flush()
        session.commit()

Every example I find on here shows creating the session, doing the select, doing the update, then flush/commit all in one method. I'd rather not duplicate the GET if I don't have to.
Ideally I'd love for this to all be one singular query like bulk_update_mappings and only go to the DB once but I don't think I can do that without the primary key.

A: Update the table directly, do not fetch / update / save instances if you don't have to.
my_table = MyORMClass.__table__
update_statement = (
    my_table.update()
            .where(my_table.c.business_key == bindparam('key'))
            .values(field_to_set=bindparam('value')))
session.execute(update_statement, [
    {'key': 100, 'value': 'value for 100'},
    {'key': 200, 'value': 'value for 200'},
])

Here the update happens in one round-trip.
the idea is that you use bindparam to bind your data to named placeholders, and then pass a list of dicts where keys match the names of the placeholders. In this case, it's 'key' and 'value', but it can be anything, and of course you can use many arguments in .values(). The example assumes that the business key field is named business_key in your table, and the field you want to update is named field_to_set.
Please note the difference between .where() ans .values(): one takes a condition formed by column object and ==, the other takes plain named arguments.
Of course you can build the update list programmatically, I just show a constant here for simplicity.
See this SQLAlchemy doc for reference.


text:
Q: Drop Down menu doesn't display in Internet Explorer I need help figuring out why the menu I have created does not work properly in IE.  I'm currently in a HTML/CSS class so my experience level is limited.  I'm kind of just googling things and checking my book as I go.
I created this menu from a tutorial I found after googling "css drop down menu".  I'm pretty proud of it but I can't figure out why it does not display properly in Internet Explorer.  It seems to work great in Firefox and Chrome, and more importantly, on ipads.  My company currently uses a java menu and I'd like to replace it with this.
Here is the link:
http://net.saddleback.edu/hyosafi0/CIM271A/random/menutest/menu.htm
I would appreciate any advice on why it does not work in IE or where I should start looking in my code for errors.  I think it has something to do with declaring a doctype but I'm not sure.
Thanks ahead.

A: You are missing an <li> tag on the second Home link.
Also, try inserting <!DOCTYPE html> at the top of your html file. This will get IE out of Quirks mode, which can solve some problems in the future.


text:
Q: Cropping Circular region of interest around a point in MATLAB
I have an image and I want to crop the circular region of interest around a point. I did following in MATLAB:
  vessel=imread('vessel.jpg');
  imshow( vessel)
  t = 0:pi/20:2*pi;
  xc=230; % point around which I want to extract/crop image
  yc=79;
  r=20;   %Radium of circular region of interest
  xcc = r*cos(t)+xc;
   ycc =  r*sin(t)+yc;
   roimaskcc = poly2mask(double(xcc),double(ycc), size(vessel,1),size(vessel,2));
   pr_gccc = find(roimaskcc);
   roimean_cc= mean(vessel(pr_gccc));
  figure, imshow(roimaskcc)

roimaskcc is correct but when I do the following it gives in nX1 matrix but not the region of interest under mask:
  vessel_undermask=vessel(roimaskcc==1);

Can anybody pls. help to extract the circular region of interest around point of interest (xc, yc).
Thanks

A: What you're doing is extract everything from vessel that's outside the mask. Since there's no such thing as circular matrices, Matlab's solution is to output a vector of all values inside the mask.
While that is technically correct, that vector can be pretty hard to work with. An alternative solution is to leave the data matrix square, and set everything outside the mask to NaN:
% make a copy
vessel_undermask = vessel;

% NaN everything outside the mask (in R, G and B layers)
vessel_undermask(repmat(~roimaskcc,[1,1,3])) = NaN;

imshow(vessel_undermask)

This should give you a matrix that's somewhat simpler to work with.
Note that
vessel_undermask(~isnan(vessel_undermask)) ==  vessel(roimaskcc)

A: Yes I got it. I did something like that:
           vesseltry=vessel;
          vesseltry(~roimaskcc)=0;

vesseltry is now my new image with circular region of interest...


text:
Q: Login into Linkedin with JSoup I need to login into Linkedin with Jsoup, preferably.
This is what I'm using to login to another website but it isn't working for Linkedin.
Connection.Response res = Jsoup
    .connect("https://www.linkedin.com/uas/login?goback=&trk=hb_signin")
    .data("session_key", mail, "session_password", password)
    .method(Connection.Method.POST)
    .timeout(60000).

// Also tried "https://www.linkedin.com/uas/login-submit"

Map<String, String> loginCookies = res.cookies();
    //Checking a profile to see if it was succesful or if it returns the login page.
Document currentPage = Jsoup.connect(someProfileLink).cookies(loginCookies).timeout(10000).
System.out.println("" + currentPage.text());

What am I doing wrong?
I need to be able to fetch user profiles by using a web crawler but whatever I try I can't get the login cookies.

A: You can login into Linkedin with this code:
    try {

                String url = "https://www.linkedin.com/uas/login?goback=&trk=hb_signin";
                Connection.Response response = Jsoup
                        .connect(url)
                        .method(Connection.Method.GET)
                        .execute();

                Document responseDocument = response.parse();
                Element loginCsrfParam = responseDocument
                        .select("input[name=loginCsrfParam]")
                        .first();

                response = Jsoup.connect("https://www.linkedin.com/uas/login-submit")
                        .cookies(response.cookies())
                        .data("loginCsrfParam", loginCsrfParam.attr("value"))
                        .data("session_key", "your_login")
                        .data("session_password", "your_password")
                        .method(Connection.Method.POST)
                        .followRedirects(true)
                        .execute();

                Document document = response.parse();

    //            System.out.println(document)

                System.out.println("Welcome "
                        + document.select(".act-set-name-split-link").html());

            } catch (IOException e) {
                e.printStackTrace();
            }


text:
Q: Sum values in 5th column that correspond to same field in 2nd column Considering below file:
0,2,,,10
0,2,,,15
0,1,,,984
0,2,,,9
1,14,,,5

Using awk, I need to calculate the total value in $5 per each $2.
The desired output would look like below:
2,34
1,984
14,5

A: Try:
awk -F, '{a[$2]+=$5};END{for(i in a)print i","a[i]}' <file

A note that array traversal in POSIX awk is unspecified order.

A: With gnu datamash:
datamash -t ',' -s -g 2 sum 5 <infile

the output will be sorted by 2nd column:
1,984
14,5
2,34

A: I'd be tempted to use perl:
#!/usr/bin/env perl
use strict;
use warnings;

my %things;

while (<>) {
    my ( undef, $key, @rest ) = split(/,/);
    $things{$key} += pop(@rest);
}

foreach my $key ( sort { $a <=> $b } keys %things ) {
    print "$key = $things{$key}\n";
}

You could condense that down to a one liner if needs be.


text:
Q: How to add custom calculated column in SQL Server I have a SQL Server query as:
SELECT MD.Author_ID, MD.CoAuthor_ID, ACP.Probability [AC_Probability],
       MD.Venue_ID, AVP.Probability [AV_Probability], A2P.pid [Paper_ID],
       P.abstract_research_area_category_id [Paper_Category_ID],
       MD.Paper_Count, MD.Year
FROM   Merged_Data MD
JOIN   sub_aminer_author2paper A2P    ON MD.Author_ID = A2P.aid AND
                                      MD.Year      = A2P.p_year AND
                                      MD.Venue_ID  = A2P.p_venue_vid
JOIN   sub_aminer_paper P             ON MD.Venue_ID  = P.p_venue_vid AND
                                      MD.Year      = P.p_year
JOIN   AuthorCoAuthorProbability ACP  ON MD.Author_ID = ACP.Author_ID AND
                                      MD.CoAuthor_ID = ACP.CoAuthor_ID AND
                                      MD.Year      = ACP.Year
JOIN   AuthorVenueProbability    AVP  ON MD.Venue_ID = AVP.Venue_ID AND
                                      MD.Author_ID = AVP.Author_ID AND
                                      MD.Year      = AVP.Year
WHERE  MD.Author_ID = 677 AND
       P.abstract_research_area_category_id IS NOT NULL AND
       A2P.pid = P.pid

which give me results as:

I want to add another column i.e. P_Probability at end before Year column which should be calculated as for instance:
For Year = 2005, the Author_ID = 677 has 8, 11 and 12 in Paper_Category_ID column whereas 3 in Paper_Count column, also every Year has maximum 3 rows for each Author_ID if exists.
So value in P_Probability column should be:
Number of times 8 exists in those 3 rows for 677 against 2005 / Paper_Count = 1/3 = 0.333333333333333
Number of times 11 exists in those 3 rows for 677 against 2005 / Paper_Count = 1/3 = 0.333333333333333
Number of times 12 exists in those 3 rows for 677 against 2005 / Paper_Count = 1/3 = 0.333333333333333
In other words the P_Probability calculation concept is:
Number of times DISTINCT Paper_Category_ID exists in 3 rows for an Author_ID in Year divided by Paper_Count in that Year


text:
Q: Springboot @PutMapping 405 error from postman Springboot version 2.1.8.RELEASE

controller

    @PutMapping("/sample/{id}")
    public Sample update(@PathVariable String id, @RequestBody Sample s){
        s.setId(id);
        return sampleService.update(s);
    }

postman

PUT    http://localhost:8080/sample/sspa01
return
{
    "status": 405,
    "error": "Method Not Allowed",
    "message": "Request method 'PUT' not supported",
    "path": "/sample/sspa01"
}

Thanks to let me know how to fix this problem

A: In here  can solve this by defining an explicit mapping for PUT, in the existing method mapping
Try this one
  //@PutMapping("/sample/{id}")

@RequestMapping(value = "/sample/{id}", produces = "application/json",  method=RequestMethod.PUT)

  @RequestMapping(value = "/sample/{id}", produces = "application/json",  method=RequestMethod.PUT)
    public Sample update(@PathVariable("id") String id, @RequestBody Sample s){
        s.setId(id);
        return sampleService.update(s);
    }

A: In my case the url was not part of permitAll() once added it worked fine, can you check your @EnableWebSecurity config for below method
  @Bean
  SecurityFilterChain filterChain(HttpSecurity http)


text:
Q: change the share icons from the facebook, linkedin, google+, tweeter I try to put in a page the share buttons of facebook, linkedin, google+, twitter

*

*http://developers.facebook.com/docs/reference/plugins/like/

*https://dev.twitter.com/docs/tweet-button
but with another graphism.
Is there a 'simple' way to do so?
I can not really use css or jQuery are they are in an iframe
Thank you

A: Make a custom button with whatever CSS you wish to and then position the standard like button over it with 100% transparency.
Though you won't be able write custom event handlers (if that's what you wanted jquery for ) for those buttons. That's why in first place these buttons don't allow you to modify them.


text: Q: Is it possible to animate the bitmap in Android Splash Screen? I have implemented a splash screen for my android app which doesn't have a layout, instead, we are setting the splash screen image through the theme (window background). So is it possible to do an animation where there is no layout available?


text:
Q: Why can't i telnet my aws instance? Created an AWS AMI instance.
I can telnet from the instance itself
telnet [Pv4 Public IP] 9200
But not from my pc.
This is my security group

What am I doing wrong?

A: You can check your Network ACL configurations.
It looks like there is some other firewall in between your PC and server which is blocking you on 9200.

A: If you can access port 80 via telnet or you're able to SSH in it's likely you have a network ACL in place. If you can not access port 80 via telnet but you can via a browser it's like a local config - maybe AV or a firewall.
EC2 instances use security groups for their firewall
Another test to narrow down the the issue would to see if you could telnet from another instances in the same subenet in the same AZ.  Being in the same subnet you should not be affected by a network ACL.

A: You can have a look at this telnet-to a cloud instance from outside
The solution to problem was "Open the services and make the telnet manual and right click on it and chose start"
As well make sure that the instance is residing in a public VPC

A: Based on what you've described, there isn't really much else to work with.  Your ability to telnet the public IP from the instance implies the server is listening on the external interface and your security group is already set to have the port open to all incoming connections.
Aside from the trivial overlooking of not actually having the instance under the listed security group, the only possibility I can think of now is an active firewall on the instance.  In the case of iptables or ufw (which is an interface to iptables), it's trivial to verify whether they are indeed getting in the way:
// List iptables access rules
sudo iptables -L -v

// List access rules via ufw
sudo ufw status

A: You said: "This is my SG", but...which way? Inbound or outbound?
It can simply be that your host can't reply to your PC.
Try to add a rule which adds outbound TCP ranging from ports 32768 to 65535 (ephemeral ports), so that the telnet server response packets can travel back to your PC.
Otherwise, like the others said, look at one level up, VPC-level (network ACL).

A: You might have your acceptor process running on 127.0.0.1:9000 which means only local clients can connect.  This is not related to your Security Group which could be wide open.
Run lsof -i:9000 if on unix.
If you see something like this under NAME then host IP used to start your acceptor will needs to change from 127.0.0.1 to 0.0.0.0 (and secure via SG/FW).
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
java    2777 ubuntu  148u  IPv6  26856      0t0  TCP localhost:afs3-callback (LISTEN)

A: Need to ensure your SSH key you generated via IAM and attached to the EC2 at launch is added to the login:
ssh-add -K <yourkeyname>.pem

ssh ubuntu@<yourdns or ip>.com   == or ==  ssh ec2-user@<yourdns or ip>

A: A Telnet service is not installed by default on an Amazon Linux AMI.
If you wish to use it, you will need to install it yourself, eg: Install and Setup Telnet on EC2 Amazon Linux or CentOS.
However, these days it is recommended to use ssh instead of telnet because it is more secure. See: Telnet on wikipedia

A: Just a thought, check firewall of your PC.


text:
Q: C# web browser alternative? I am looking for an alternative to web browser in C# that doesn't require being viewed, it needs to have navigation, the notice of when it's navigating and document loading has completed.
It also needs to be able to get and set elements by name, id, etc...
Is there such a way to do this without having webbrowser show up to the users?

A: Use the .net classes that allow for retrieval of http information without UI controls, namely HttpWebRequest or the simpler WebClient.  HttpWebRequest has events that you can provide listeners for in order to execute actions as desired as specified times.  Here's a link to a page that exhibits an example of using such an event.

A: Say what? Use the Web Browser control. You don't need to make it visible if you don't want to.

A: See HtmlAgilityPack.  It will load documents and allows XPath expressions to find elements.

A: If you really need a browser control (for example you're doing a web scraper requiring execution of javascript, which you can't implement with a WebClient or HttpWebRequest), try GeckoFX, an open-source component which makes it easy to embed Mozilla Gecko (Firefox) into any .NET application.


text:
Q: How to filter array by object value and return a new array? I am having a hard time in finding a way to filter this array by id value, and generate a new one preserving coords with it's filter.
Array example:
var herbs =[
{
"coords":[3300,2796],"items":[
{id: "dandelion",qty: 72},
{id: "sage",qty: 4},
{id: "valerian",qty: 1},
]},
{
"coords":[3300,2800],"items":[
{id: "dandelion",qty: 26},
{id: "valerian",qty: 7},
{id: "sage",qty: 2},
]},
{
"coords":[3300,2804],"items":[
{id: "dandelion",qty: 57},
{id: "sage",qty: 4},
{id: "wormwood",qty: 1},
]}]

I want to filter it by id, generating a new one with it's coords.
Example:
Filtering by id = dandelion
var dandelion =[
{
"coords":[3300,2796],"items":[
{id: "dandelion",qty: 72},
]},
{
"coords":[3300,2800],"items":[
{id: "dandelion",qty: 26},
]},
{
"coords":[3300,2804],"items":[
{id: "dandelion",qty: 57},
]}]

Filtering by id = sage
var sage =[
{
"coords":[3300,2796],"items":[
{id: "sage",qty: 4},
]},
{
"coords":[3300,2800],"items":[
{id: "sage",qty: 2},
]},
{
"coords":[3300,2804],"items":[
{id: "sage",qty: 4},
]}]

Also, this array it's pretty big, I have 467.000 coords. So I plan to filter it and save a new file with each filtered.

A: You can use reduce for this to push to a new array with items the result of a filter within the reduce call. It only pushes to the new array when the search term is found somewhere in the items:

var herbs =[
    {
    "coords":[3300,2796],"items":[
    {id: "dandelion",qty: 72},
    {id: "sage",qty: 4},
    {id: "valerian",qty: 1},
    ]},
    {
    "coords":[3300,2800],"items":[
    {id: "dandelion",qty: 26},
    {id: "valerian",qty: 7},
    {id: "sage",qty: 2},
    ]},
    {
    "coords":[3300,2804],"items":[
    {id: "dandelion",qty: 57},
    {id: "sage",qty: 4},
    {id: "wormwood",qty: 1},
    ]}]

function filterByID(array, id) {
    return array.reduce((a, c) => {
        let items = c.items.filter(i => i.id === id )
        if (items.length){
            a.push({
            coords: c.coords,
            items: items
            })
        }
        return a
    }, [])
}

console.log(filterByID(herbs, "dandelion"))
console.log(filterByID(herbs, "sage"))

A: It is very straightforward. Use standard Array methods map and filter to get what you want.

var herbs = [{
    "coords": [3300, 2796],
    "items": [{
        id: "dandelion",
        qty: 72
      },
      {
        id: "sage",
        qty: 4
      },
      {
        id: "valerian",
        qty: 1
      },
    ]
  },
  {
    "coords": [3300, 2800],
    "items": [{
        id: "dandelion",
        qty: 26
      },
      {
        id: "valerian",
        qty: 7
      },
      {
        id: "sage",
        qty: 2
      },
    ]
  },
  {
    "coords": [3300, 2802],
    "items": [{
        id: "dandelion",
        qty: 26
      },
      {
        id: "valerian",
        qty: 7
      },
      //no sage
    ]
  },
  {
    "coords": [3300, 2804],
    "items": [{
        id: "dandelion",
        qty: 57
      },
      {
        id: "sage",
        qty: 4
      },
      {
        id: "wormwood",
        qty: 1
      },
    ]
  }
];

function filterHerbs(id) {
  return herbs.map((h) => {
      return {
        coords: h.coords,
        items: h.items.filter((i) => i.id == id)
      }
    })//filter result in case of empty item arrays
    .filter((h) => h.items.length);
}
var dand = filterHerbs('dandelion')
console.log(dand);
var sage = filterHerbs('sage');
console.log(sage);

A: const dandelion = herbs.map(
    ({coords, items}) => items.filter(
        ({id}) => id === 'dandelion'
).map(ob => ({coords, ...ob})));


text:
Q: Simple way to convert datarow array to datatable I want to convert a DataRow array into DataTable ... What is the simplest way to do this?

A: Why not iterate through your DataRow array and add (using DataRow.ImportRow, if necessary, to get a copy of the DataRow), something like:
foreach (DataRow row in rowArray) {
   dataTable.ImportRow(row);
}

Make sure your dataTable has the same schema as the DataRows in your DataRow array.

A: DataTable Assetdaterow =
    (
        from s in dtResourceTable.AsEnumerable()
        where s.Field<DateTime>("Date") == Convert.ToDateTime(AssetDate)
        select s
    ).CopyToDataTable();

A: DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();

A: DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{
    dt.ImportRow(dr);
}

A: .Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method
For datarow array just use .CopyToDataTable() and it will return datatable.
For single datarow use
new DataRow[] { myDataRow }.CopyToDataTable()

A: You could use System.Linq like this:
if (dataRows != null && dataRows.Length > 0)
{
   dataTable = dataRows.AsEnumerable().CopyToDataTable();
}

A: For .Net Framework 3.5+
DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();

But if there is no rows in the array, it can cause the errors such as The source contains no DataRows. Therefore, if you decide to use this method CopyToDataTable(), you should check the array to know it has datarows or not.
if (dr.Length > 0)
    DataTable dt1 = dr.CopyToDataTable();

Reference available at MSDN:
DataTableExtensions.CopyToDataTable Method (IEnumerable)

A: Here is the solution. It should work fine.
DataTable dt = new DataTable();
dt = dsData.Tables[0].Clone();
DataRows[] drResults = dsData.Tables[0].Select("ColName = 'criteria');

foreach(DataRow dr in drResults)
{
    object[] row = dr.ItemArray;
    dt.Rows.Add(row);
}

A: DataTable dt = new DataTable();

DataRow[] dr = (DataTable)dsData.Tables[0].Select("Some Criteria");

dt.Rows.Add(dr);

A: Another way is to use a DataView
// Create a DataTable
DataTable table = new DataTable()
...

// Filter and Sort expressions
string expression = "[Birth Year] >= 1983";
string sortOrder = "[Birth Year] ASC";

// Create a DataView using the table as its source and the filter and sort expressions
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows);

// Convert the DataView to a DataTable
DataTable new_table = dv.ToTable("NewTableName");

A: Simple way is:
// dtData is DataTable that contain data
DataTable dt = dtData.Select("Condition=1").CopyToDataTable();

// or existing typed DataTable dt
dt.Merge(dtData.Select("Condition=1").CopyToDataTable());

A: Incase anyone needs it in VB.NET:
Dim dataRow as DataRow
Dim yourNewDataTable as new datatable
For Each dataRow In yourArray
     yourNewDataTable.ImportRow(dataRow)
Next

A: You need to clone the structure of Data table first then import rows using for loop
DataTable dataTable =dtExisting.Clone();
foreach (DataRow row in rowArray) {
   dataTable.ImportRow(row);
}

A: DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
 DataRow AddNewRow = dataTable.AddNewRow();
 AddNewRow.ItemArray = dr.ItemArray;
 dataTable.Rows.Add(AddNewRow);
}


text:
Q: Using jQuery plugin as Angular Directive I'm trying to use a jQuery plugin that can curve text (Arctext.js) as an Angular Directive.
The Directive seems to work fine, the given text is curved as expected, except that I want this text to be an Angular variable.
And the problem is the jQuery plugin seems to be executed before Angular resolves the variable value.
My html element :

{{ myController.myVar }}

My directive :
return {
    restrict: "C",
    link: function(scope, element, attrs) {
        element.arctext({radius: 500})
    }
}

The page displays '{{ myController.myVar }}' as curved text.
How to get the variable value instead ?

A: Try this:
HTML:

Directive:
return {
    restrict: 'C',
    link: function(scope, element, attrs) {
        attrs.$observe('text', function(newval) {
            if (newval) {
                $(element).text(newval).arctext({radius: 500})
            }
        });
    }
}


text:
Q: Why Geocoder.getFromLocationName returns null? I am using google map V2. I want to use geocoderto find the location but getFromLocationName() it is returning me null value and I couldn't find why. Just see my code and suggest me, what should I do?
EditText sLocation = (EditText) v.findViewById(R.id.editText1);
                String location = sLocation.getText().toString();

                List<android.location.Address> addressList= null;

                if (location != null || !location.equals("")) {
                    Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
                    try {
                        addressList = geocoder.getFromLocationName(location, 1);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    android.location.Address address = addressList.get(0);
                    LatLng latlng = new LatLng(address.getLatitude(), address.getLatitude());
                    gMap.addMarker(new MarkerOptions().position(latlng).title("Marker"));
                    gMap.animateCamera(CameraUpdateFactory.newLatLng(latlng));

                }

A: I was getting null value form getFromLocationName(). Because, my addressList was getting "null" value from location. When I declared my EditText in onClick method then getFromLocationName() return me correct value like this:
sButton =(Button) v.findViewById(R.id.generalId);
sButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EditText sLocation = (EditText)getActivity().findViewById(R.id.editText1);
                location = sLocation.getText().toString();

                List<android.location.Address> addressList= null;

                if (location != null || location.length()>0) {
                    Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
                    try {
                        addressList = geocoder.getFromLocationName(location, 1);

                    } catch (IOException e) {

                            e.printStackTrace();
                    }

                    android.location.Address address = addressList.get(0);
                    String locality = address.getLocality();
                    Toast.makeText(getActivity(), locality, Toast.LENGTH_LONG).show();
                    double latitude = address.getLatitude();
                    double longitude = address.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    gMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
                    gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                }

            }
        });


text:
Q: numpy.array with and without specifying dtype behaves strange I am completely puzzled by this.
From the following
import numpy as np

a = np.array([4, -9])
a[0] = 0.4
a

I expected output: array([ 0.4, -9]). But it gives me
array([ 0, -9]).
But when I changed the dtype to f
a = np.array([4, -9], 'f')
a[0] = 0.4
a

It gives me the expected out put of array([ 0.40000001, -9.        ], dtype=float32)
The documentation for numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0) says:

dtype : data-type, optional
  The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method.

When I initialized the array it initialized the values to integers and so when I indexed the array with a float it only recognized the integer part of 0.4 and hence gave me 0. This is how I understand it. Is this correct?. But I am still surprised by this behavior.
Question: What exactly is going on here?

A: The problem is that your array is of dtype=np.int64:
In [141]: a = np.array([4, -9])

In [142]: a.dtype
Out[142]: dtype('int64')

This means that you can only store integers, and any floats are truncated before assignment is done. If you want to store floats and ints together, you should specify dtype=object first:
In [143]: a = np.array([4, -9], dtype=object)

In [144]: a[0] = 0.4

In [145]: a
Out[145]: array([0.4, -9], dtype=object)

As for the issue with array([ 0.40000001, -9.        ], 0.4, as a floating point number does not have an exact representation in memory (only an approximate one), which accounts for the imprecision you see.


text:
Q: fraction with 2 variables, and radicals in numerator I arrived at the following solution to a problem in pre-calculus:
$$
\frac{2xh + h^2 + \sqrt{x+h} - \sqrt{x}}{h}
$$
However, this can be simplified further to:
$$
2x+h+\frac{1}{\sqrt{x+h}+\sqrt{x}}
$$
The steps to simplify were not provided. I substituted in $x = 9, h = 16$ to confirm and I've searched a few places, but am at a loss as to how the term
$$
\frac{\sqrt{x+h} - \sqrt{x}}{h}
$$
can be simplified to:
$$
\frac{1}{\sqrt{x+h}+\sqrt{x}}
$$
What are the steps and relevant rules?

A: This is an example of the very useful "multiply by the conjugate" trick. The trick is based on the fact that
$$(a+b)(a-b)=a^2-b^2,$$
which is easy to verify by direct multiplication — but it's so useful that it's worth remembering!
In your example, the conjugate of the numerator $\left(\sqrt{x+h}-\sqrt{x}\right)$ is the expression $\left(\sqrt{x+h}+\sqrt{x}\right)$, so we're going to multiply the numerator and denominator simultaneously by this conjugate:
$$\frac{\sqrt{x+h}-\sqrt{x}}{h}=\frac{\left(\sqrt{x+h}-\sqrt{x}\right)\left(\sqrt{x+h}+\sqrt{x}\right)}{h\left(\sqrt{x+h}+\sqrt{x}\right)}=\frac{\left(\sqrt{x+h}\right)^2-\left(\sqrt{x}\right)^2}{h\left(\sqrt{x+h}+\sqrt{x}\right)}=\frac{x+h-x}{h\left(\sqrt{x+h}+\sqrt{x}\right)}=\frac{h}{h\left(\sqrt{x+h}+\sqrt{x}\right)}=\frac{1}{\sqrt{x+h}+\sqrt{x}}.$$

A: Note that
$$h = x+h-x = (\sqrt{x+h}-\sqrt{x})(\sqrt{x+h}+\sqrt{x})$$
and therefore,
$$\frac{h}{\sqrt{x+h}+\sqrt{x}} =  \sqrt{x+h}-\sqrt{x}$$


text:
Q: File operation in C++ I have written an object to file but when I read the object from the file, it is not getting the correct value. If 1 object is considered as 1 record and if only 1 record is there in the file, it's getting the value. If I write more records (many objects of the same type) then it's not getting the value.

A: There could be a couple of problems. Of the top of my head it might be an issue with how you are interfacing with the file, as the comments above indicate. Or it might be a serialization issue.
I recently learned that one cannot simply write a class to a file because its not guaranteed to be contiguous memory (other reasons too, but the moral I took was don't do it).
Instead one needs to serialize the object/class before writing it to the file.
A couple of web resources that I found useful for this are:
http://functionx.com/cpp/articles/serialization.htm (I liked this one a lot).
http://functionx.com/cpp/articles/serialization.htm
Is it possible to serialize and deserialize a class in C++?


text:
Q: Rollback mono 4.0.1 to 3.12.0 So, our mono was updated from 3.12.0 to 4.0.1 and caused a bunch of problems with nunit as seen here: New SIGABRT after upgrading to Mono 4 running NUnit tests While upgrading to 4.1.0 snapshot fixes these issues, it hasn't been officially released and we would not like to use it. Instead we'd like to downgrade back to 3.12.0 but it seems that I can't even do that. Running apt-cache showpkg mono-complete gives me only the following options
matt@matt-T420:~/vw3$ apt-cache showpkg mono-complete
Package: mono-complete
Versions:
4.0.1-0xamarin4 (/var/lib/apt/lists/download.mono-project.com_repo_debian_dists_wheezy_main_binary-amd64_Packages)
 Description Language:
                 File: /var/lib/apt/lists/ca.archive.ubuntu.com_ubuntu_dists_vivid_universe_binary-amd64_Packages
                  MD5: dacc30c6a4347277b44c68a99c998d5f
 Description Language: en
                 File: /var/lib/apt/lists/ca.archive.ubuntu.com_ubuntu_dists_vivid_universe_i18n_Translation-en
                  MD5: dacc30c6a4347277b44c68a99c998d5f

3.2.8+dfsg-4ubuntu4 (/var/lib/apt/lists/ca.archive.ubuntu.com_ubuntu_dists_vivid_universe_binary-amd64_Packages)
 Description Language:
                 File: /var/lib/apt/lists/ca.archive.ubuntu.com_ubuntu_dists_vivid_universe_binary-amd64_Packages
                  MD5: dacc30c6a4347277b44c68a99c998d5f
 Description Language: en
                 File: /var/lib/apt/lists/ca.archive.ubuntu.com_ubuntu_dists_vivid_universe_i18n_Translation-en
                  MD5: dacc30c6a4347277b44c68a99c998d5f

However if I browse to http://origin-download.mono-project.com/repo/debian/dists/wheezy/snapshots/3.12.0/ I can see the package but I'm not sure how to add it to my list of repos. I don't know how to modify echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list to pint to that 3.12.0 folder.
I basically just want to blow away mono-4.0, reinstall 3.12.0 and then pin/hold it at that version. Can someone please help?

A: First remove mono 4.0.1
sudo apt-get remove mono-complete

sudo apt-get purge mono-complete

sudo apt-get autoremove

After a few attempts, I have modified my repo like this, which seems to have worked:
echo "deb http://download.mono-project.com/repo/debian wheezy/snapshots/3.12.0 main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list

then ran:
sudo apt-get update

sudo apt-get install mono-complete

mono --version

I am now running 3.12

A: Downgrading packages with apt is a bit of a pain.

you'll basically need to "apt-get install libfoo=3.12.1-0xamarin4" with every upgraded lib on the same command line.

Source: https://twitter.com/directhex/status/596382226121674752 (from the creator of the Mono packages)
You can add the snapshot of old packages repo by following http://www.mono-project.com/docs/getting-started/install/linux/#accessing-older-releases


text:
Q: TypeError: 'cmp' is an invalid keyword argument for this function-Python I am new to python and i am having a script which i try to run it with Python 3.5 and i got this error

priorities[i].sort(cmp=comparer)
TypeError: 'cmp' is an invalid keyword argument for this function

Here is the function that has the error from the script
def comparer(first, second):
    """Compare function for message priorities in maintenance mode"""
    return cmp(int(first["Priority"]), int(second["Priority"]))

def get_sequence(inputs, fcm):
"""Creates right sequence for the maintenance mode"""
flags = count_flags(inputs)
sequence = []
for index, where in [(0, '"Axis"="Elevator"'),
                     (1, '"Axis"="Aileron"'),
                     (2, '"Axis"="Rudder" or "Axis"="HS-ACE"')]:
    if len(flags[index]) == 0:
        sequence += WRITE_SEQUENCE_MAINT_0.Get(where)
    elif len(flags[index]) == 1:
        sequence += WRITE_SEQUENCE_MAINT_1.Get(where)
    elif len(flags[index]) > 1:
        sequence += WRITE_SEQUENCE_MAINT_2.Get(where)
    else:
        raise NotImplementedError("This number of flags does not make sense")

priorities = [[], [], []]
for flag in flags[0] + flags[1] + flags[2]:
    lines = WRITE_PROCESSING_MSGPRIORITY.Get('"Message Enable Flag"="%s" and "FCM Instance"="%s"' % (flag, fcm))
    if len(lines) > 0:
        priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[lines[0]["Axis"]]].append(lines[0])
for i in range(3):
    priorities[i].sort(cmp=comparer)

for message in sequence:
    if "Second Highest Priority" in message["Message"]:
        new_m = priorities[{"Elevator":0, "Aileron":1, "Rudder":2}[message["Axis"]]][1]
        message["Message"] = new_m["Message"]
        message["Lane"] = new_m["Lane"]
        message["EP Bit"] = new_m["EP Bit"]
    elif "Highest Priority" in message["Message"]:
        priorities_for_rudder = priorities[{"Elev":0, "Ail":1, "Rud":2}[message["Axis"]]]
        if len(priorities_for_rudder) > 0: # This rudder message does not exist
            new_m = priorities_for_rudder[0]
            message["Message"] = new_m["Message"]
            message["Lane"] = new_m["Lane"]
            message["EP Bit"] = new_m["EP Bit"]
        else:
            message["Message"] = "Rudder Filler Message"
            message["Lane"] = "COM"
            message["EP Bit"] = "0"
return sequence

This script was written in python 2.7.

A: There is no longer a cmp argument for sorting in python 3.
Use a key, and a function that returns a single value to be mapped for comparison.
Instead of comparer, you can use this function.
def comparer_key(item):
    """Compare keys for message priorities in maintenance mode. Returns a key."""
    return int(item["Priority"])

And then,
for i in range(3):
    priorities[i].sort(key=comparer_key)