text:
Q: Convert System.Drawing.Bitmap to stdole.StdPicture I have a System.Drawing.Bitmap currently and I need to convert it into an stdole.StdPicture.
Currently I'm using:
var pic = (stdole.StdPicture)Microsoft.VisualBasic.Compatibility.VB6.Support.ImageToIPicture
                   (MyDLL.Properties.Resources.Img); // this is a System.Drawing.Bitmap

but I get a Compiler Warning:

Warning 'Microsoft.VisualBasic.Compatibility.VB6.Support.ImageToIPicture(System.Drawing.Image)' is obsolete: '"Microsoft.VisualBasic.Compatibility.* classes are obsolete and supported within 32 bit processes only. http://go.microsoft.com/fwlink/?linkid=160862

So what to use instead? I couldn't find another solution yet...

A: taken from NetOffice http://netoffice.codeplex.com Office Addin Example
public class IconConverter : System.Windows.Forms.AxHost
{
   private IconConverter(): base(string.Empty)
   {
   }

   public static stdole.IPictureDisp GetIPictureDispFromImage(System.Drawing.Image image)
   {

      return (stdole.IPictureDisp)GetIPictureDispFromPicture(image);
   }
}

A: If you do a Google search for [convert .net image to ole picture], you'll find a whole lot of chatter about going the other way (i.e. converting an ole picture to image), and a lot of advice that says, in effect, "don't try to use ole pictures in .NET". I concur. I went down that path a few years ago and decided that I didn't really need the OLE picture that badly.
I strongly recommend that you re-evaluate your need for OLE picture objects. If you're saving images in a database, store them as BLOBs rather than as picture objects. If you absolutely have to use OLE picture objects, then good luck. It's going to be very frustrating.


text:
Q: Double clicked aspx page goes to Mozilla instead of desinger Need help!
I don't know what I did but every time I double-click an aspx page in visual studio, it goes to Mozilla.

Any suggestions?

A: You can't just open .aspx files (or .php files, or any similar ones) in a browser and expect to see the website rendered. You need a webserver to do that.
Normally, that webserver for .aspx pages on Windows would be IIS. But if you're just developing the site on your machine, the developer webserver that's part of Visual Studio should suffice. If you open the solution in Visual Studio, you do that by pressing Ctrl+F5 (by default).

A: Make sure that your file association for 'aspx' files is Visual Studio.
Right-click on an 'aspx' file, click 'Open with...", select Visual Studio.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenCV Haar Classifier Killed I am trying to train a Haar Classifier however during Stage 2 it stops with the message Killed
PARAMETERS:
cascadeDirName: classifier
vecFileName: samples.vec
bgFileName: negatives.txt
numPos: 500
numNeg: 964
numStages: 10
precalcValBufSize[Mb] : 2048
precalcIdxBufSize[Mb] : 2048
stageType: BOOST
featureType: HAAR
sampleWidth: 80
sampleHeight: 40
boostType: GAB
minHitRate: 0.999
maxFalseAlarmRate: 0.5
weightTrimRate: 0.95
maxDepth: 1
maxWeakCount: 100
mode: ALL

Stages 0-1 are loaded

===== TRAINING 2-stage =====
<BEGIN
POS count : consumed   500 : 500
NEG count : acceptanceRatio    964 : 0.182992
Precalculation time: 49
+----+---------+---------+
|  N |    HR   |    FA   |
+----+---------+---------+
|   1|        1|        1|
+----+---------+---------+
|   2|        1|        1|
+----+---------+---------+
|   3|        1|        1|
+----+---------+---------+
|   4|        1|        1|
+----+---------+---------+
|   5|        1|  0.56639|
+----+---------+---------+
Killed

The command I am using to run is below:
opencv_traincascade -data classifier -vec samples.vec -bg negatives.txt  -numStages 10 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 500-nonsym -mem 512  -numNeg 964 -w 80 -h 40 -mode ALL -precalcValBufSize 2048  -precalcIdxBufSize 2048

What is causing this?
N.B: I am following the tutorial given here (replacing the images with a different object in different amounts).

A: Reducing the width and height in the opencv_traincascade command made the program run correctly.
Your -w 80 -h 40 is probably too high for your PC. A recommanded size should be -w 24 -h 24.
I noticed an high usage of hard drive while performing the command unless it's killed. Maybe our hard drives are not quick enough.


text:
Q: Char and unsigned char Where is unsigned char used in C ( please tell about some real-world examples )? Why would we need both char and unsigned char?
Char ranges from -127 to 128 ( 8-bit integer )
Unsigned Char ranges from 0 to 255 ( 8-bit integer )
If the purpose is to store ASCII, why would we need both?
Another question.
Consider this:
char a = 127;
unsigned char b = 255;

When I print it using std::cout. It gives me different characters. Can you explain why?
( I'm using Microsoft vs11 compiler )

A: unsigned char stores a number. You can use it when you need to represent numbers in the range 0 to 255 and want to conserve memory.

A:
Where is unsigned char used in C ( please tell about some real-world examples )?
Why would we need both char and unsigned char?

signed or unsigned are properties of the different C data types (char, short, int, etc...). So it's not a question of whether we need both, both come automatically as part of how C is defined.

Char ranges from -127 to 128 ( 8-bit integer ) Unsigned Char ranges from 0 to 255 ( 8-bit integer )

While that's true for most of the platforms out there, there's nothing garanting that char will be signed. In fact on ARM platforms, it's unsigned. See this fix: http://www.spinics.net/lists/linux-btrfs/msg20653.html as an example of real-world bug introduced by assuming that char is signed.

If the purpose is to store ASCII, why would we need both?

The thing is, the purpose is not to store ASCII. It happens to be used to store ASCII but it's a not a necessity.

char a = 127;
unsigned char b = 255;
When I print it using std::cout. It gives me different characters. Can you explain why? ( I'm using Microsoft vs11 compiler

I think what you're looking for is the following:
#include <iostream>

int main(void)
{
        char a = -1;
        unsigned char b = 255;
        std::cout << a << std::endl << b << std::endl;
        return 0;
}

That is '-1' signed will be equal to '255' unsigned. Please note that this is heavily implementation dependent, and there's nothing that guarantees it will work accross all platforms and compilers.

A: You forgot to mention signed char, which also exists and is a distinct from char.
char has the same range as either signed char or unsigned char and its intended use if for character data (although you can only use narrow encodings, like ASCII, if you want the correspondence of 1 char == 1 character).
Despite the use of char in their names, both signed char and unsigned char are not targeted for character data, but rather to hold small numbers. unsigned char in particular is often used to store raw byte data.


text:
Q: Identifying records via Batch Apex timing out. REQUEST_RUNNING_TOO_LONG I'm trying to identify task records in a production org. The problem is that the data volume is too large to create a report or one-off SOQL Task records. Our task records are huge and are in desperate cleanup, hence us needing to identify certain information before proceeding with mass deletions. There are 1907144 task records (3.6 GB) and 40% of our data usage.
So I thought I would try a batch SOQL to buy more processing time. However I'm getting the following error:

First error: [REQUEST_RUNNING_TOO_LONG] Your request was running for too long, and has been stopped.

I've tried multiple methods of speeding up the query by adding or removing filter criteria, but it always seems to timeout in Production. Putting a limit on the SOQL doesn't seem to help either. Is there something I can change in the batch class to increase the timeout limit or could I add or remove parts of my filter criteria? Note: the Subject LIKE '%Opportunity has been%' is really what I am trying to identify and needs to be in the query somewhere.
Here's my relevant code (edited per Eric's comment below, but it still failed :(
global class batchableSOQL implements Database.Batchable<sObject>, Database.Stateful{

    global List<String> taskRecordIds = new List<String>();
    global String s;
    global List<String> stringLines = new List<String>();

    global Database.QueryLocator start(Database.BatchableContext BC){
        //String twoYearsAgo =  DateTime.now().AddDays(-730).format('yyyy-MM-dd\'T\'hh:mm:ss\'z\'');
        String query = 'select id, subject, type, ActivityDate, WhatId, What.name, CreatedDate from Task WHERE contains_Opportunity_has_been__c  = true  AND Type = \'System Generated Email\' AND Isdeleted = false AND CreatedDate > 2015-05-22T00:00:00Z';
    System.Debug('queryis= '+query);
    return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Task> scope){
        //add the found records to a csv
    }

    global void finish(Database.BatchableContext BC){
        //notify admin of records found with csv attachment
    }

}


text:
Q: numpy.ravel_multi_index error - trying to obtain indices I am using numpy.ravel_multi_index in order to convert a set of nd-indices to a list of linear/ flat indices.
After providing my nd tuple of arrays which looks like this (x, y, z):
([13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26],
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26],
[21, 22, 23, 24, 25, 26])

And the dimensions of the original matrix which the "flat indices" should be cast:
(42, 36, 50)

This is throwing an error saying:
ValueError: operands could not be broadcast together with shapes (14,) (22,) (6,)

However I'm not sure why this is? These indices came from the matrix with dim (42, 36, 50), so why is this a problem?


text:
Q: Checking whether the necessary DOM node is still there in browser before retrying an ajax request In my firefox extension, I am sending an ajax request. If that fails I will retry the request. But at this time, I need to check whether the DOM node I am going to populate after the request completion is still there in browser(User might have closed the tab or navigated away from this page). If it is not there I have to abort the request.
I know that I can do this by a DOM search.(getElementById or $(element)). But since we have the access to the document(element.ownerDocument), can I check whether the document is still valid? I think this would be more efficient.

A: How about:
if (element.ownerDocument && element.ownerDocument.defaultView)

When the tab is closed the document will still be around (you are preventing it from being garbage collected by holding a reference to the element) but it will be detached from a view (window object).

A: Use the .length property. It will return 0 if the element no longer exists. It's preferred over .size() since it doesn't require a function call. From the jQuery docs:

The .size() method is functionally equivalent to the .length property;
  however, the .length property is preferred because it does not have
  the overhead of a function call.


text:
Q: Plotly+ggplot() in R causing strange lines to appear on initial play I am having a strange issue in ggplot with strange lines appearing on the initial play of my animation (in viewer and saved to HTML page through Rstudio). I do not know what could be causing this, and have been stuck on this for multiple days. After the initial start of my program (initial press of play) everything looks correct and as it should. But if its the first press, or the first open of the saved html page, then I see these strange lines. Below is the code I have used to create this map, and also a link to a video of the issue, as it is reproducible. Simply run this code in r and press the play button. I am using simple lat lon points in their respective columns, and an optional radius. The column formatting is "Date,Name,lat,lon,optrad". Any help on this is appreciated!
link to example video: https://imgur.com/a/eBlZb5L
link to sample data https://www.filedropper.com/latlondatloctestforstack_1
library(readr)
library(dplyr)
library(tibble)
library(lubridate)
latlntable<- read_csv("latlondatloctestforstack.csv")

latlntable$Month<-format(latlntable$Date, "%Y-%m")

library(ggplot2)
library(maps)
library(ggthemes)
library(gganimate)
library('plotly')

world <- ggplot() +
  borders("world", colour = "gray85", fill = "gray90") +
  theme_map()

ghost <- tibble(
  Month = c(as.Date('2018-06-01',format="%Y-%m-%d")),#'0',#playing with sort by Month
  optrad = 0, lon = 0, lat = 0) %>%
  mutate(Month = format(Month, "%Y-%m"))

mapn <- world +
  geom_point(aes(x = lon, y = lat, size = optrad, # this is the init transparent frame, optrad is the radius of points
                 frame = Month),
             data = ghost, alpha = 0) +
  #this is my data
  geom_point(position=position_jitter(h=0.005, w=0.005),aes(x = lon, y = lat,
                                                            size = optrad,Name=Name,Date=Date,frame=Month,cumulative = TRUE,group=seq_along(Month)),#,frame=date,
             data = latlntable, colour = 'purple', alpha = .7) +
  scale_radius(range = c(1, 3), breaks = c(10,15,20)) +
  ggtitle("MyMapTitle")+
  theme(plot.title = element_text(hjust = 0.5,size=35),legend.position = "none")

#all below is for interactive html page through plotly using ggplotly
xp<-ggplotly(mapn, tooltip = c('text','Name','Date'))

p <- xp %>%
  animation_opts(
    1000,650, easing = "sin", redraw = FALSE,
  )
p <- p %>%
  layout(xaxis = list(autorange = TRUE,title = "Fixed lat/lon coords displayed",size=10),
         yaxis = list(autorange = TRUE),
         updatemenus = list(
           list(
             type = 'buttons',
             direction = 'right',
             x=0,
             y=0,
             showactive = FALSE,
             buttons = list(list(
               label = 'Pause',
               method = 'animate',
               args = list(NULL, list(fromcurrent = TRUE, mode = "immediate"), NULL)
             )))))
p <- p %>% config(displaylogo = FALSE,
                  modeBarButtonsToRemove = list(
                    'sendDataToCloud',
                    'toImage',
                    'resetScale2d',
                    'hoverClosestCartesian',
                    'hoverCompareCartesian',
                    'lasso2d',
                    'select2d',
                    'toggleSpikelines'
                  ))

animation_slider(p, hide = FALSE)


text:
Q: I am facing problem of U+FB00, U+FB02 I am using Texmaker for practicing, While practicing tex, I encountered 3 errors that are as follows:

*

*! Package inputenc Error: Unicode character ff (U+FB00)(inputenc) not set up for use with LaTeX.See the inputenc package documentation for explanation.Type H  for immediate help.... ...ng Rigaku Miniflex II desktop X-ray diff2

*! Package inputenc Error: Unicode character fl (U+FB02)(inputenc) not set up for use with LaTeX.See the inputenc package documentation for explanation.Type H  for immediate help.... ...(XRD) was carried out using Rigaku Minifl

*! Package inputenc Error: Unicode character ff (U+FB00)(inputenc) not set up for use with LaTeX.See the inputenc package documentation for explanation.Type H  for immediate help.... ...l and elemental determination. X-ray diff
I was using the following packages:
\usepackage[hmargin=2.5cm,vmargin=2.5cm]{geometry}
\usepackage{amsfonts}

I tried all the possible methods to remove them, but all of them went in vein. Please help me.
Thank you

A: You copied and pasted into your document source some Unicode text that contained the ligatures ff (U+FB00) and fl (U+FB02).  (This should not happen if you compiled the document you copied from with modern fonts.)
Do a search-and-replace to replace ff with ff and fl with fl.
You could also \DeclareUnicodeCharacter to do the replacement automatically.


text:
Q: BAT Using for /f on a text file not working? I am trying to use the for /F to feed in 3 variables and use them to move files into the folders they need to be in for organization.
The script is doing exactly what I want it to do... EXCEPT it is only doing it for the very last line in the .txt file.  I thought the /F would automatically do the command for each line in the text file but something is wrong and it is not.
Can anyone tell me how to fix the below code so it will work for every line in the text instead of just the last line?
Thank you!
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2,3 delims=," %%G in (MoveFiles.txt) do (
@set "Account_ID=%%G"
@set "PACKAGE_ID=%%H"
@set "FILE_NAME=%%I")

mkdir -p "O:\Documents and Media\%PACKAGE_ID%\%ACCOUNT_ID%"

SET FOO="O:\MediaAttachments\%FILE_NAME%"
COPY %FOO% "O:\Documents and Media\%PACKAGE_ID%\%ACCOUNT_ID%\%FILE_NAME%"

A: Everything that you want done on every line must be done IN the for loop.
What's happening is that you're updating your variables for each line.  So, they are on the last set items when they come out of the for loop.  Then you do your mkdir, set, & copy which is only for that last item.
Moving the end parenthesis to the bottom should fix only doing things once.
Then change % to ! to use the EnableDelayedExpansion that you've already set up.
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2,3 delims=," %%G in (MoveFiles.txt) do (
    @set "Account_ID=%%G"
    @set "PACKAGE_ID=%%H"
    @set "FILE_NAME=%%I"

    mkdir -p "O:\Documents and Media\!PACKAGE_ID!\!ACCOUNT_ID!"

    SET FOO="O:\MediaAttachments\!FILE_NAME!"
    COPY !FOO! "O:\Documents and Media\!PACKAGE_ID!\!ACCOUNT_ID!\!FILE_NAME!"
)


text:
Q: Upload data to Exasol from python Dataframe I wonder if there's anyways to upload a dataframe and create a new table in Exasol? import_from_pandas assumes the table already exists. Do we need to run a SQL separately to create the table? for other databases, to_sql can just create the table if it doesn't exist.

A: Yes, As you mentioned import_from_pandas requires a table. So, you need to create a table before writing to it. You can run a SQL create table ... script by connection.execute before using import_from_pandas. Also to_sql needs a table since based on the documentation it will be translated to a SQL insert command.

A: Pandas to_sql allows to create a new table if it does not exist, but it needs an SQLAlchemy connection, which is not supported for Exasol out of the box. However, there seems to be a SQLAlchemy dialect for Exasol you could use (haven't tried it yet): sqlalchemy-exasol.
Alternatively, I think you have to use a create table statement and then populate the table via pyexasol's import_from_pandas.


text:
Q: How to detect and find checkboxes in a form using Python OpenCV? I have several images for which I need to do OMR by detecting checkboxes using computer vision.
I'm using findContours to draw contours only on the checkboxes in scanned document. But the algorithm extracts each and every contours of the text.
from imutils.perspective import four_point_transform
from imutils import contours
import numpy as np
import argparse, imutils, cv2, matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

image = cv2.imread("1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 75, 200)

im_test = [blurred, cv2.GaussianBlur(gray, (7, 7), 0), cv2.GaussianBlur(gray, (5, 5), 5), cv2.GaussianBlur(gray, (11, 11), 0)]
im_thresh = [ cv2.threshold(i, 127, 255, 0)  for i in im_test ]
im_thresh_0 = [i[1] for i in im_thresh ]
im_cnt = [cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0] for thresh in im_thresh_0]

im_drawn = [cv2.drawContours(image.copy(), contours, -1, (0,255,0), 1) for contours in im_cnt]

plt.imshow(im_drawn[0])
plt.show()

Input Image:

A: Well... Are the checkboxes always in that region of the image? The checkboxes Always maintain the same size area on the image?
If yes, you can run findContours only in that region of the image...
Or maybe the Template Matching with Multiple Objects, example from OpenCV docs: https://docs.opencv.org/3.4.3/d4/dc6/tutorial_py_template_matching.html

A: *

*Obtain binary image. Load the image, grayscale, Gaussian blur, and Otsu's threshold to obtain a binary black/white image.

*Remove small noise particles. Find contours and filter using contour area filtering to remove noise.

*Repair checkbox horizontal and vertical walls. This step is optional but in the case where the checkboxes may be damaged, we repair the walls for easier detection. The idea is to create a rectangular kernel then perform morphological operations.

*Detect checkboxes. From here we find contours, obtain the bounding rectangle coordinates, and filter using shape approximation + aspect ratio. The idea is that a checkbox is essentially a square so its contour dimensions should be within a range.

Input image -> Binary image

Detected checkboxes highlighted in green

Checkboxes: 52

Another input image -> Binary image

Detected checkboxes highlighted in green

Checkboxes: 2

Code
import cv2

# Load image, convert to grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and filter using contour area filtering to remove noise
cnts, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
AREA_THRESHOLD = 10
for c in cnts:
    area = cv2.contourArea(c)
    if area < AREA_THRESHOLD:
        cv2.drawContours(thresh, [c], -1, 0, -1)

# Repair checkbox horizontal and vertical walls
repair_kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5,1))
repair = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, repair_kernel1, iterations=1)
repair_kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (1,5))
repair = cv2.morphologyEx(repair, cv2.MORPH_CLOSE, repair_kernel2, iterations=1)

# Detect checkboxes using shape approximation and aspect ratio filtering
checkbox_contours = []
cnts, _ = cv2.findContours(repair, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.035 * peri, True)
    x,y,w,h = cv2.boundingRect(approx)
    aspect_ratio = w / float(h)
    if len(approx) == 4 and (aspect_ratio >= 0.8 and aspect_ratio <= 1.2):
        cv2.rectangle(original, (x, y), (x + w, y + h), (36,255,12), 3)
        checkbox_contours.append(c)

print('Checkboxes:', len(checkbox_contours))
cv2.imshow('thresh', thresh)
cv2.imshow('repair', repair)
cv2.imshow('original', original)
cv2.waitKey()


text:
Q: Save Session Android I want to do make my app save session to not login again when i kill the process : when i login in the Main.java he weel redirect me to Menu.java then after i kill the precess an runit again he should take me directly to Menu.java without login with saving the username
exactly like this tutu http://www.tutorialspoint.com/android/android_session_management.htm
this is Main.java "Login Page"
public class Main extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;

public static final String data = "ett";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button exit = (Button)findViewById(R.id.button18);

   exit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
            Intent exit = new Intent(Intent.ACTION_MAIN);
            exit.addCategory(Intent.CATEGORY_HOME);
            exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(exit);

        }
    });

    b = (Button)findViewById(R.id.Button01);
    et = (EditText)findViewById(R.id.username);
    pass= (EditText)findViewById(R.id.password);
    tv = (TextView)findViewById(R.id.tv);

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = ProgressDialog.show(Main.this, "",
                    "Verification ...", true);
             new Thread(new Runnable() {
                    public void run() {
                        login();
                    }
                  }).start();
        }
    });
}

void login(){
    try{

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://192.168.1.4/android/etc.php"); // make sure the url is correct.
        //add your data
        nameValuePairs = new ArrayList<NameValuePair>(2);
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
        nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
        nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        response=httpclient.execute(httppost);
        // edited by James from coderzheaven.. from here....
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response);
        runOnUiThread(new Runnable() {
            public void run() {
                tv.setText("Response from PHP : " + response);
                dialog.dismiss();
            }
        });

        if(response.equalsIgnoreCase("User Found")){
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(Main.this,"Login Success", Toast.LENGTH_SHORT).show();
                }
            });

            SharedPreferences setting = getSharedPreferences(data, 0);
            SharedPreferences.Editor editor = setting.edit();
            editor.putString("et", et.getText().toString());
            editor.commit();
            Intent intent=new Intent(Main.this, Menu.class);

            startActivity(intent);
        }else{
            showAlert();
        }

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}
public void showAlert(){
    Main.this.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
            builder.setTitle("Erreur d'identification");
            builder.setMessage("Code ou mot de passe incorrecte")
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                       }
                   });

            AlertDialog alert = builder.create();
            alert.show();
        }
    });

}

}
Menu.java this wher should the app start after saving session
public class Menu extends ActionBarActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menus);

    Button button1 = (Button)findViewById(R.id.button1);
    Button button3 = (Button)findViewById(R.id.button3);
    Button button4 = (Button)findViewById(R.id.button4);
    Button button14 = (Button)findViewById(R.id.button14);
    Button button5 = (Button)findViewById(R.id.button5);
    Button exit = (Button)findViewById(R.id.button18);

    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent1 = new Intent(Menu.this, emploi.class);
            startActivity(intent1);
        }
    });

    button3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent2 = new Intent(Menu.this, Maritimnews.class);
            startActivity(intent2);
        }
    });

    button4.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent3 = new Intent(Menu.this, Resultats.class);
            startActivity(intent3);
        }
    });

    button14.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent4 = new Intent(Menu.this, Demande.class);
            startActivity(intent4);
        }
    });

    button5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent5 = new Intent(Menu.this, Apropos.class);
            startActivity(intent5);
        }
    });

    exit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
            Intent exit = new Intent(Intent.ACTION_MAIN);
            exit.addCategory(Intent.CATEGORY_HOME);
            exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(exit);

        }
    });

    }

}

i don't know where i put the sharedpreferces exactly to make it save the session
the sharedpreferences there just for passing data between Main.java and Menu.java
i wan't to add another sheredPreferences to save session like facebook means when i login in Main.java ---redirecte--> Menu.java so if i close an run the app again he will start with Menu.java :) and Thank you

A: if you implement that way the user will login only once in your application and will be forever connected. the best is to do it this way:
first add a checkbox to login to let the user decide if he wants to save his login.
add sharepreferences if checked and delete sharepreferences if uncheck.
read sharedpreferences in the onresume() method of main activity and add some logic to intent directly to menu activity if preferences is not null

A: I used mySharedPreferences that indicate to me if user already logged in, and I pass a int value from previous activity to know if the user just enter the app or not.
public class ConnectWithFaceBookActivity extends Activity{

    int mode = Activity.MODE_PRIVATE;
    private SharedPreferences  mySharedPreferences;
    private String TAG = "ConnectWithFaceBookActivity";
    private TextView lblEmail;
    private String accessToken;

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

        mySharedPreferences =  this.getSharedPreferences( "facebook", Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor= mySharedPreferences.edit();
        lblEmail = (TextView) findViewById(R.id.lblEmail);
        LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
        Intent i = getIntent();
        int logout = i.getIntExtra("LOGOUT", 0);

        //checking if already sign in
        if(logout!=1 && mySharedPreferences.getString("email","")!="")//1 represent logout button preesed
        {
            String mString;
            mString= mySharedPreferences.getString("email","");
            lblEmail.setText(mString);

            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
            finish();
        }

        authButton.setOnErrorListener(new OnErrorListener() {

            @Override
            public void onError(FacebookException error) {
                Log.i(TAG, "Error " + error.getMessage());
            }
        });

        // set permission list, Don't foeget to add email
        authButton.setReadPermissions(Arrays.asList("public_profile","user_friends","email"));

        // session state call back event
        authButton.setSessionStatusCallback(new Session.StatusCallback()
        {
            @Override
            public void call(Session session, SessionState state, Exception exception)
            {

                Boolean open = session.isOpened();

                if (open)
                {
                    Log.i(TAG,"Access Token"+ session.getAccessToken());
                    accessToken = session.getAccessToken();
                    Request.newMeRequest (session, new Request.GraphUserCallback()
                    {
                        @Override
                        public void onCompleted(GraphUser user,Response response)
                        {
                            if (user != null)
                            {
                                Log.i(TAG,"User ID "+ user.getId());
                                Log.i(TAG,"Email "+ user.asMap().get("email"));
                                String str = user.asMap().get("email").toString();
                                lblEmail.setText(str);

                                editor.putBoolean("isLogIn",true);
                                editor.putString("email",str);

                                //save the changes that you made
                                editor.commit();
                                Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                    }).executeAsync();
                }
                else
                {
                    editor.putBoolean("isLogIn",false);
                    editor.putString("email","");

                    //save the changes that you made
                    editor.commit();
                }
            }
        });
    }

    public static void callFacebookLogout(Context context) {
        Session session = Session.getActiveSession();
        if (session != null) {
            if (!session.isClosed()) {
                session.closeAndClearTokenInformation();
                //clear your preferences if saved
            }
        } else {

            session = new Session(context);
            Session.setActiveSession(session);

            session.closeAndClearTokenInformation();
                //clear your preferences if saved
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }
}


text:
Q: Only type-check an Ocaml file I am wondering is it possible to only type-check an ml file? More precisely, I have a file a.ml that depends on b.cmi. How can I only type-check a.ml? Note that I don't have b.cmo, only b.cmi.

A: ocamlc -i a.ml should work; it also returns the inferred interface.
Note that even if you don't have b.cmo, you can perfectly compile a.ml (this is what separate compilation is about) with ocamlc -c a.ml.


text:
Q: iPhone display date using a user locale but in other language Is there any solution to display to the user a date using his locale settings but the words to be in a different language?
What I want is to display to a user that has set up en_US a date in german language (month names, weekdays for example).

A: Good question. It is possible if you first create an NSDateFormatter with the user's locale (default), set its style, then store the current date format. After that, set the locale to the language you want to display and reset the date format:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateStyle:NSDateFormatterFullStyle];
NSString *usersDateFormat = [df dateFormat];
[df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier(@"de_DE")] autorelease]];
[df setDateFormat:usersDateFormat];
NSString *dateString = [df stringFromDate:[NSDate date]];

A: The iOS Class Reference for NSDateFormatter has sample code for this:
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
It is in the Overview section.
Basically, you manually set the locale, and the formatter formats the given date with that locale.


text:
Q: Creating a good mongodb schema I am working on an Inventory app for monitors, desktops, laptops, projectors, printers, scanners. So I want to ask, what would be a good structure for this? Should I create a schema each category or as one like
var Item = mongoose.model('Item', {
  category: { type: String, minlength: 5, required: true, trim: true },
  type: { type: String, minlength: 5, required: true, trim: true },
  brand: { type: String, minlength: 5, required: true, trim: true },
  model: { type: String, minlength: 5, required: true, trim: true },
  serial: { type: String, minlength: 5, required: true, trim: true },
  storage: { type: String, minlength: 5, required: true, trim: true },
  graphics: { type: String, minlength: 5, required: true, trim: true },
  ram: { type: String, minlength: 5, required: true, trim: true },
});

The ram and graphics will only be available for desktop and laptop. Is it okay to make a single schema for all or should be schema for each category?

A: This is just fine ,only while doing operations on let say category is anything except desktop or laptop you can omit the property while selecting it from the document
For example
Item.findOne({category: "printer"}).select("-graphics -ram");


text:
Q: Division in JavaScript giving undefined error Im trying to calculate the time between when a user starts typing and when they reach the end. So I have named two constants both using the Date.now(); function. Whenever I run the program it always gives the error : ReferenceError: start is not defined at HTMLInputElement.element.onkeyup (/main.js:86:16) The code is below:
Javascript:

var input = document.getElementById("boch");
input.addEventListener("keyup", function (event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    document.getElementById("bocho").click();
  }
});

var element = document.querySelector("#boch");

element.onkeyup = function () {
  var value = element.value;

   if (value.includes("m")) {
     let start = Date.now();
  }

  if (value.includes("man")) {
    document.getElementById('word-1').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-1').style.backgroundColor = "red";
  }

  if (value.includes("man become")) {
    document.getElementById('word-2').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-2').style.backgroundColor = "red";
  }

  if (value.includes("man become as")) {
    document.getElementById('word-3').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-3').style.backgroundColor = "red";
  }

  if (value.includes("man become as and")) {
    document.getElementById('word-4').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-4').style.backgroundColor = "red";
  }

  if (value.includes("man become as and through")) {
    document.getElementById('word-5').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-5').style.backgroundColor = "red";
  }

  if (value.includes("man become as and through find")) {
    document.getElementById('word-6').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-6').style.backgroundColor = "red";
  }

  if (value.includes("man become as and through find would")) {
    document.getElementById('word-7').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-7').style.backgroundColor = "red";
  }

  if (value.includes("man become as and through find would here")) {
    document.getElementById('word-8').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-8').style.backgroundColor = "red";
  }

  if (value.includes("man become as and through find would here and")) {
    document.getElementById('word-9').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-9').style.backgroundColor = "red";
  }

  if (value.includes("man become as and through find would here and before")) {
    document.getElementById('word-10').style.backgroundColor = 'green';
  } else {
    document.getElementById('word-10').style.backgroundColor = "red";
  }

   if (value.includes("man become as and through find would here and before")) {
     let end = Date.now();

  }
  let millis = start/end;

  console.log(`seconds elapsed = ${Math.floor(millis / 1000)}`);

}

Html:

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

   man become as
   and through find would here and before

<input type="text" id="boch" autocomplete="off">

      <button id="bocho" onclick="document.getElementById('boch').value = ''">Enter</button>

A: Where you have declared the variable 'start' is not in the same scope as when it is being used. This means that
let millis = start/end;

is unable to see start.
You need to change let to be var. This way the scope is not restricted in the same way

A: The error says that the variable start is undefined in your element.onkeyup, that means, in your function. If the variable doesn't exist, is impossible to do any calc with it.
Basicly, you have a scope problem, the variables (let and const) exists only in the local that they are declared, so the start exist only in one if(){}. The same with the variable end.
To fixed it, the ideal is declare the variables (start and end) in the top, before your if's, together to the value.


text:
Q: Cannot add created label to threads I tried to write a function in Google Apps Script that creates a new label in Gmail and adds it to threads.
I have two problems:

*

*When I run the function for the first time (archivedLabel not existing yet) I cannot add it to the threads immediately after it is created.
archivedLabel = GmailApp.getUserLabelByName(labelText) at the end of the if statement will still return null and the script crashes.
If I run the script for the second time (label already created) everything works fine.

*The new labels only appear in Gmail after the user refreshes the Gmail App in the browser. Is there a way to do this automatically or a method to refresh the labels and messages so I can see the new label in Gmail without manually reloading the page?
function addArchivedLabel(thread){
  var labelText = "Backed up";
  var archivedLabel = GmailApp.getUserLabelByName(labelText);

  //create new archived label if not already existing
  if(archivedLabel == null) {
    var textColor = "#89d3b2"; // Please set this.
    var backgroundColor = "#ffbc6b"; // Please set this.
    var userId = "me";
    var resource = Gmail.newLabel();
    resource.labelListVisibility = "labelShow";
    resource.messageListVisibility = "show";
    resource.name = labelText;
    var labelColor = Gmail.newLabelColor();
    labelColor.textColor = textColor;
    labelColor.backgroundColor = backgroundColor;
    resource.color = labelColor;

    Gmail.Users.Labels.create(resource, userId);
    archivedLabel = GmailApp.getUserLabelByName(labelText);
  }
  archivedLabel.addToThread(thread); //add new label to archived emails
}

A: I just encountered the same problem
For some reason this is working :
function getOrCreateLabel() {
  if (!GmailApp.getUserLabelByName(LABEL_NAME)) {
    GmailApp.createLabel(LABEL_NAME)
  }
  console.log(GmailApp.getUserLabelByName(LABEL_NAME)) // not NULL
}

And this is not working as expected:
function getOrCreateLabel() {
  if (!GmailApp.getUserLabelByName(LABEL_NAME)) {
     Gmail.Users.Labels.create({
       "labelListVisibility": "labelHide",
       "messageListVisibility": "hide",
       "name": LABEL_NAME
     }, "me")
  }
  console.log(GmailApp.getUserLabelByName(LABEL_NAME)) // NULL
}

For the second function,It seems that appsscript cache the response of GmailApp.getUserLabelByName at runtime.
So in my opinion. You will need to create a trigger, here a working exemple:
function addArchivedLabel(thread){
  var labelText = "Backed up";
  var archivedLabel = GmailApp.getUserLabelByName(labelText);

  const thread_id = UserProperties.getProperty("thread")
  // Check if come from trigger
  if (thread_id) {
    //  retrieve the thread
    thread = GmailApp.getThreadById(thread_id)

    // Clean property and trigger
    UserProperties.deleteProperty("thread")
    ScriptApp.getScriptTriggers().forEach((p) => {
      if (p.getHandlerFunction() == "addArchivedLabel") {
        ScriptApp.deleteTrigger(p)
      }
      })
  }

  //create new archived label if not already existing
  if(archivedLabel == null) {
    var textColor = "#89d3b2"; // Please set this.
    var backgroundColor = "#ffbc6b"; // Please set this.
    var userId = "me";
    var resource = Gmail.newLabel();
    resource.labelListVisibility = "labelShow";
    resource.messageListVisibility = "show";
    resource.name = labelText;
    var labelColor = Gmail.newLabelColor();
    labelColor.textColor = textColor;
    labelColor.backgroundColor = backgroundColor;
    resource.color = labelColor;

    Gmail.Users.Labels.create(resource, userId);
    UserProperties.setProperty("thread", thread.getId())
    ScriptApp.newTrigger("addArchivedLabel").timeBased().everyMinutes(1).create()
    return
  }
  archivedLabel.addToThread(thread); //add new label to archived emails
}

// fixture to simulate get thread
    function main() {
      const thread = GmailApp.getInboxThreads()
      addArchivedLabel(thread[0])
    }

Hope it will help


text:
Q: Query Execution Timeout with Postgres 8.4 I want to implement, query time out. Application framework consists, Spring MVC and hibernate.
If I am specifying timeout in session factory. it gives error Timeout is not implemented in Postgresql driver.
I am using postgres 8.4
Code is:
@Override
@Transactional(timeout=20)
public List<MasterBooking> searchMasterBookings(---){//some more code}

error stack trace is:
SQL state [0A000]; error code [0];Method org.postgresql.jdbc4.Jdbc4PreparedStatement.setQueryTimeout(int) is not yet implemented.; nested exception is org.postgresql.util.PSQLException: Method org.postgresql.jdbc4.Jdbc4PreparedStatement.setQueryTimeout(int) is not yet implemented.

How can I implement this ?

A: The postgres driver does not implement this method, see also http://archives.postgresql.org/pgsql-bugs/2008-04/msg00161.php for details. A request for a solution is on the TODO list.
Using a connection pool like e.g. C3P0 helps you implement a controlled timeout behavior in a much better way.


text:
Q: Table splitting – how do we insert a new row? I'm using table splitting to map entities Entity1 and Entity2 to a DB table MyTable.
Is there a way to insert a new row into MyTable by adding an instance of  Entity1 (or Entity2) to the context and let EF construct the necessary Insert command. I tried the following, but it throws an exception:
        Entity2 entity = new Entity2();
        context.Entity2.AddObject(entity);

        context.SaveChanges();// UpdateException: Invalid data encountered. A
                              // required relationship is missing

thank you

A: You must always construct whole record for the split table so if your Entity1 contains navigation property to Entity2 it must be filled:
Entity1 entity = new Entity1();
entity.Entity2 = new Entity2();
context.Entity1.AddObject(entity);
context.SaveChanges();


text:
Q: Nokogiri returns XML tags as well as data XML Data:
<configs>
<config>
<name>XP</name>
<browser>IE</browser>
<browser>FF</browser>
<browser>Chrome</browser>
</config>
</configs>

I'm new to Ruby, Nokogiri, and programming in general.  I'm trying to write a QA tool to help with automation.
Ruby code:
doc = Nokogiri::XML(open("configs.xml"))
configs = doc.xpath("//configs/config").map do |i|
  {'name' => i.xpath('name').to_s, 'browsers' => i.xpath('browser').to_s}
end

configs.each do |i|
  puts i['name']
  puts i['browsers']
end

This does what I want it to, it returns the data, but includes the XML tags.  Is there a way to strip them that I'm just not finding?

A: Use .text to get text node data:
:name => i.xpath('name').text

.to_s is the string representation of an XML node, which is more than you're looking for.
However, the rest of your code is a bit broken if you're expecting individual browser entries.
As-is it'll smash the text data together into a single blob. Instead join them together, etc, for example:
configs = doc.xpath("//configs/config").collect do |cfg|
  browsers = cfg.xpath('browser').collect { |b| b.text }.join(', ')
  { name: cfg.xpath('name').text, browsers: browsers }
end

configs.each do |i|
  puts i[:name]
  puts i[:browsers]
end

You may want a blob of "IEFFChrome", in which case never mind.


text:
Q: Shadow/gradient in top and bottom of element I was looking for a multi component date picker like the one in the image under, but didn't find anything on Github, or elsewhere.
So I decided to make one. I'm having problems implementing the CSS where it fades out on top and bottom.
I thought about using :before and :after in the container, but no success. Can I apply gradients in :before and :after

For example:

ol {
    overflow: hidden;
    width: 8em;
    height: 6em;
    text-align: center;
    border: 0.5em solid black;
    border-radius: 0.5em;
    padding: 0px;
}

li {
    margin: 0px;
    list-style: none;
    padding: 0.5em 0;
    line-height: 1em;
    border: 1px solid #ccf;
}

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

How to make the shadow on top and bottom?

A: Try something like this:

2010

      ...

With the date-picker styled however you like (setting width and height), and the following CSS:
.date-picker {
    position: relative;
    width: 8em;
    height: 6em;
    border: 0.5em solid black;
    border-radius: 0.5em;
}

ol {
    position: absolute;
    overflow: hidden;
    width: 100%;
    height: 100%;
    text-align: center;
    margin: 0;
    padding: 0;
}

li {
    margin: 0px;
    list-style: none;
    padding: 0.5em 0;
    line-height: 1em;
    border: 1px solid #ccf;
}

.shadow {
    position: absolute;
    width: 100%;
    height: 100%;
    background: linear-gradient(rgba(0, 0, 0, 0.2), transparent, transparent, rgba(0, 0, 0, 0.2));
}

This creates a gradient image overlay positioned in front of the ol which is the image's sibling. Keep in mind that the z-index of .shadow needs to be larger than that of the ol.
EDIT: Looking more closely at the image you posted, the gradient seems closer to quadratic than linear. If you want the list to look more rounded, making a non-linear gradient in photoshop or something would make it look much more three dimensional.

A: Yes, you can apply gradients in :before and :after elements.
Example:
ol {
    overflow: hidden;
    width: 8em;
    height: 6em;
    position: relative;
    text-align: center;
    border: 0.5em solid black;
    border-radius: 0.5em;
    padding: 0px;
}

ol:before {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom : 80%;
    content: "";
    background-image: linear-gradient(to bottom, rgba(0,0,0.1) 0%, rgba(0,0,0) 100%);
    z-index: -1;
    pointer-events: none;
}

ol:after {
    position: absolute;
    left: 0;
    right: 0;
    top: 20%;
    bottom : 0;
    content: "";
    background-image: linear-gradient(to bottom, rgba(0,0,0.1) 0%, rgba(0,0,0) 100%);
    z-index: -1;
    pointer-events: none;
}

li {
    margin: 0px;
    list-style: none;
    padding: 0.5em 0;
    line-height: 1em;
    border: 1px solid #ccf;
}

A: Ok, got it by using gradients not on :before / :after but in a new div which floats with position: absolute; like:
.fader {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 9em;
    background: linear-gradient(top, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0) 30%, rgba(0, 0, 0, 0) 70%, rgba(0, 0, 0, 0.7) 100%);
    background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0) 30%, rgba(0, 0, 0, 0) 70%, rgba(0, 0, 0, 0.7) 100%);
    background: -moz-linear-gradient(top, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0) 30%, rgba(0, 0, 0, 0) 70%, rgba(0, 0, 0, 0.7) 100%);
    pointer-events: none;
}

and the HTML:

2010

2011

        ...

jsFiddle: https://jsfiddle.net/bo7dyx83/


text:
Q: Convert unidirectional LSTM cell to Bidirectinoal LSTM cell in tensorflow 1.0 I have this legacy code that was inmplemented in tensorflow 1.0.1.
I want to convert the current LSTM cell to bidirrectional LSTM.
with tf.variable_scope("encoder_scope") as encoder_scope:

cell = contrib_rnn.LSTMCell(num_units=state_size, state_is_tuple=True)
cell = DtypeDropoutWrapper(cell=cell, output_keep_prob=tf_keep_probabiltiy, dtype=DTYPE)
cell = contrib_rnn.MultiRNNCell(cells=[cell] * num_lstm_layers, state_is_tuple=True)

encoder_cell = cell

encoder_outputs, last_encoder_state = tf.nn.dynamic_rnn(
    cell=encoder_cell,
    dtype=DTYPE,
    sequence_length=encoder_sequence_lengths,
    inputs=encoder_inputs,
    )

I found some examples out there.
https://riptutorial.com/tensorflow/example/17004/creating-a-bidirectional-lstm
But I cannot convert my LSTM cell to bidirectional LSTM cell by reffering them.
What should be put into state_below in my case?
Update: Apart from above issue I need to clarify how to convert following decoder network (dynamic_rnn_decoder) to use bidirectional LSTM. (The documentation does not give any clue about that)
with tf.variable_scope("decoder_scope") as decoder_scope:

    decoder_cell = tf.contrib.rnn.LSTMCell(num_units=state_size)
    decoder_cell = DtypeDropoutWrapper(cell=decoder_cell, output_keep_prob=tf_keep_probabiltiy, dtype=DTYPE)
    decoder_cell = contrib_rnn.MultiRNNCell(cells=[decoder_cell] * num_lstm_layers, state_is_tuple=True)

    # define decoder train netowrk
    decoder_outputs_tr, _ , _ = dynamic_rnn_decoder(
        cell=decoder_cell, # the cell function
        decoder_fn= simple_decoder_fn_train(last_encoder_state, name=None),
        inputs=decoder_inputs,
        sequence_length=decoder_sequence_lengths,
        parallel_iterations=None,
        swap_memory=False,
        time_major=False)

Can anyone please clarify?

A: You can use bidirectional_dynamic_rnn [1]
cell_fw = contrib_rnn.LSTMCell(num_units=state_size, state_is_tuple=True)
cell_fw = DtypeDropoutWrapper(cell=cell_fw, output_keep_prob=tf_keep_probabiltiy, dtype=DTYPE)
cell_fw = contrib_rnn.MultiRNNCell(cells=[cell_fw] * int(num_lstm_layers/2), state_is_tuple=True)

cell_bw = contrib_rnn.LSTMCell(num_units=state_size, state_is_tuple=True)
cell_bw = DtypeDropoutWrapper(cell=cell_bw, output_keep_prob=tf_keep_probabiltiy, dtype=DTYPE)
cell_bw = contrib_rnn.MultiRNNCell(cells=[cell_bw] * num_lstm_layers, state_is_tuple=True)

encoder_cell_fw = cell_fw
encoder_cell_bw = cell_bw

encoder_outputs, (output_state_fw, output_state_bw) = tf.nn.bidirectional_dynamic_rnn(
    cell_fw=encoder_cell_fw,
    cell_bw=encoder_cell_bw,
    dtype=DTYPE,
    sequence_length=encoder_sequence_lengths,
    inputs=encoder_inputs,
    )

last_encoder_state = [
                       tf.concat([output_state_fw[0], output_state_bw[0]], axis=-1),
                       tf.concat([output_state_fw[1], output_state_bw[1]], axis=-1)
                     ]

However, as it says in TensorFlow docs, this API is deprecated and you should consider moving to TensorFlow2 and use keras.layers.Bidirectional(keras.layers.RNN(cell))
Regarding the updated question, you cannot use bidirectional in the decoder model as bidirectional would mean it already knew what it still has to generate [2]
Anyway, to adapt your decoder to the bidirectional encoder you could concatenate the encoder states and double the decoder num_units (or half the num_units in the encoder) [3]
decoder_cell = tf.contrib.rnn.LSTMCell(num_units=state_size)
decoder_cell = DtypeDropoutWrapper(cell=decoder_cell, output_keep_prob=tf_keep_probabiltiy, dtype=DTYPE)
decoder_cell = contrib_rnn.MultiRNNCell(cells=[decoder_cell] * num_lstm_layers, state_is_tuple=True)

# define decoder train netowrk
decoder_outputs_tr, _ , _ = dynamic_rnn_decoder(
    cell=decoder_cell, # the cell function
    decoder_fn= simple_decoder_fn_train(last_encoder_state, name=None),
    inputs=decoder_inputs,
    sequence_length=decoder_sequence_lengths,
    parallel_iterations=None,
    swap_memory=False,
    time_major=False)


text:
Q: What is the best way to know if a value is defined in an enum? I read that it is difficult to find out if an element is in an enumeration. So what would be the best way ?
For example, the following code comes from the Linux kernel 2.6.32:
enum v4l2_colorfx {
    V4L2_COLORFX_NONE    = 0,
    V4L2_COLORFX_BW      = 1,
    V4L2_COLORFX_SEPIA   = 2,
};

And this one from the 2.6.38 version:
enum v4l2_colorfx {
    V4L2_COLORFX_NONE        = 0,
    V4L2_COLORFX_BW          = 1,
    V4L2_COLORFX_SEPIA       = 2,
    V4L2_COLORFX_NEGATIVE    = 3,
    V4L2_COLORFX_EMBOSS      = 4,
    V4L2_COLORFX_SKETCH      = 5,
    V4L2_COLORFX_SKY_BLUE    = 6,
    V4L2_COLORFX_GRASS_GREEN = 7,
    V4L2_COLORFX_SKIN_WHITEN = 8,
    V4L2_COLORFX_VIVID       = 9,
};

How would you check if V4L2_COLORFX_NEGATIVE is defined ? Would #ifndef V4L2_COLORFX_NEGATIVE be okay ?

A: You would have to look at a compiler macro in the wider context (for example the version of linux, I don't know what's available) or some other piece of information at compile time. ifndef is for checking if compiler macros are defined, not symbols in code.

A: Check the version of linux in /usr/include/linux/version.h ( you need to install kernel headers though )
it contains something like :
#define LINUX_VERSION_CODE 132640
#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))

So you can use this :
#if LINUX_VERSION_CODE >= KERNEL_VERSION( 2, 6, 38 )


text:
Q: Simulating the transition of packages in a distribution line I am new to python and am trying to run a simulation of a warehouse logistics. The problem is composed of four main agents:
a shed, trucks, motorcycles and a distribution line. The truck enters the shed in one side with a specified amount of boxes, it goes to center of the shed, stops and start unloading the boxes to the distribution line, the distribution line moves the boxes to the other side of the shed where motorcycles pickup one box each.
The objective is to vary the size of the shed and distribution line to find the shape that can deliver more boxes in fixed amount of time (or compute the time taken to distribute a fixed amount of boxes, as in my code for now)
The distribution line is a rectangle, a grid with variable amount of rows and columns, depending on the size of the shed, let's say each cell has 0,50m on each side.
In the code I simulated the truck passing through the shed, and the amount of trucks passing as iterations, the problems is:
how to simulate the boxes moving through the grid (distribution line) from one side to the other, maybe accumulating in the stock until a bike arrives, and have the motorcycles "grab" them and go out after the boxes arrive?
I tried to count the boxes with "+= 1" function but I don't know why it's not working (would not be very realistic as well)
This is the main code:
import time
from Vehicles import Truck, Motorbike

bike1 = Motorbike(10, 1)
truck1 = Truck(10, int(input("Enter how many loads the truck has: ")))
num_iterations = int(input("Enter number of iterations: "))

start = time.time()

shed_width = 4
shed_length = 12
truck_path = int(shed_length * truck1.truck_speed/2)

for n in range(num_iterations):
    truck_middle = False
    while truck_middle is not True:
        for i in range(truck_path):
            x = 100/truck_path
            if i == truck_path/2:
                truck_middle = True
            else:
    #the bar here is to just have some visual feedback while the code runs
                print("\r[%-60s] %d%%" % ('=' * i, x * i), end='')
                time.sleep(0.1)

        print("\ntruck is in the middle")
        truck_middle = True

    # while truck_middle is True:
    #     box = 0
    #     if box < truck1.truck_load:
    #         box += 1
    #     else:
    #         truck_middle = False
    print("This was iteration: " + str(n+1))
    time.sleep(0.01)

end = time.time()

print("\nDone! \nThe simulation took " + str(end - start) + " seconds to complete!")

I also created a class in a file called "Vehicles" for the truck and the motorcycles, where I can define their speed and the load they can carry:
class Truck:
    def __init__(self, truck_speed, truck_load):
        self.truck_speed = truck_speed
        self.truck_load = truck_load

class Motorbike:
    def __init__(self, motorbike_speed, motorbike_load):
        self.motorbike_speed = motorbike_speed
        self.motorbike_load = motorbike_load

I am open to code suggestions, indications of libraries and other resources I can search and study, any help will be much appreciated! thanks!

A: box = 0
while truck_middle == True:

    if box < truck1.truck_load:
        box += 1
    else:
        truck_middle = False

In your way, box will always be 1 and truck_middle is always  True, and it goes in a dead loop


text:
Q: Binary Search Tree - node deletion I am trying to understand why when deleting a node in a BST tree and having to keep the children and adhering to the BST structure, you have to either take the node's right child (higher value, then node being deleted) and if that right child has a left child take that child.  Else just the the node being deleted right child.
Why don't you just take the node being deleted left child, if there's one.  It still works out correctly?
Or have I missed something.
I'm reading this article.

A: You're oversimplifying.
The node selected to replace the one that was deleted must be larger than all the nodes to the left of the deleted one, and smaller than all the nodes to the right. So it must be either the left subtree's rightmost descendant or the right subtree's leftmost descendant; except if one or the other subtree is entirely absent, we can remove a level of tree entirely simply by replacing the deleted node with the child that was present.
The rules listed in the article will always give you the right subtree's leftmost descendant when both trees are present. If you wished, you could indeed derive an alternative ruleset that used the leftmost subtree's rightmost descendant instead.
It does not "work out correctly" to just always use the left child. Indeed, if there is a child on the right and the left child itself has two children, it cannot even be done without essentially rebuilding the tree.

A: You would be correct for the special case that you described. But for something more general where you can have many more levels deeper than the node being deleted you need to replace that node with a node that will be less than everything to the right, and greater than everything to the left. So as an example:
   2
 /  \
1    6
    / \
   4   7
    \
     5

Let's say you wanted to move the node 6, now following your instructions we will replace it with the left child, node 4. Now what do we do with node 5? We could make it the left child of node 7 (or the left most descendant of node 7 if it existed), but why would you do all this reshuffling when you know that removing a leaf is trivial and you just want to replace the node with another node that would keep every node on the left less and every node on the right greater.


text:
Q: Парсинг строки на c# через : Есть строка вида "1:String1:2:2:3:String3:4:String4"
Эту строку нужно распарсить в
string 1 = String1
int 2 = 2
string 3 = String3
string 4 = String4

Как это можно реализовать на c#?
UPD: количество и тип каждого значения заранее известен

A: Для пар ключ-значение можно использовать словарь
static void Main(string[] args)
{
    Dictionary<int, string> dictionary = new Dictionary<int, string>();
    string text = "1:String1:2:2:3:String3:4:String4";
    string[] values = text.Split(':');
    for (int i = 0; i < values.Length - 1; i += 2)
    {
        if (int.TryParse(values[i], out int index))
            dictionary.Add(index, values[i + 1]);
    }

    foreach (KeyValuePair<int, string> pair in dictionary)
    {
        bool isInt = int.TryParse(pair.Value, out _);
        Console.WriteLine("{0} {1} = {2}", isInt ? "int" : "string", pair.Key, pair.Value);
    }
    Console.ReadKey();
}

Вывод в консоль
string 1 = String1
int 2 = 2
string 3 = String3
string 4 = String4


text:
Q: Outputing backslash in a C++ macro Is it possible in C++ to write a macro, which AFTER expansion will output a backslash sign?
Right now I'm using a code:
#define SOME_ENUM(XX) \
    XX(FirstValue,) \
    XX(SecondValue,) \
    XX(SomeOtherValue,=50) \
    XX(OneMoreValue,=100) \

but I want to write a macro, which will generate the code above, so I want to be able to write:
ENUM_BEGIN(name) // it should output: #define SOME_ENUM(XX) \
ENUM(ONE)        // it should output: XX(ONE,) \
//...

But I was not able to write a macro like ENUM_BEGIN, because it should expand to something with backslash on the end.
Is it possible in C++?

A: No, it is not possible. Relevant to this would be §2.2.1, translation phase 2 described in ISO/IEC 14882:2011(E):

Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to
  form logical source lines. Only the last backslash on any physical
  source line shall be eligible for being part of such a splice. If, as
  a result, a character sequence that matches the syntax of a
  universal-character-name is produced, the behavior is undefined. A
  source file that is not empty and that does not end in a new-line
  character, or that ends in a new-line character immediately preceded
  by a backslash character before any such splicing takes place, shall
  be processed as if an additional new-line character were appended to
  the file.

Basically what will happen is the \\\n (where the \n is physically in the source, not an escape), will be treated as a \ character, followed by a line splice. The remaining \ will most likely result in a syntax error (there may be situations where it is legal, but I don't currently see any), and not treated during subsequent translation phases as a line splice (line splicing occurs in only phase #2).

A: I haven't found any documentation for it, but I would've thought that you could just do \\ and you'll generate a backslash.
However, in my research, I see that may not be the biggest thing you'll have to deal with.  As millsj just commented, you'll have issues outputting the # in your ENUM_BEGIN.  See Escaping a # symbol in a #define macro? .


text:
Q: Hibernate keeps looking for configuration file in a different location I built my project using the Eclipse IDE, and placed my hibernate.cfg.xml file in the resources folder (screenshot below):

The problem occurs when I try to reference hibernate.cfg.xml in my DAO classes. Here is a snippet of my code where I get my SessionFactory:
DAO getSessionFactory() example
private static SessionFactory getSessionFactory() {
        String hibernatePropsFilePath = "src/main/resources/hibernate.cfg.xml";
        File hibernatePropsFile = new File(hibernatePropsFilePath);

        Configuration configuration = new Configuration();
        configuration.configure(hibernatePropsFile);
        configuration.addAnnotatedClass(MyClass.class);

        StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();

        return configuration.buildSessionFactory(serviceRegistry);
    }

As you can see, I'm still pointing to the "correct" location in my project, however when I test using Postman, I get the following error:

HTTP Status 500 - Request processing failed; nested exception is
  org.hibernate.internal.util.config.ConfigurationException: Specified
  cfg.xml file
  [C:\Users\MYUSERNAME\Desktop\src\main\resources\hibernate.cfg.xml] does
  not exist

My question: Why is it constantly looking in my Desktop for my file path, and how do I change it to look only in my project? I checked and made sure that my resources path is present in my Web Deployment Assembly (screenshot below):

A: src/main is maven specific project structure to arrange the source files. But after build the compiled classes and resource files are copied to WEB-INF/classes/ directory.
Assuming you are using maven and your resources folder is part of the source structure, then the XML file will be copied to WEB-INF/classes/resources folder.
Change the path to String hibernatePropsFilePath = "/resources/hibernate.cfg.xml";
Update:
After taking a second look at your Web Deployment Assembly settings image, your main/resources folder is mapped to classes directory not classes/resources. so change the code as shown below without use of File.
    Configuration configuration = new Configuration("hibernate.cfg.xml");
    configuration.addAnnotatedClass(ClientCrossRef.class);`
    configuration.configure();

and even more better thing is, since your cfg.xml file is already part of classpath, you don't even need to specify it. Hibernate will look for it in the classpath.
And by the way, you can build the session factory easily as
SessionFactory sessionFactory = new Configuration().configure(
                    "hibernate.cfg.xml")
                    .buildSessionFactory();


text:
Q: Break down date by month and the week of each month using Sql What I need is break down the date by month and the week of that month. For example, for '2020-01-06' I want to see January, 1 week, or for  '2020-01-13', I want to see January, 2nd week.
Here is the code that wrote:
.....
distinct t1.incidentid
,t1.status as [CW_Staus],
t1.title
,t1.createddatetime
,datename(MM,t1.createddatetime) as Month
,datename(ww,t1.createddatetime) as Week
.....

Now, what I see is this

However, with the start of each month, I want to restart the week count. for '2020-02-01', I want to see Feb, 1week.
What am I missing in the code?
Thank you

A: You could try taking the day of the month and divide by 7:
SELECT DISTINCT
    t1.incidentid,
    t1.status AS [CW_Staus],
    t1.title,
    t1.createddatetime,
    DATENAME(MM, t1.createddatetime) AS Month,
    1 + ((DATEPART(day, t1.createddatetime)-1) / 7) AS WeekOfMonth
...

Keep in mind that the above logic assumes that you actually want to reset the count of weeks for each month, at the start of each month.  More typically, there are ISO standard ways of counting the week in the year.  There are edge cases to be considered, as any given year may not have an whole number of weeks.


text:
Q: UICollectionViewDelegate not firing I have created a UICollectionView and manually implemented the datasource and delegate protocols, assigned them to the datasource and delegate properties on the view and supplied a custom flow layout implementation - but I can't seem to get the
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

delegate calls to fire.
I have an example project that uses a UICollectionViewController ... but in my case, I really can't, nor do I want to create a view controller or push it on the stack. I've got the items drawing correctly. I've customized the cells. I've extended the flow layout and customized it so the grid is correct - but tapping on any of the cells fails to fire the delegate selection methods.
Just wondering if there is was something else obvious I was missing.

A: Do you programmatically assign the delegate and data source?
[collectionView setDelegate:self];
[collectionView setDataSource:self];
//or.... (i dont find this method safe or consistent
collectionView.delegate = self;
collectionView.dataSource = self;

edit: You may also want to check if you are referencing the right view for the delegates. If you insert the collection view into a UIView, and you have delegate methods on the view controller, make sure to reference the correct object. If you have touch events, they may also be blocking that call.


text:
Q: Why can't I link with an associative array in a class method? I can't seem to make a small example of this, but maybe someone's run into it before.
I have a class, Path, with a method void find() and when I try to instantiate an associative array of type int[string] inside the method, I get a linker error that looks like this:
/tmp/ccTF0A0c.o: In function `_D6object28__T16AssociativeArrayTAyaTiZ16AssociativeArray6rehashMFNdZHAyai':
game.d:(.text._D6object28__T16AssociativeArrayTAyaTiZ16AssociativeArray6rehashMFNdZHAyai[_D6object28__T16AssociativeArrayTAyaTiZ16AssociativeArray6rehashMFNdZHAyai]+0x44): undefined reference to `_D14TypeInfo_HAyai6__initZ'
collect2: ld returned 1 exit status

If I stick the associative array in the class's members, everything looks fine.
The code looks something like this:
class Path
{
    int[string] bar; // Here it works.
    void find()
    {
        int[string] foo; // Here it fails.
    }
}

A: I just had a very similar problem myself with a class storing an associative array of object values and string keys. Even though this example in the question above actually did compile (Line:3 int[string] bar; // Here it works.) for me it didn't, my compile would fail with this message:
/tmp/cc8XXyP6.o: In function `_D6object64__T16AssociativeArrayTAyaTC2px5pizza8graphics8textures8MaterialZ16AssociativeArray6rehashMFNdZHAyaC2px5pizza8graphics8textures8Material':
/usr/include/d2/4.6/object.di:366: undefined reference to `_D50TypeInfo_HAyaC2px5pizza8graphics8textures8Material6__initZ'
collect2: ld returned 1 exit status

Turns out I solved it myself just by initializing the array in the class's constructor with an AA literal [key:value] containing a single key/value pair and it worked fine.
Example: (Doesn't Compile)
class Cache {
    Material[string] dict;
    ...
    Material load(string filename) {
        ... (File I/O and such)
        dict[filename] = loadedMaterial; //Compiler Error?
    }
}

Example: (DOES Compile)
class Cache {
    Material[string] dict;
    ...
    this() {
        dict = ["notexture" : new Material()]; //Somehow makes all the difference
    }
    ...
    Material load(string filename) {
        ... (File I/O and such)
        dict[filename] = loadedMaterial; //Works fine
    }
}

Not quite the same problem I think but it might still be useful to someone stumbling around with the same error message, this was the first meaningful question I found after googling for an hour.

A: Are you doing incremental compiles?
The D compiler doesn't support that.
[Opinion: The D language will never go mainstream due to this problem]


text:
Q: Regex getting number from string that stops at _ and str after _ underscore I have several strings that look like this:
str1 = "C:/Users/10MedicineA\20072018_medicineName_00222_01111"
str2 = "C:/Users/MedicineB\21072018_medicineName_03333_01121"

I need to extract the digits after the backslash (supposed to be the date) and the medicineName as well as the identifier (which is the first number series after the "medicineName".
So the final result should look like:
['20072018','medicineName','00222']

How is it possible to get everything after the backslash \ till the underscore _?
I would like to do it with regex, and of course its easy to filter the C:/Users/ part, cause its always the same, but thats not true for the rest:
final = re.findall(r'\d+\.*',str1)
['10','20072018','00222','01111']

or
final = re.findall(r'(?=[0-9]).*(?=\_)')

A: If you want to stick with regex, you could do something like:
import re

strings = ["C:/Users/10MedicineA/20072018_medicineName_00222_01111",
           "C:/Users/MedicineB/21072018_medicineName_03333_01121"]

for s in strings:
    r = re.search(r"(\d+)_(medicineName)_(\d+)_", str1)
    if r:
        print(list(r.groups()))

And this gives:
['20072018', 'medicineName', '00222']
['21072018', 'medicineName', '03333']

If you want to cover more general options change to:
"(\d+)_([^_]*)_(\d+)_"

Considering that your strings are paths, you could also use pathlib for that task:
from pathlib import Path

s = "C:/Users/10MedicineA/20072018_medicineName_00222_01111"

last_part = Path(s).name
print(last_part.split("_")[:3])

A: Try this,
import re

str1 = "C:/Users/10MedicineA\20072018_medicineName_00222_01111"
str2 = "C:/Users/MedicineB\21072018_medicineName_03333_01121"

pattern = re.compile(r'(\d+)_([^_\s]*)_(\d+)')

print(list(pattern.search(str1).groups()))
# ['72018', 'medicineName', '00222']

print(list(pattern.search(str2).groups()))
# ['72018', 'medicineName', '03333']

Here is the visualization of my regex pattern.

A: My guess is that this expression might likely return the desired output:
.*\\|(.+?)_

which would collect all chars upto the last \, then using this capturing group (.+?) would return our desired outputs, and simultaneously excludes the last undesired substring after the _.

If you wish to find the first three substrings before _, this expression might work:
\\([^\\_\s]+)_([^\\_\s]+)_([^\\_\s]+)_

Test
import re

regex = r"\\([^\\_\s]+)_([^\\_\s]+)_([^\\_\s]+)_"

test_str = ("C:/Users/10MedicineA\\20072018_medicineName_00222_01111\n"
    "C:/Users/MedicineB\\21072018_medicineName_03333_01121\n"
    "Users/3A Medicine\\\\200726_21-PQmed_00223_07_01110")

print(re.findall(regex, test_str))

DEMO


text:
Q: How do I stop processing rows in Spring-JDBC? I have a consumer that can say he doesn't want to process more data.
I've looked upon the methods in Spring JdbcTemplate, but I see no way to inform Spring I don't want to process more rows when I'm on callback.
I could throw an exception, but then the jdbcTemplate.query(...) would rethrow this exception, which is the behavior I don't wish.
Is there any way to force stop processing rows without causing exception?
jdbc.query(sql, new RowCallbackHandler() {

  @Override
  public void processRow(ResultSet rs) throws SQLException
  {
    // TODO how to stop if I want to do it here?
  }}
);

A: (If somebody comes to this thread) - Use ResultSetExtractor.
Loop through resultset in while condition and break out when needed.
Set<String> distinctNames = jdbcTemplate.query(query,
new ResultSetExtractor<Set<String>>(){
    public Set<String> extractData(ResultSet rs) throws SQLException, DataAccessException {
        Set<String> distinctNames = new HashSet<>();
        Integer cacheMax = 1000
        while(rs.next() && distinctNames.size() <= cacheMax){
        // magic is in while loop condition to break out when we want ignoring rest of results from DB.
            distinctNames.add(rs.getString("COLUMN_NAME"));
        }
        return distinctNames;
    }
});

A: Take a look into:

*

*setFetchSize

*setMaxRows

jdbcTemplate.setFetchSize(intValue): Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when
  more rows are needed for ResultSet objects genrated by this Statement.
  If the value specified is zero, then the hint is ignored. The default
  value is zero.
jdbcTemplate.setMaxRows(intValue): Sets the limit for the maximum number of rows that any ResultSet object generated by this Statement
  object can contain to the given number. If the limit is exceeded, the
  excess rows are silently dropped.

I think that jdbcTemplate.setMaxRows(intValue) could be helpful for your requirements.


text:
Q: Conditional regular expressions in stringr I'm wondering how to implement a conditional regular expression in R.  It seems that this can be implemented in PERL:
?(if)then|else

However, I'm having trouble figuring out how to implement this in R.  As a simple example, let's say I have the following strings:
c('abcabd', 'abcabe')

I would like the regular expression to match "bd" if it is there and "bc" otherwise, then replace it with "zz".  Thus, I would like the strings above to be:
c('abcazz', 'azzabe')

I have tried this using both sub and str_replace neither of which seem to work.  It seems that my syntax might be wrong in sub:
sub('b(?(?=d)d|c)', 'zz', c('abcabe','abcabd'), perl=TRUE)
[1] "azzabe" "azzabd"

The logic is "match b, if followed by d match d, otherwise match c".  With str_replace, I get errors :
str_replace(c('abcabe','abcabd'), regex('b(?(?=d)d|c)'), 'zz')
Error in stri_replace_first_regex(string, pattern, fix_replacement(replacement),  :
Use of regexp feature that is not yet implemented. (U_REGEX_UNIMPLEMENTED)

I primarily use stringr so would prefer a solution using str_replace but open to solutions using sub.

A: You are almost near but you should have conditional pattern true assertion in each step:
(?(?=.*bd)bd|bc)

Live demo
You don't even need conditional regex:
^(.*)bd|bc

R code:
sub('^(.*)bd|bc', '\\1zz', c('abcabe','abcabd'))


text:
Q: Missing something in my input for CountryData dependencies I'm trying to find
(a)which countries have dependencies
(b)and a list of countries that consider themselves dependencies
(c)and a list of countries that don't consider themselves dependencies.

Okay, so to find the countries that have dependencies (part a) I input
 CountryData["Countries", "Dependencies"]

But that output gives me {} throughout the list with the names of 10 or so countries, which I'm not sure are correct.

For part b, of finding the countries that consider themselves dependencies, I have:
 Flatten[Map[CountyData[#,"Dependencies"]&]]

for this part I'm not sure what else I am missing.

I got stuck at part b, so I think this part is similar to part c.

A: The dependencies refer to territories that are not official states of the governing countries, but are also not sovereign states in their own right. It's not clear what you intend to do with the mapping operation, but if I had to guess, you probably wanted to do something like this:
Map[{#, CountryData[#, "Dependencies"]} &, CountryData["Countries"]] /.
    {_, {}} :> Sequence[]
(* {{"Australia", {"ChristmasIsland", "CocosKeelingIslands", "NorfolkIsland"}},
    {"China", {"HongKong", "Macau"}}, ... } *)

i.e., each country paired with its dependencies.
I prefer using rules for such purposes, so I would've probably written this as:
Thread[CountryData["Countries"] ->
    CountryData["Countries", "Dependencies"]] ~DeleteCases~ Rule[_, {}]
(* {"Australia" -> {"ChristmasIsland", "CocosKeelingIslands", "NorfolkIsland"},
    "China" -> {"HongKong", "Macau"}, ... } *)

You can also do this the other way round – a rule mapping each dependency to its governing state:
Thread /@ Thread[CountryData["Countries", "Dependencies"] ->
     CountryData["Countries"]] ~DeleteCases~ Rule[{}, _] // Flatten
(* {"ChristmasIsland" -> "Australia", "CocosKeelingIslands" -> "Australia",
    "NorfolkIsland" -> "Australia", "HongKong" -> "China", "Macau" -> "China", ... *)

A: here's a possible way:
With[{cd = CountryData[]},
  {#[[All, 1]], Flatten@#[[All, 2]], Complement[cd, Flatten@#[[All, 2]]]} &
  @(Select[#, #[[2]] != {} &] &@({#, CountryData[#, "Dependencies"]} & /@ cd))]

Note that it is essentially based on
(Select[#, #[[2]] != {} &] &@({#, CountryData[#, "Dependencies"]} & /@ CountryData[]))

Which gives a nested list of countries and its dependencies.


text:
Q: Parsing Group XML Node from SOAP Response - OBJECTIVE C I have the following XML from SOAP Response how should I parse it ?
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
  <areaSearchResponse  soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
 <areaSearchReturn xsi:type="ns1:QueryBean" xmlns:ns1="http://rpc.xml.coldfusion">
 <details soapenc:arrayType="xsd:anyType[4]" xsi:type="soapenc:Array">
  <details xsi:type="soapenc:string">photo1.jpg</data>
  <details xsi:type="soapenc:int">1224</data>
  <details xsi:type="soapenc:double">552.0</data>
  <details xsi:type="soapenc:double">20.04</data>
 </details>
 <details soapenc:arrayType="xsd:anyType[4]" xsi:type="soapenc:Array">
  <details xsi:type="soapenc:string">photo2.jpg</data>
  <details xsi:type="soapenc:int">1234</data>
  <details xsi:type="soapenc:double">632.0</data>
  <details xsi:type="soapenc:double">34.05</data>
 </details>

I am using NSXMLParser as follows
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

if([[attributeDict valueForKey:@"xsi:type"] isEqualToString:@"soapenc:Array"]
   && [[attributeDict valueForKey:@"soapenc:arrayType"] isEqualToString:@"xsd:anyType[4]"]){

    _propertyInfoArray  =   [[NSMutableArray alloc] init];
    self.isNewRow   =   YES;
    NSLog(@" New Row Created ");
}else{
    self.isNewRow   =   NO;
    _rawData    =   [[NSMutableString alloc] init];
}

}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[_rawData appendString:string];

}

-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

    if(self.isNewRow){
        NSLog(@"Previous Row will be Added to NSSet");
    }else{
        [_propertyInfoArray addObject:_rawData];

        NSLog(@"Value %@ ",_rawData);
    }
}

}

In my above code in didEndElement: method I am always getting value of self.isNewRow as False (NO)
Why is that ?
What other way I can parse the above XML ?
Or
What is the best way to parse the Group Node ?
Thanks in Advance !

A: I got it solved. I used KissXML and xPath to parse that XML. following is the code in case anybody is facing same issue to parse the xml
DDXMLDocument *doc  =   [[DDXMLDocument alloc] initWithData:data options:0 error:&err];
NSArray *areaSearchNode  =   [doc nodesForXPath:@"/soapenv:Envelope/soapenv:Body/areaSearchResponse/areaSearchReturn/details/" error:&err];

   for(DDXMLDocument *node in areaSearchNode){
    NSArray   *newRoot   =   node.children;

    DDXMLNode *photoURL =   (DDXMLNode*) newRoot[0];

    DDXMLNode *listingID =   (DDXMLNode*) newRoot[1];
    NSString *listingIDstr  =   [listingID stringValue];

    DDXMLNode *priceFrom =   (DDXMLNode*) newRoot[2];
    NSString *price =   [priceFrom stringValue];

    DDXMLNode *latNode =   (DDXMLNode*) newRoot[3];
    NSString *lat   =   [latNode stringValue];

    DDXMLNode *lonNode =   (DDXMLNode*) newRoot[4];
    NSString *lon   =   [lonNode stringValue];

    DDXMLNode *bedroomType =   (DDXMLNode*) newRoot[5];
    NSString *bedroomTypestr    =   [bedroomType stringValue];

    DDXMLNode *bathroomType =   (DDXMLNode*) newRoot[6];
    NSString *bathroomTypestr   =   [bathroomType stringValue];

   // Here adding parsed data into class
    IDSPropertyInfo *propertyInfo    =   [[IDSPropertyInfo alloc]
                                         initWithPhotoURL:[photoURL stringValue]
                                         listingID:[listingIDstr intValue]
                                         priceFrom:[price doubleValue]
                                         lat:[lat doubleValue]
                                         lon:[lon doubleValue]
                                         bedroomTypeID:[bedroomTypestr intValue]
                                         bathroomTypeID:[bathroomTypestr intValue]];
 }

  //Now Add IDSPropertyInfo Class into NSMutableArray.
 [self.propertyInfoArray addObject:propertyInfo];


text:
Q: verify signed response for FB.getLoginStatus Anyone have code to verify the response returned from FB.getLoginStatus?
This is an example response.
{ "session":{
  "uid":"000000000000000",
  "session_key":"0.aaaaaaaaaaaaaaa0.0000.0000000000.0-000000000000000",
  "secret":"aa0a0_aaaaa0_aa0aaaaaa__",
  "expires":0000000000,
  "base_domain":"foo.com",
  "access_token":"000000000000000|0.aaaaaaaaaaaaaaa0.0000.0000000000.0-000000000000000|0aaa0aaaaaa00aaaaaa0aaaa-0a",
  "sig":"00aa0a0000000000a00a00aaa00a00a0"
  },
  "status":"connected",
  "perms":"{"extended":["email","contact_email"],"user":["user_birthday"],"friends":[]}"
}

How do you verify the signature, secret, etc?
I have the FB App Secret, but unsure what needs to be hased (HMACSHA256) to match the sig value?
Thanks for your help.

A: fix, use new oauth param in FB.init() and then verify signed request using example from registration, etc
https://developers.facebook.com/blog/post/525/


text:
Q: Converting string column to dummy variables with duplicate keys I am trying to convert this -
> df.orig <- data.frame(id = c('foo', 'bar', 'foo'), action = c('abc','def','ghi'))
> df.orig
   id action
1 foo    abc
2 bar    def
3 foo    ghi

Into:
> df.new <- data.frame(id = c('foo', 'bar'), action_abc = c(1,0), action_def = c(0,1), action_ghi = c(1,0))
> df.new
   id action_abc action_def action_ghi
1 foo          1          0          1
2 bar          0          1          0

sparse.model.matrix and dcast seem to not handle multiple keys ('foo') very well.
> sparse.model.matrix(id ~ action - 1, df.orig)
3 x 3 sparse Matrix of class "dgCMatrix"
  actionabc actiondef actionghi
1         1         .         .
2         .         1         .
3         .         .         1

A: By using table
  df <- data.frame(id = c('foo', 'bar', 'foo'), action = c('abc','def','ghi'),stringsAsFactors = F)

  table(df$id,df$action)

      abc def ghi
  bar   0   1   0
  foo   1   0   1


text:
Q: how to render xml data in blade view I have a serive in root response xml daha as in image below:
Route::get('feed', function() {
    $feed = App::make("feed");
    $feed->setCache(60, 'feedNewsKey');
    if (!$feed->isCached()) {
        $news = \DB::table('news')->orderBy('created_at', 'desc')->take(20)->get();
        foreach ($news as $post) {
            $feed->add($post->title, 'asd', url('detail/' . $post->id), $post->created_at, $post->description, $post->description,['user_id'=>$post->id, 'photo'=>$post->photo]);
        }
    }
    return $feed->render('atom');
});

I wonder how I can iterate in these xlm data in blade.php view file ?


text:
Q: On heroku app not working code=H10 I am getting this error on Heroku:

2018-07-09T04:37:55.732211+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=newcri.herokuapp.com request_id=b04ee149-4ed1-442f-beb1-4b71c9fd492f fwd="49.34.129.7" dyno= connect= service= status=503 bytes= protocol=https

Project url is https://github.com/ravikkanani/newapi


text:
Q: How can I assign this Python variable to the list I am looping through? Thank you to everyone who has made my first StackOverflow post extremely helpful and fun.
I have been working through this problem all day and have gotten to this point. I have it almost figured out.
Directions:
Your task is to assign the variable names_and_ranks to a list, with each element equal to the city name and it's corresponding rank. For example, the first element would be, "1. Buenos Aires" and the second would be "2. Toronto". Use a for loop and the lists city_indices and city_names to accomplish this. We'll need to perform some nifty string interpolation to format our strings properly. Check out f-string interpolation to see how we can pass values into a string. Remember that list indices start at zero, but we want our names_and_ranks list to start at one!
Here is what I have:
The code city_indices only gives me "11" so I have made it into a list
city_indices = list(range(0, len(cities)))
city_indices

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

city_names

['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

The original code that produced the correct list, but not assigned to the correct variable. The generated list should be assigned to names_and_ranks
city_indices = -1
names_and_ranks = [city_names[city_indices]]
for elements in city_names:
        city_indices += 1
        print(f'{city_indices+1}. {city_names[city_indices]}')
# write a for loop that adds the properly formatted string to the names_and_ranks list

Returns:

1. Buenos Aires
2. Toronto
3. Marakesh
4. Albuquerque
5. Los Cabos
6. Greenville
7. Archipelago Sea
8. Pyeongchang
9. Walla Walla Valley
10. Salina Island
11. Solta
12. Iguazu Falls

This list is correct with the correct numbering. However, it does not seem to correspond to the names_and_ranks variable correctly. In fact, when I run:
names_and_ranks[0]

I get the last item (#12) on my list.... Keep in mind that the list index is 0 - 11, but I am numbering the output 0 - 12.
Any ideas? Once I assign this variable and run a successful loop to show a list of cities starting at 1. I will need to print the different elements in the new list.
ie names_and_ranks[0] should return "1. Buenos Aires"
Current result from running:
names_and_ranks[0] # should return '1. Buenos Aires'

IndexErrorTraceback (most recent call last)
<ipython-input-152-871e7a906308> in <module>
----> 1 names_and_ranks[0] # '1. Buenos Aires'
      2  # '2. Toronto'
      3  # '12. Iguazu Falls'

IndexError: list index out of range

A: How about using enumerate?
You can use index, easily
for example,
for index, value in enumerate(['foo', 'bar', 'baz']):
    print(index, value)

this returns
0 foo
1 bar
2 baz

A: here is using f'strings, this returns same as above:
city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

names_and_ranks = []
for index,city in enumerate(city_names):
        names_and_ranks.append(f'{index+1}. {city}')
print(names_and_ranks)

output:
    ['1. Buenos Aires', '2. Toronto', '3. Marakesh', '4. Albuquerque', '5. Los Cabos', '6. Greenville', '7. Archipelago Sea', '8. Pyeongchang', '9. Walla Walla Valley', '10. Salina Island', '11. Solta', '12. Iguazu Falls']
EDIT: as the questioner wants names_and_ranks[8] returning '8. Pyeongchang' this is the edit:
city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

names_and_ranks = [0]
city_indices = 1
for city in city_names:
        names_and_ranks.insert(city_indices,f'{city_indices}. {city}')
        city_indices+=1

print(names_and_ranks[8])

A: Here's one way to do:
names_and_ranks = [f'{i}. {x}' for i,x in enumerate(l, 1)]

print(names_and_ranks[0])
1. Buenos Aires

A: your entire code is correct except for the first line:
city_indices = -1

which (is an index, i guess) should start from 0 and NOT from -1.
Reason,
in Python, -1 points to last element of list/string/.. and -2 as second last element and so on.
so, I recommend you should change only:
    city_indices = 0
and then change the further code based on this line.
city_indices = 0
names_and_ranks = [city_names[city_indices]]
for elements in city_names:
    print(f'{city_indices+1}. {city_names[city_indices]}')
    city_indices += 1

A: I moved on after realizing I probably was spending way too much time on something relatively simple. I found the solutions manual. Here is the correct answer. I hope this might help someone else working on the Learn.co Flatiron School Data Science Pre-Work...
names_and_ranks = []
for elements in city_indices:
        names_and_ranks.append(f"{elements + 1}. {city_names[elements]}")

names_and_ranks


text:
Q: How to put drawable in the middle of textView on android java I can't find information on how to draw image in the middle of texview using drawable. Below Images on how the app looks like atht he moment

When the knight should be in the middle of box (textView). I have created my textviews dynamicly with loops so accessing XML file is not possible. I am using
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(ic_horsey, 0, 0, 0 ) to draw the image.

A: TextView are not used to display Drawables. You have to use an ImageView for that.
Regarding your screenshot, a LinearLayout containing a TextView for the letter and an ImageView for the chess piece will do the job to represent a chess cell


text:
Q: Jquery Sortable, delete current Item by drag out My Problem:
The sortable event out: fires when I drag something in the list or when I sort the list.
But I only want to start the function when I drag an item out.
My code
        $(document).ready(function ust()
        {
            $('#div1').sortable({
                out: function(event, ui) { $('#nfo').append('OUT<br />'); }
            });

        });

Working example
http://jsfiddle.net/FrbW8/22/

A: This is the default behaviour of the out callback. See this jquery ui trac ticket
I really do not agree with the 'logical' behaviour notion.

"However, note that the "out" callback
  will still be triggered if you drag
  into a list and then release the mouse
  (but not if you're not over the list).
  This is logical behaviour and happens
  for normal sortables as well."

A: The other solutions doesn't seems to work with connected sortable lists so I'm posting my own solution that works perfectly for my case. This makes use of the "droppable" plugin capturing the "drop" event when the elements are dropped outside of the sortable lists.
$('#div1').sortable({
    ....
}).droppable({greedy: true})

$('body').droppable({
    drop: function ( event, ui ) {
        ui.draggable.remove();
    }
});

Here is a jsfiddle of this approach in action: http://jsfiddle.net/n3pjL/

A: Use beforeStop to intercept the item and remove it:
receive: function(e, ui) { sortableIn = 1; },
over: function(e, ui) { sortableIn = 1; },
out: function(e, ui) { sortableIn = 0; },
beforeStop: function(e, ui) {
   if (sortableIn == 0) {
      ui.item.remove();
   }
}

(I originally found this in the Google, but can no longer find the link. So, I apologize for not referencing the source.)

A: I use this.element.find('.ui-sortable-helper').length to make difference between "sort out event" and "drop out event". When you are sorting, sorted item has class ui-sortable-helper. After drop there is no other ui-sortable-class until you start sorting again (at least in my script). Hope to help someone.


text:
Q: redirect all pages from specific folder to new domain I have some files placed under a particular folder in my old domain like this: http://www.olddomain.com/oldfolder/. I want to redirect all requests that try to access files under this folder to a new domain. Example: http://www.olddomain.com/oldfolder/page.html => http://www.newdomain.com/page.html I tried from this but it's not redirecting me to new domain. what would I do to troubleshoot this ?

A: Try :
RedirectMatch 301 ^/oldfolder/(.+)$ http://newdomain.com/$1

Or
Redirect 301 /oldfolder/ http://newdomain.com/