text:
Q: onLocationChanged has not been called i've been trying to create a map-related android app, but i realized that the onLocationChanged of my app had not been called, therefore the map always stay at the default area (US).
my code:
public class MapMainActivity extends MapActivity
implements OnClickListener, LocationListener {

MapView mapView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_main);

    //reference
    mapView = (MapView)findViewById(R.id.map_view);
    mapView.setBuiltInZoomControls(true);
    this.findViewById(R.id.btn_satellite).setOnClickListener(this);
    this.findViewById(R.id.btn_street).setOnClickListener(this);

}//onCreate

@Override
protected void onResume() {
    super.onResume();

    Toast.makeText(this, "GPS tracking started",
        Toast.LENGTH_SHORT).show();

 // Start location updates; 5s/5m
    LocationManager locManager = (LocationManager)getSystemService(
        Context.LOCATION_SERVICE);
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
        5000, 0, this);

    Criteria crit = new Criteria();
    crit.setAccuracy(Criteria.ACCURACY_FINE);
    String provider = locManager.getBestProvider(crit, true);
    Location loc = locManager.getLastKnownLocation(provider);

}//onResume

@Override
protected void onPause() {
    super.onPause();

    Toast.makeText(this, "GPS tracking stopped",
        Toast.LENGTH_SHORT).show();

    LocationManager locManager = (LocationManager)getSystemService(
            Context.LOCATION_SERVICE);
        locManager.removeUpdates(this);
}//onPause

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v == findViewById(R.id.btn_street))
    {
        mapView.setSatellite(false);
    }//street view

    else if (v == findViewById(R.id.btn_satellite))
    {
        mapView.setSatellite(true);
    }
}//onClick

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}//isRouteDisplayed

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    double lat = location.getLatitude();
    double lon = location.getLongitude();

    TextView txtLat = (TextView)findViewById(R.id.txt_lat);
    txtLat.setText(String.format("%.6f", lat));
    TextView txtLon = (TextView)findViewById(R.id.txt_lon);
    txtLon.setText(String.format("%.6f", lon));

    MapView map = (MapView)findViewById(R.id.map_view);
    map.getController().animateTo(new GeoPoint((int)(lat*1E6),//1000000),
        (int)(lon*1E6)));
}//onLocationChanged

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "GPS disabled",
            Toast.LENGTH_SHORT).show();
}//onProviderDisabled

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "GPS enabled",
            Toast.LENGTH_SHORT).show();
}//onProviderEnabled

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}//onStatusChanged

}//class

the whole of my log cat when i run the app through my device (16/12/2011)
D/InputTransport(5357): Input channel constructed: name='40baf680 Toast (client)', ashmemFd=54, receivePipeFd=57, sendPipeFd=58

I/MapActivity(5357): Handling network change notification:CONNECTED

E/MapActivity(5357): Couldn't get connection factory client

I/ViewRoot(5357): !@FINISH DRAWING : sg.edu.tp/sg.edu.tp.SIP_TestMapActivity

I/ViewRoot(5357): !@finishDrawing is completed : sg.edu.tp/sg.edu.tp.SIP_TestMapActivity

I/ViewRoot(5357): !@FINISH DRAWING : Toast

I/ViewRoot(5357): !@finishDrawing is completed : Toast

D/InputTransport(5357): Input channel destroyed: name='40baf680 Toast (client)', ashmemFd=54, receivePipeFd=57, sendPipeFd=58

manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sg.edu.tp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SIP_MLT_TestActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <uses-library android:name="com.google.android.maps" />
        <activity android:name=".SIP_TestMapActivity"></activity>
        <activity android:name=".SIP_TestDraw1Activity"></activity>
        <activity android:name=".SIP_TestDraw2Activity"></activity>
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

</manifest>

A: Are you testing that while moving about or while sitting tethered to your dev machine with USB and watching logcat?
If sitting at dev machine, I suspect you're not able to move the 5 meters required to trigger a location change event as you requested in your call to requestLocationUpdates
From API docs: .

If minDistance is greater than 0, a location will only be broadcast if
  the device moves by minDistance meters.

try reducing the min distance param in that call to zero and see what happens.
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000, 0, this);

You probably dont want to leave that at zero for anything other than testing.
If that doesnt help you might try to see that your GPS is working at all by doing something like this in your onResume, after you ask for locationUpdates:
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, true);
Location loc = lm.getLastKnownLocation(provider);

and see if you are getting good location info.

A: Location stuiff is tricky.  On one side, you need recent location fast, with best precision possible on  the other side you do no like to  drain battery fast.  There are also differences between API levels.  See this manual for detailed explanation:
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
As for your original question - requersting location updates ist just a recomendation  to location manager to send you those updates after something changes. It's no obliged to do
so.   Your GPS system may be not fine enough (and is certainly not)  to detect snall location changes while leashed on USB cable.  For testing purposes, you could create mock provider
and manipulate it with outher application.
http://developer.android.com/reference/android/location/LocationManager.html#addTestProvider%28java.lang.String,%20boolean,%20boolean,%20boolean,%20boolean,%20boolean,%20boolean,%20boolean,%20int,%20int%29


text:
Q: SQLite3 shell not updating values I'm in the sqlite3 shell, and I'm trying to see why my update isn't recording. In python I'm calling it like:
db.execute("UPDATE total SET amount = amount + ?", [DONATION])
db.commit()

And in the shell like:
sqlite> .schema total
CREATE TABLE total(
    amount REAL);
sqlite> select * from total;
sqlite> update total set amount = 0.002;
sqlite> select * from total;
sqlite>

Both cases the value is never getting updated.
Any help is appreciated!

A: You need to insert first:
sqlite> insert into total values (0.0);

Now you can do:
sqlite> update total set amount = 0.002;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solving a modular equation with a large modulus I am having trouble solving this equation:
$17^n\equiv 1 \mod 640826899755722841329632946651705039010285107743541637238400825304943424424715705661705191669759$
for the smallest integer $n > 0$
I tried Wolfram|Alpha, but it did not help me. I realize that it would be easy to solve this equation if we knew the prime factors of the modulus. Could you help me to find a solution for this equation?

A: This is what MultiplicativeOrder[] should be used for. As my computer is a bit on the weak side, I'll use a smaller example:
MultiplicativeOrder[17, 640826899755722841]
  476643402271080

Check:
PowerMod[17, %, 640826899755722841]
   1


text:
Q: How to disable/enable a VisualState based on some condition? (Metro) I defined a VisualState for a button in a controltemplate:
  <ControlTemplate x:Key="ButtonTemplate" TargetType="Button">
      ...
      <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
          ...
          <VisualState x:Name="PointerOver">
            <Storyboard>
              <DoubleAnimation Storyboard.TargetName="c1" Storyboard.TargetProperty="Opacity" To="0.7"/>
            </Storyboard>
          </VisualState>
          ...
        </VisualStateGroup>
      </VisualStateManager.VisualStateGroups>
      ...
  </ControlTemplate>

But this effect (change opacity when mouseover) should be enabled/disabled based on a viewmodel condition, so how do I do that with XAML?
I tried creating a binding for the To value of the DoubleAnimation, it doesn't work because Storyboard is freezed. I'm also thinking sth like a template selector, but there is no such thing for the VisualState Manager.

A: I was discussing it recently with someone and I might add a generic solution to the problem to the WinRT XAML Toolkit, which would work similar to DataTriggers from WPF, but for now I would just add a DependencyProperty to your control, bind the property to your view model and on value change - update the visual state.


text:
Q: Program isn't calculating factors correctly and inputting into array I'm having issues with the testPerfect method. I need it to calculate the factors and put them into the array, then return a boolean value of true or false if the number is perfect or not. As of now the array is just getting 1,2,3...5,6,7...to whatever number was input to check.  Any suggestions?
import java.util.Arrays;
import java.util.Scanner;

public class moo_Perfect
{
public static void main ( String args [] )
{
    int gN;
    int gP = getPerfect();
    int [] array = new int[100];
    boolean tP = testPerfect(gP, array);
    //int printFactors;
    System.out.println(Arrays.toString(array));
}

public static int getNum() //Get amount of numbers to check
{
Scanner input = new Scanner ( System.in );
System.out.print( "How many numbers would you like to test? " );
int count = input.nextInt();
int perfect = 1;
boolean vN = validateNum(count, perfect);
while(!vN)
{
    System.out.print (" How many numbers would you like to test? ");
    count = input.nextInt();
    vN = validateNum(count, perfect);
}
return count;
}

public static boolean validateNum( int count, int perfect  ) //Check if number is valid
{
if (( count <= 0) || ( perfect <= 0))

{
    System.out.print( "Non-positive numbers are not allowed.\n");
}

else
{
    return true;
}
return false;

}
public static int getPerfect() //Gets the numbers to test
{
Scanner input = new Scanner ( System.in );
int perfect = -1;
int count = getNum();
System.out.print("Please enter a perfect number: " );
perfect = input.nextInt();
boolean vN = validateNum(perfect, count);
while (!vN)
{
    System.out.print("Please enter a perfect number: ");
    perfect = input.nextInt();
    vN=validateNum(perfect, count);
}
return perfect;
}

public static boolean testPerfect( int perfect, int[] array )

{
//testPerfect(perfect, array);
int limit = perfect;
int index = 0;
for ( int i = 1; i <=limit; i++)
{
    array[index++] = i;
    perfect /= i;
}
array[index] = perfect;
int sum = 0;
for ( int i =0; i < array.length; i++)
{
    sum = sum + array[i];
}

if ( sum == perfect)
{
    int[] w = array;

    return true;
}

else
{
    return false;
}

}

A: This is a job for a List, not an array (because you don't know how long the array should be before hand, Lists take care of this). After you instantiate a list of integers (say, factors), you can change the body of your first for-loop to
if (perfect % i == 0) factors.add(i)

i.e. "add i to our list of factors only if it divides evenly into perfect".

EDIT: If you have to use an array, you could do this
array[i] = (perfect % i == 0) ? i : 0

This will place i in your array only if it divides perfect, otherwise it will place 0. Therefore, the sum of the elements in this array will equal the sum of the factors of perfect.


text:
Q: Given $X$ a normal topological space $J \subset X,$ $J \simeq D ^2$. Prove that $J$ is a retract of $X$. Given $X$ a normal topological space $J \subset X,$ $J \simeq D ^2$. Prove that $J$ is a retract of $X$.
Not really sure how to approach this one. I guess I have to somehow use Urysohn's lemma, but I'm not sure exactly how. Any advice would be welcome.

A: It's easier to use $[0,1]^2$, as it's homeomorphic to $D^2$, say via a homeorphism $h: D^2 \rightarrow [0,1]^2$. If $j$ is the homeomorphism from $J$ to $D^2$, then $h \circ j$ is a map from $J$ (which is a closed subspace of the normal space $X$) onto $[0,1]^2$. Call the two projections onto the factors $[0,1]$ of this map $h_1$ and $h_2$. Extend these maps $h_1$ and $h_2$ to $X$ (call the extensions $\overline{h_1}$ and $\overline{h}_2$, say) by Tietze's extension theorem.
Then $j^{-1} \circ h^{-1} \circ (\overline{h_1} \times \overline{h_2})$ is the required retraction.


text:
Q: Redis Timeseries purge data by label I want to cache timeseries data stored in mysql.
For cache stategy I use next logic: split all data to a blocks by one hour, then when user request data I try to range from it from redis, then for all blocks that do not contain in result load a block from mysql db and push it to redis timeseries, if no data exist by this block - push single empty value at the end of block.
Problem: My algorithm implies that if at least one value selected for block therefore all block were chached. The problem occurs when redis reached memory limit and purge data.
Question: Can I specify purge strategy that guarantee if one value of block were purged then all data from block were purged?
I didn't find any solution.


text:
Q: Unable to update UILabel using dispatch_async method in swift iOS I am setting json string value to UILabel using dispatch_async method. But Its unable to show updated value , but when I am printing label text, its showing updated value. here is my code-
 override func viewDidLoad() {
     super.viewDidLoad()
     get_detail_postmethod(url, params: params)
}

 func get_detail_postmethod(url: String, params: String) {
    let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    request.HTTPMethod = "POST"
    let postString = params
    print("param=\(params)")
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")

        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
            print(json)
           if let success = json["success"] as? Int
            {
            if((success) == 1){

             self.extract_json(data!)

            }
            else{

            }
            }

        }catch {
            print("Error with Json: \(error)")
        }
    }
    task.resume()
}

and below code for extract json data and set String value to UILabel-
func extract_json(jsonData:NSData)
{
    let json: AnyObject?
    do {
        json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
        print("full data \(json!)")
    } catch {
        json = nil
        return
    }
    let user_object = json!["opportunity_master"] as! NSArray
    let data_block = user_object[0] as? NSDictionary
    self.opp_title = (data_block!["opportunity_title"] as? String)!
    self.event_sdate = (data_block!["event_start_date"] as? String)!

    dispatch_async(dispatch_get_main_queue(), {
        print(self.opp_title)
        self.Event_title.text? = self.opp_title
        self.Txt_event_date.text = self.event_sdate
        self.Event_title.setNeedsDisplay()

        print("event title label \(self.Event_title.text)")

    })

}

I am not able to update values. Please suggest is there any other way to implement update UiLabel text.

A: This is solved by calling Viewcontroller like this-
let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let Opprt_Controller = storyboard.instantiateViewControllerWithIdentifier("Opprtunity_Event") as! Opportunity_Event

    self.navigationController!.pushViewController(Opprt_Controller, animated: true)

A: Try the below code to update your Label :
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
        print(self.opp_title)
        self.Event_title.text? = self.opp_title
        self.Txt_event_date.text = self.event_sdate
        self.Event_title.setNeedsDisplay()
        print("event title label \(self.Event_title.text)")

})

A: call get_detail_postmethod(url, params: params) method in viewDidAppear instead of viewDidLoad.

A: There is a syntax error in your dispatch_async method. Update code block with following.
dispatch_async(dispatch_get_main_queue()) {
    print(self.opp_title)
    self.Event_title.text? = self.opp_title
    self.Txt_event_date.text = self.event_sdate
    self.Event_title.setNeedsDisplay()

    print("event title label \(self.Event_title.text)")
}


text:
Q: How to delete a Cell from Collection View? I want to delete cell from UICollectionview,when user touchUpInside(Button) to  remove cell.
Here is my code:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell

    cell.myLabel.text = self.items[indexPath.row]

    cell.deleteBtn?.layer.setValue(indexPath.row, forKey: "Cdelete")
    cell.deleteBtn?.addTarget(self, action: Selector(("deleteColor:")), for: UIControlEvents.touchUpInside)

    cell.backgroundColor = UIColor.cyan // make cell more visible in our example project

    return cell
}

func deleteColor(sender:UIButton) {

    let i : Int = (sender.layer.value(forKey: "Cdelete")) as! Int
    self.items.remove(at: i)
    collectionView.reloadData()
}

Where i am doing wrong?

A: set tag for your deletebutton for fetch the current cell/ know the which cell you tapped
cell.deleteBtn?.tag = indexPath.row
cell.deleteBtn?.addTarget(self, action: #selector(yourVCName. deleteColor(_:)), for: .touchUpInside)

and call like
@IBAction func deleteColor(_ sender: UIButton){
   print("Button pressed  ")
  // continue your work

           var hitPoint = sender.convert(CGPoint.zero, to: yourCollectionViewName)
   var hitIndex: IndexPath? = yourCollectionViewName.indexPathForRow(at: hitPoint)

        self.items.remove(at: hitIndex.row)
          self.yourCollectionViewName.performBatchUpdates({
    self.yourCollectionViewName.deleteItems(at: [hitIndex])
}) { (finished) in
    self.yourCollectionViewName.reloadItems(at: self.yourCollectionViewName.indexPathsForVisibleItems)
}

 }


text:
Q: Has anyone studied this operator? I've been studying a particular unary operator on the commutative ring $\mathbb{Z}/n\mathbb{Z}$. The operator is:
$\downarrow(x) = y\pmod{n}$ iff $n \equiv y \pmod{x}$, where $0< x,y \le n$.
The operator isn't distributive on addition or multiplication, so its use is probably fairly limited. I've proven a couple fairly trivial results, but I'm interested in seeing if there are more resources available.
One of the fairly trivial results:
If $n$ is composite and $n=pq$ and WLOG $p \le q$, then if $q\ge kp+k$ I can show that
$(\downarrow(q-k))\mid p$.

A: This is not really an operator on $\mathbb{Z}/n\mathbb{Z}$, it's an operator on the numbers $\{1,2,\ldots, n\}$.  The reason is that if $x\equiv x'\pmod{n}$, we would expect any such operator to satisfy $\downarrow (x)=\downarrow(x')$, but this one doesn't.

A: Yes. If the modulus is prime $\, n = p,\,$ then iterating the map $\ x\mapsto p\ {\rm mod}\ x\ $ yields Gauss's algorithm for computing inverses mod $\,p.\,$ By this variant of the Euclidean algorithm, Gauss deduced the prime divisor property, i.e.  if a prime divides a product then it divides some factor, which immediately yields uniqueness of prime factorizations (fundamental theorem of arithmetic).


text:
Q: MVC ignores DataType on overriden model property when DisplayFor is used I'm wondering if anyone can confirm this behavior or if I've done something wrong.
Normally when you specify the DataType(DataType.MultilineText) attribute, and do something like @Html.DisplayFor(m => m.Body) MVC will use the MultilineText.cshtml in the DisplayTemplates folder. That does not seem to work when the DataType attribute is applied to an overriden property as in the code below. Now if I move the attribute to the property in the abstract class it MVC does use the MultilineText.cshtml display template.
public abstract class PostBase
{
    [Required]
    public virtual string Body { get; set; }
}

public class MessagePost : PostBase
{
    [StringLength(500), DataType(DataType.MultilineText)]
    public override string Body
    {
        get { return base.Body; }
        set { base.Body = value; }
    }
}

A: What's the Model in declared in your view? The abstract or child?
It uses reflection to read the attribute based on the model declared so:
@model PostBase

@Html.DisplayFor(m => m.Body)

Will work differently to
@model MessagePost

@Html.DisplayFor(m => m.Body)

the first of these will apply the [Required] only. It's bound to a PostBase model (doesn't know or care what the child class), so when it reflects the PostBase class; this only has [Required] on that property. So it never looks for the MultilineText.cshtml, why would it? It's not got MultilineText on it.
The second one will apply [StringLength(500), DataType(DataType.MultilineText)] and [Required]. The attributes are combined for inherited classes so when it reflects the class it'll see both attributes.
This view should use the template as required. I'm guessing this doesn't work for you though as I'm presuming the inheritance is there for a reason?


text:
Q: Refactoring block of jQuery code? I have a section of jQuery code that I am having to repeat over and over with only a small change accompanying each iteration. Here is an example of what I have:
  if($('.smm').hasClass('vendor-icon-active')) {
      total = total + 1200;
  } else {
    total = total;
  }

  if($('.repman').hasClass('vendor-icon-active')) {
      total = total + 495;
  } else {
    total = total;
  }

  if($('.blog-management').hasClass('vendor-icon-active')) {
      total = total + 395;
  } else {
    total = total;
  }

  if($('.press-release').hasClass('vendor-icon-active')) {
      total = total + 195;
  } else {
    total = total;
  }

In my code, I have about 30 of those sections. Is there a way I could simplify that process and clean up my code?

A: You can use a common class to group the elements, and a data-* attribute to hold the value associated with them. Try this:

var total = 0;
$('.item').each(function(i, el) {
  var $item = $(el);
  if ($item.hasClass('vendor-icon-active')) {
    total += +$item.data('value');
  }
});
console.log(total);

Foo

Foo

Foo

Foo

A: This should do the trick...
function updateTotal(className, value) {
    if ($('.' + className).hasClass('vendor-icon-active')) {
        total += value;
    }
}

updateTotal("ssm", 1200);
updateTotal("repman", 495);
updateTotal("blog-management", 395);
updateTotal("press-release", 195);

I just moved the main functionality into that one function.  You can add as many function calls as you need afterwards :)


text:
Q: Comparing data in MongoDB
I need to generate the daily percentage sales for each of the 700 products based on their daily sales for the last 9 years.
Here is an example of what my node script should generate:
Shoes1 | +5% | -1% | +10% | +5% | -1% | +10% |... (and so one for 3000 days)
...
Shoes200 | +5% | -1% | +10% | +5% | -1% | +10% |... (and so one for 3000 days)

I have 2 structures in mind, but I'm not sure which one would work better since I have around 3000 days of daily sales for about 700 product to record.
Here is the first one.
Product

    {
        product_title: name1;
        sales:[{sales_number1:date}]
       /* sales: [{45:010104}, {23:050214},..., {243:050614},.....]*/
    }

Here is the second one

Date

    {
        Day: 050114;
        sales:[{product name: sales_number1}]
        /* sales: [{shoes1: 45}, {shoes2:5},..., {shoes1000:14}]*/
    }

Any advice would very welcome.
Thanks.

A: Going by your output that you want(showing percentage change for a particular shoe in comparison to previous day),the first approach would be better
Product

    {
        product_title: name1;
        sales:[{sales_number1:date}]
       /* sales: [{45:010104}, {23:050214},..., {243:050614},.....]*/
    }

because in that case you would be querying over the array of the same document and then calculating the percentages.If you go by the second approach then you would need to pick an element corresponding to different shoes from different documents' arrays and then calculate percentage that would create more complex query.


text:
Q: is there a PEAR::DB equivilent of FROM_UNIXTIME() I'm working on a way to extract given data from a timestamp in a MySQL. I've been advised to try FROM_UNIXTIME() ... but my development is built around pear::db so I'm looking for a replacement. Have you any suggestions

A: Do you mean a PHP-based solution instead of using SQL? Just use the date() function to format your timestamp:
date("Y-m-d H:i:s", $timestamp);

Specific answer  (see comments): to get just the month from this, just change the format string to "m" and leave out everything else.


text:
Q: Leer Parte del XML y algunos hijos con repeticiones LINQ buenas tardes, tengo el siguiente XML
<Detalle>
                    <Item>
                        <NroLinDet>1</NroLinDet>
                        <CodItem>
                            <TpoCod>2</TpoCod>
                            <Cod>45136</Cod>
                        </CodItem>
                        <IndFact>3</IndFact>
                        <IndAgenteResp />
                        <NomItem>PEKITAS TOALLAS HUMEDAS 70</NomItem>
                        <DscItem>CONT:437148|DTO-FIN:4%|</DscItem>
                        <Cantidad>10</Cantidad>
                        <UniMed>UNI</UniMed>
                        <PrecioUnitario>58.00</PrecioUnitario>
                        <DescuentoPct>0</DescuentoPct>
                        <DescuentoMonto>23.20</DescuentoMonto>
                        <SubDescuento>
                            <DescTipo>2</DescTipo>
                            <DescVal>4.00</DescVal>
                        </SubDescuento>
                        <RecargoPct>0</RecargoPct>
                        <RecargoMnt>0</RecargoMnt>
                        <MontoItem>556.80</MontoItem>
                    </Item>
                    <Item>
                        <NroLinDet>2</NroLinDet>
                        <CodItem>
                            <TpoCod>3</TpoCod>
                            <Cod>45678</Cod>
                            <TpoCod>2</TpoCod>
                            <Cod>45136</Cod>
                        </CodItem>
                        <IndFact>6</IndFact>
                        <IndAgenteResp />
                        <NomItem>PEKITAS TOALLAS HUMEDAS 70</NomItem>
                        <DscItem>CONT:508195|DTO-COM:100%|DTO-FIN:4%|REF/OFE:60 u|</DscItem>
                        <Cantidad>10</Cantidad>
                        <UniMed>UNI</UniMed>
                        <PrecioUnitario>58.00</PrecioUnitario>
                        <DescuentoPct>0</DescuentoPct>
                        <DescuentoMonto>580.00</DescuentoMonto>
                        <SubDescuento>
                            <DescTipo>2</DescTipo>
                            <DescVal>4.00</DescVal>
                        </SubDescuento>
                        <SubDescuento>
                            <DescTipo>2</DescTipo>
                            <DescVal>100.00</DescVal>
                        </SubDescuento>
                        <RecargoPct>0</RecargoPct>
                        <RecargoMnt>0</RecargoMnt>
                        <MontoItem>0.00</MontoItem>
                    </Item>
                </Detalle>

Necesito sacar algunos elementos y el  que se encuentra dentro de Coditem del cual pueden haber hasta 5 apariciones. No estoy pudiendo sacar ese elemento. Debajo el código que estoy haciendo con linq pero no se como sacar en el mismo objeto las apariciones de cod. Me podrán ayuda? mil gracias
var elemento = from el in eDetalle.Descendants("Item")
                       select new
                       {
                           NroLinDet = el.Element("NroLinDet").Value,
                           NomItem = el.Element("NomItem").Value,
                           DscItem = el.Element("DscItem").Value,
                           PrecioUnitario = el.Element("PrecioUnitario").Value,
                           Cantidad = el.Element("Cantidad").Value,
                           DescuentoMonto= el.Element("DescuentoMonto").Value,
                           DescuentoPct = el.Element("DescuentoPct").Value,
                           DescVal = el.Element("DescVal").Value,
                           MontoItem = el.Element("MontoItem").Value,
                           ACA TENDRIA QUE SACAR EL VALOR DE TODAS LAS APARICIONES DE Cod DENTRO DE CodItem
                       };

Muchas gracias por su ayuda

A: El xml no es valido en el nodo CodItem, si vas a tener repeticiones deberia ser
<CodItems>
    <CodItem>
        <TpoCod>3</TpoCod>
        <Cod>45678</Cod>
    </CodItem>
    <CodItem>
        <TpoCod>2</TpoCod>
        <Cod>45136</Cod>
    </CodItem>
</CodItems>

necesitas reflejar una coleccion
Entonces en el linq usarias
CodItems = el.Descendants("CodItem").Select(x= >new {
                                      Tipo = x.TpoCod,
                                      Cod = x.Cod
                                     }),

sobre la seleccion aplicas una nueva para crear cada item que representa el item de codigo


text:
Q: Issue Displaying Updated Webpage I am using Adobe Dreamweaver to Web Develop. I have uploaded the files via ftp to the web server, also went on the web sever to confirm the files are uploading. When going to view webpage in all browsers, the changes aren't there. What could possibly be wrong? I know it's not uploading the files the files are updating and uploading on the web server.

A: I found the solution! The issue was the aName under the Domain settings. It works perfect now.


text:
Q: img src not locating image path I'm fairly new to web dev/Flask so sorry if my question is basic.
I have an image called logo2.png and somehow the HTML isn't finding it. I even put the image everywhere I thought the code would look but it still returns a 404 error.
My code to find the image is:

Pando WR NFL Stat Form

Enter the stats for a wide receiver to see how much they're worth

The file directory looks like: directory image. routes.py creates an end point that renders index.html. The above code is inside index.html. I tried putting the specified image inside the static directory, templates directory, same directory as routes.py and even the parent directory with microblog.py which Flask uses to run the project. I've even tried an absolute path to no avail

A: Looking at your file structure your image is named pandoLogo2.png, noting that src is case sensitive.
It's also recommended to use the static url_for function to get the url for the image src, in case the static folder for your project is moved:
... src="{{ url_for('static', filename='pandalogo2.png') }}" ...


text:
Q: Conditions in SUM function I have a User entity with one-to-many relationship with Certificate entity (one user might have multiple certificates).
A Certificate has a startDate and endDate which determine their period of validity. I need filter all the users, that have expired certificates and have no active certificates.
An active certificate - c.startDate <= :today AND c.endDate > :today
An expired certificate - c.endDate <= :today.
I now how to do it in plain SQL:
SELECT
  u.user_id
FROM `User` u JOIN `Certificate` c ON c.user_id = u.user_id
GROUP BY u.user_id
HAVING SUM(c.end_date > :today) = 0

Now I'm trying to port the SQL query to Doctrine QueryBuilder syntax:
$qb = $this->createQueryBuilder();
$qb
    ->from('SomeNS:User', 'u')
    ->select('u')
    ->join('u.certificates', 'c')
    ->groupBy('u.id')
    ->having('SUM(c.endDate > :today) = 0')
    ->setParameter('today', $today);

But an error occurs:

Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '<'

It looks like the conditions in the SUM function aren't understood by Doctrine.
Please help to figure out how one can use conditions in SUM function or point me out what I do wrong.

A: Here is a concrete answer using the expr() method of queryBuilder:
---
->having(
  $qb->expr()->andx( // this is the "AND" in between the sums
    $qb->expr()->lte( // this is the "<="
      ...(your SUM here, after you fix the logic),
      0
    ),
    $qb->expr()->eq( // this is the "="
      ...(your SUM here, after you fix the logic),
      0
    )
  )
)

Once you get those "SUM" conditions right, you put them in the placeholders and it should work.


text:
Q: R - Creating Variables With For-Loop [this question is edited]
I want to simplify my question - I hope that will lead to understanding enough to answer the more complex one myself.
How can I create the variables a:i in R with a for-loop?
for(i in a:i) { "create variable [i]"

}

Thank you very much for your help!

A: You can use assign
for(I in 1:6) {
      assign(letters[I], 1)
}

Output
 list(a,b,c,d,e,f)
[[1]]
[1] 1

[[2]]
[1] 1

[[3]]
[1] 1

[[4]]
[1] 1

[[5]]
[1] 1

[[6]]
[1] 1


text:
Q: Is there any way to plot several categorical Y variables in the same graph that has the same categorical X variable? In my dataset, the x-variable is a categorical variable called "Agency" which has 3 variables. I am trying to plot multiple Y variables called "Limitation 1, Limitation 2,...Limitation7" to make a single graph that contains all the y variables and the x variable at the bottom. Below is the sample code I used to get the individual bar graphs, but is there a code that enables me to merge the results from all the 7 categorical Y variables into one layout?
This is currently the code I am using to get individual bar graphs and I did this for all the limitations
counts7 <- table(dataset$Limitation1, dataset$Agency)

barplot(counts7,main="Limitation1 and Agency",
    xlab="HTA Agency", col=c("darkgrey","black")
    legend = rownames(counts), beside=TRUE)

A: It would help to have your data, and maybe a more detailed explanation of what you want, but here is a go using a slightly modified version of the inbuilt airquality data set. Using melt() from reshape2 to convert from wide to long representation (makes tabulation much easier), and barchart() from lattice to make the multi-way plot.
library(lattice)
library(reshape2)

airq <- airquality[, -6]
airq[,1:4] <- lapply(airq[,1:4],
  function(x) cut(x, quantile(x, na.rm=TRUE), labels=1:4))

airq.tab <- table(melt(airq, id.vars="Month"))

barchart(airq.tab, stack=FALSE, layout=c(1, 4), horizontal=FALSE, xlab="Month")


text:
Q: Hibernate does not create proxy within @DataJpaTest I have a very simple test that tests the spring data repository that works ok in normal runtime. I really don't think it should be this difficult to do this, but I do not understand what I am doing wrong, please help.
When I try to test this repository I start receiving errors that say something like:

Caused by: org.hibernate.HibernateException: Generation of
HibernateProxy instances at runtime is not allowed when the configured
BytecodeProvider is 'none'; your model requires a more advanced
BytecodeProvider to be enabled.   at
org.hibernate.bytecode.internal.none.DisallowedProxyFactory.getProxy(DisallowedProxyFactory.java:37)
at
org.hibernate.tuple.entity.AbstractEntityTuplizer.createProxy(AbstractEntityTuplizer.java:746)
at
org.hibernate.persister.entity.AbstractEntityPersister.createProxy(AbstractEntityPersister.java:5049)

It appears that hibernate can not create a proxy for entity classes, because it for some reason has been assigned a DisallowedProxyFactory implementation for proxy factory. So I added this configs:

spring.jpa.properties.hibernate.enhancer.enableDirtyTracking=true
spring.jpa.properties.hibernate.enhancer.enableLazyInitialization=true

But now I simply receive this error instead:

Caused by: java.lang.IllegalStateException: Cannot apply class
transformer without LoadTimeWeaver specified  at
org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.addTransformer(SpringPersistenceUnitInfo.java:83)

So I added @EnableLoadTimeWeaving to the test class, and now I receive this error

Caused by: java.lang.IllegalStateException: ClassLoader
[jdk.internal.loader.ClassLoaders$AppClassLoader] does NOT provide an
'addTransformer(ClassFileTransformer)' method. Specify a custom
LoadTimeWeaver or start your Java virtual machine with Spring's agent:
-javaagent:spring-instrument-{version}.jar

The initial test set up:
@DataJpaTest
@Transactional
@Import({RdsPersistenceConfigration.class})
class DivisionRepositoryTest {

    @Autowired
    private DivisionRepository repository;

    @Test
    @Sql(scripts = "classpath:sql/division-repository-test.sql")
    void crudOperations() {
        // test case logic
    }
}

Division entity:
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "division")
public class Division {

    private transient static final int HASH_CODE = Division.class.hashCode();

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "division_name", nullable = false)
    private String divisionName;

    @OneToMany(mappedBy = "division", fetch = FetchType.LAZY)
    private Set<Branch> branches = new HashSet<>();

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tenant_id", nullable = false)
    private Tenant tenant;

    public void setTenant(Tenant tenant) {
        if (tenant != null) {
            this.tenant = tenant;
            tenant.addDivision(this);
        } else {
            if (this.tenant != null) this.tenant.removeDivision(this);
            this.tenant = tenant;
        }
    }

    @Transient
    public void addBranch(Branch branch) {
        if (branch != null) {
            if (branch.getDivision() != this) {
                branch.getDivision().removeBranch(branch);
            }
            branches.add(branch);
        }
    }

    @Transient
    public void removeBranch(Branch branch) {
        if (branch != null) {
            branches.remove(branch);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Division division = (Division) o;
        return Objects.equals(id, division.id);
    }

    @Override
    public int hashCode() {
        return Division.HASH_CODE;
    }

}

Repository:
public interface DivisionRepository extends JpaRepository<Division, Integer> {

    Page<Division> findAll(Pageable pageable);

}

Rds Persistence config class
@Configuration
@PropertySource("classpath:application-liquibase.properties")
@EntityScan("com.nflp.processingapplication.main.modules.persistence.sql")
public class RdsPersistenceConfigration {
}

Updated test after suggestion from @M. Denium
@DataJpaTest
@Transactional
@TestPropertySource(properties = "spring.liquibase.change-log=classpath:db/changelog/changelog.master.xml")
class DivisionRepositoryTest {

    @Autowired
    private DivisionRepository repository;

A: Ok, I finally found the solution, the reason was in something I did not even suspect, my application uses spring native to create optimized production builds, apparently it has somehow intervened with the development build process of the application. For now, I have just removed it from my application.
Later on I will probably try to separate the development build.gradle from the production one.


text:
Q: Not able to install android studio (Error code - 36)
*

*I am using Mac

*I uninstalled Android Studio

*I am trying to install android studio again

*I downloaded a fresh package

*I am trying to drag the package into applications

*I am getting the below error and its not getting installed

A: This problem comes from your Mac pc file system. Error Code 36 is somewhat of a rare error that some Mac users experience. Kindly try following steps and retry again

*

*Go to permission and sharing option. Make it to everyone.

*Also, make sure that your account has read access to the files you
are trying to install.

*Now try to install the same files. If you are still getting the error code 36, go for the actual fix given below.

STEPS TO FIX ERROR CODE 36

*

*Go to Applications.

*Tap on Utilities option. Select Terminal tab. Within the terminal
window, type the following snippet of code: dot_clean.

*The folder,
that was giving error code 36 while copying, needs to be dragged to
the terminal window. As soon as you drag that folder, you will
observe the path of that particular folder appearing on to the
terminal window at the end of the command.

*After going through the
above steps, Click Enter.

*Now retry to install.
Hopefully, you shouldn't be getting error code 36 on your MAC PC now.


text:
Q: How to debug a code that has no trace of my code in its stack trace? I have a web API application, and I get this error:
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__58`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at System.Web.Http.Services.DefaultServices.GetServices(Type serviceType)
at System.Web.Http.ServicesExtensions.GetServices[TService](ServicesContainer services)
at System.Web.Http.ModelBinding.ModelBinderAttribute.GetModelBinderProvider(HttpConfiguration configuration)
at System.Web.Http.ModelBinding.ModelBinderAttribute.GetModelBinder(HttpConfiguration configuration, Type modelType)
at System.Web.Http.ModelBinding.ModelBinderAttribute.GetBinding(HttpParameterDescriptor parameter)
at System.Web.Http.ModelBinding.DefaultActionValueBinder.GetParameterBinding(HttpParameterDescriptor parameter)
at System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter)
at System.Web.Http.ModelBinding.DefaultActionValueBinder.GetBinding(HttpActionDescriptor actionDescriptor)
at System.Web.Http.Tracing.Tracers.ActionValueBinderTracer.System.Web.Http.Controllers.IActionValueBinder.GetBinding(HttpActionDescriptor actionDescriptor)
at System.Web.Http.Controllers.HttpActionDescriptor.get_ActionBinding()
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem..ctor(HttpControllerDescriptor controllerDescriptor)
at System.Web.Http.Controllers.ApiControllerActionSelector.GetInternalSelector(HttpControllerDescriptor controllerDescriptor)
at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)
at System.Web.Http.Tracing.Tracers.HttpActionSelectorTracer.<>c__DisplayClass2.<System.Web.Http.Controllers.IHttpActionSelector.SelectAction>b__0()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)
at System.Web.Http.Tracing.Tracers.HttpActionSelectorTracer.System.Web.Http.Controllers.IHttpActionSelector.SelectAction(HttpControllerContext controllerContext)
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

No part of my code is shown here. How can I debug this?
I've done a global exception handler via AppDomain.CurrentDomain.UnhandledException and it's not hit. I've added a customized ExceptionFilter to web API, and again, it's not executed for this error.
I have no idea how to debug this. Could you help please?


text:
Q: Path for fonts? I searched already for this question and got a page on here where someone answered with "go to home/username/.fonts" or somesuch. I ran into a couple problems:

*

*No such folder existed.

*I discovered there was a "home" above "Home" in the hierarchy. Went there, double-clicked on my username, it took me back to Home. Which still did not contain any folder with the word "font" or "fonts" in it. There is an "etc" immediately followed by "Music." Nothing before "Calibre Library" and nothing after "Zombie Shooter 2 Saves" either.
So yeah, there is no home/username/.fonts or home/username/fonts or anything of the sort. So where in the 24 Hecks does the OS actually keep the Fonts folder? And if anyone tells me home/username/fonts or whatever, I may have to scream.
I have Ubuntu 12, I think, if that helps.

A: You can search for the directory by opening a terminal (Ctrl+Alt+T)
and entering:
find ~ -name fonts

(for me it's .local/share/fonts)

A: the .font folder is a hidden folder ,you may have to create it first.
you can install new fonts by putting them in it.
Now for the location of intalled fonts you can find their locations in your fonts.conf file
gedit /etc/fonts/fonts.conf
mine are in /usr/share/fonts

A: The directory /home itself is not any user's home directory. Rather, this directory contains the home directories of all the users of the system (except root), the name of each user's home direcotry being the name of the user. So, if your user name is user266566, then there will be a directory /home/user266566. That is your home directory. When you are in that directory, the file manager/shell recognizes that and indicates it in some way, such as capitalizing the H in Home, showing a house icon, or replacing the /home/user266566 with ~ (in the case of a shell).
If it helps, /home is akin to C:\Users in Windows.
As for the font directories, you can install fonts either available for all users or simply for yourself. If you want a font available to just yourself, put it in ~/.fonts, where ~ refers to your home directory. If the directory .fonts doesn't exist in your home folder, make one. Also keep in mind that any file (including directories) that begins with a dot (.) will appear hidden unless you set your file manager to show hidden files.
So, if you can't find .fonts, perhaps the file manager is set to not show hidden files. (The key sequence Ctrl + H is a convention to toggle between showing and hiding "dot" files.)
If you want to install fonts system-wide (i.e. for all users), you'll need administrative privileges. The easiest way is to install fonts though the package manager if they're available as packages. These fonts will get installed in /usr/share/fonts (and within that directory, most likely in truetype). However, if you want to manually install fonts, a better place to put them is /usr/local/share/fonts since that nicely separates the fonts installed by the package manager and the fonts you installed manually.


text:
Q: Can I refer someone without committing? One of the proposals (specifically the Food and Cooking proposal) is a perfect site for a friend of mine, but not so much for me. Can I send her a referal request without having committed myself?
If not is this a deliberate choice or just a not-implemented feature?

A: The "Share This" link is now present on all Area 51 proposals...

A: I disagree with Ivo's reply.
I know a group of tinkerers who'd be a perfect fit for launching-today Electronic and Robotics, for example, but I myself just lack have the know-how.
It'd be great to get at least some form of acknowledgment. It's not like reputation abunds on Area51 anyway -- in over five months there still are no 10k mods.

A: I guess it's deliberate. The point is to create a community, if you're not part of it then you can't help building it.
How would you benefit from him/her committing to the site if you don't do it yourself? Just send them the link and they can commit for themselves.


text:
Q: What is a union of n-manifolds? For example, a cross is not a manifold; however, it can be expressed as the union of four 1-manifolds. In my opinion, this is somehow more "tractable" than other non-manifold objects like the union of a line and a region. I am particularly interested in the union of manifolds of the same dimensions.
My questions are:

*

*What are their name?

*What are some properties of this kind of objects? Are they considered similar to manifolds?

Your answer doesn't have to be complete in any sense. Any help will be appreciated!


text:
Q: Labels displaying slightly below form checkbox? I want my text to display inline with my form checkbox - and as far as I know, this is the appropriate code. For some reason, the text is falling slightly beneath the check box? See screen shot and code below.

style.css
input, textarea, select, .uneditable-input {
  border: 2px solid #dbdbdb;
  width: 100%;
  margin-bottom: 15px;
  margin-top: 15px;
  border-radius: 5px;
  padding: 10px;

}

input {

   height: 35px;
   width: 325px;
   font-size: 16px;
}

input[type="radio"], input[type="checkbox"] {

    width: 30px;

}
    label {

        font-size: 18px;
        display: inline-block;
        font-weight: lighter;
        vertical-align: top;
    }

        label[for=receive_newsletters] {

            font-size: 12px;
            display: inline-block;

        }

        label[for=terms_accepted] {

            font-size: 12px;
            display: inline-block;

        }

new.html.erb
    <%= f.check_box :receive_newsletters %> I would like to receive newsletters
    <%= f.check_box :terms_accepted %> I agree to the Terms of Service & Privacy Policy

    <%= f.submit :Register %>
  <% end %>

A: You should remove height: 35px; from input or specify height: auto for input[type=checkbox]


text:
Q: Rails unique lists dependent on sessions I'm trying to create a webpage that allows users to create their own lists on the index page, and I want the list saved in their session, so each list is unique to the user.
I can't seem to get a grasp of how Rails stores sessions. Will I need to create a table to store each session and have it relate to my table of list items, or does Rails already implement sessions in a way I can use to display the list items?
I'm using Rails 5, and I'm aware the session store has been taken out and placed into a gem, but I don't know to what extent.

A: You can store temporary data (like RAM in a computer) with
session[:my_data] = { name: 'foo', age: 1 }
You can store more permanent data (like hard drive in a computer) with
cookies[:my_data] = { name: 'foo', age: 1 }
You can write this code in any controller.
More details about sessions and cookies here.


text:
Q: Rendering an object passed through Pusher in Rails I am trying to implement a realtime chat application.
I'm using pusher to notify server about the button click, and then pass the message object as message to a subscriber. What I need to do is, render that message in other user's chat screen(show.html.erb) dynamically. Here is my cycle:
// MessagesController.rb

    def create
        conversation = Conversation.find(params[:conversation_id])
    message = Message.create(content: params[:content], user_id: params[:user_id])
    conversation.messages << message
        Pusher['test_channel'].trigger('my_event', {
      message: message
    })
    end

And my subscriber is
// show.html.erb
    // some html code
       <ul class="chats">
       <%= render @messages %>
       </ul>
    // some html code

    <script>
         // some js code
         var channel = pusher.subscribe('some_channel');

         channel.bind('some_event', function(data) {
             // What to do here?
         });
    </script>

A: This assumes you are using jquery. It's also untested so may have a few bugs/syntax errors.
Ajax method:
JS
channel.bind('some_event', function(data) {
  $.ajax({
    url:'/messages/'+data.message.id,
    success:function(html){ $('.chats').append(html)}
  });
});

routes:
match '/messages/:id' => "messages#show_no_layout"

controller:
def show_no_layout
  @message = Message.find(params[:id])
  render "show", layout: false
end

view(show.html.erb):
<%= *whatever you want in here* %>

ICH(read more) method:
This will of course require adding an extra js file which is why its not my first suggestion.
Template:
<script id = "messageTemplate" type = "text/html">
   {{ message.content }}
   // plus whatever else you want.
</script>

channel.bind('some_event', function(data) {
  messageHtml = ich.messageTemplate(data.message);
  $('.chats').append(messageHtml);
});

A: If you are using JQuery,
channel.bind('some_event', function(data) {
    $('.message').text(data.message);
});

See this tutorial.


text:
Q: Communicating between networks using sockets I have a question about network connections among computers.
I've made some applications where messages pass through the Internet (via sockets) to make a connection between two devices. However, a strong condition is that two devices must be connected to the same network.
Can anyone give me a trick how to create a communication using sockets between two computers even if they are connected to different netwkorks?
Thank you in advance.

A:
Here is a great tutorial on how to use sockets and general networking
  (in java) http://www.thenewboston.org/watch.php?cat=25&number=38

In order to communicate between two diffrent networks over the internet, you will need to do something called port forwarding. What that does is that when your public IP of your network receives a packet with a spesific port number. The router knows where to send that packet to which local IP.
If you dont port forward and receive some data. The router doesent know where to send the packet. Therefore it discards it, which means others wont be able to connect to you.
You will only need to port forward the network with your server (using the example i linked). How you do that is by logging in to your router, and say that a port which the server uses gets forwarded to the IP of the PC hosting the server.
On the other network (client) you will need to change the IP address of which the client shall connect to. That IP address needs to be your public IP of your server's network. You can find that by connecting to the server's network and go to: http://www.whatsmyip.org/    . Keep in mind  that public IP addresses may change over time.
Hope this helped!
-Kad


text:
Q: Print previous occurrence of a regexp after a match is found with grep (Bash) I have spent some time trying to find the answer to this question but with no luck...
I am writing a script which takes a string as input, then searches through a cvs log for a match. The output should be the filename prior to the matching string. I can write a regex to match the filename without any trouble, however I am unsure how to look back for the last occurrence of a regex after a match is made...
There are obviously many files in the cvs log that I will be parsing and the number of lines between the filename and the input string is unknown so cannot do anything like 'grep -B4' etc...

EXAMPLE BELOW (cvs log with irrelevant bits removed) - Need to match a string (which will be given as input to script (e.g. 120233)) and retrieve the filename associated with it, which here will be (Aliases.xml). As I said there are many files so although the regex will match many filenames, i am only interested in the one prior to my matched string.
This is my first time posting here and I am new to programming so I hope this makes sense.
----------

RCS file: /user1/cvs/Aliases.xml

revision 1.18
date: 2015/03/13 16:21:07;

FIX - 217427 - fixed error....

revision 1.17
date: 2013/03/27 08:03:36;

IMPROVEMENT - 120233 - some improvement

A: You can use awk command for this:
cvs log | awk -F '[:, ]+' -v s='120233' '/RCS file:/{f=$3} f && $0 ~ s{print f; f=""}'

Explanation:
-F '[:, ]+'    # make one or more of colon, comma or <space> a field saprator
-v s='120233'  # pass search string to awk in variable s
/RCS file:/    # search for string "RCS file:"
{f=$3}         # store filename in variable f
f && $0 ~ s    # if f is NOT_EMPTY and line matches variable s
print f; f=""  # print filename from variable f and set f to EMPTY


text:
Q: CPlex and C++ error: no matching function for call to 'IloModel::add(bool)' I'm learning how to use CPlex with C++, and due to that, my question might seem stupid. The following algorithm must access a SQlite database, which contains data of soccer players, fetch its contents and then, with CPlex, determine what is the the best lineup according to the average points and their cost inside a fantasy game.
Here's the code:
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include <iomanip>
#include <sqlite3.h>
#include <string.h>
#include <ilcplex/ilocplex.h>

#define TECNICO 0
#define GOLEIRO 1
#define ZAGUEIRO 2
#define LATERAL 3
#define MEIA 4
#define ATACANTE 5
#define NOME 0
#define TIME 1
#define POSICAO 2
#define SITUACAO 3
#define JOGOS 4
#define PRECO 5
#define PRECO_MEDIO 6
#define PONTUACAO 7
#define PONTUACAO_MEDIA 8
#define FALTAS_SOFRIDAS 9
#define ASSISTENCIAS 10
#define FINALIZACAO_TRAVE 11
#define FINALIZACAO_DEFENDIDA 12
#define FINALIZACAO_FORA 13
#define GOLS 14
#define ROUBADA_BOLA 15
#define SG 16
#define DEFESA_DIFICIL 17
#define DEFESA_PENALTI 18
#define PASSE_ERRADO 19
#define IMPEDIMENTO 20
#define PENALTI_PERDIDO 21
#define FALTA_COMETIDA 22
#define GOL_CONTRA 23
#define CARTAO_AMARELO 24
#define CARTAO_VERMELHO 25
#define GOL_SOFRIDO 26
#define ID 27
#define MAX 855

using namespace std;

struct Jogador{
    string nome;
    int id;
    vector<bool> posicao;
    float pontuacao_media;
    float custo;
    bool provavel;
    bool pertinencia;
};

Jogador jogadores[MAX];

int contador = 0;

int callback(void *, int, char **, char **);

int main(){
    sqlite3 *db;
    sqlite3_stmt *stmt;
    char *err_msg;

    int rc = sqlite3_open("jogadores.db", &db);

    if(rc == SQLITE_OK){
        const char *sql = "SELECT * FROM jogador";
        rc = sqlite3_exec(db, sql, callback, 0, &err_msg);
    }
    else{
        cout << "falhou ao abrir o banco" << endl;
    }

    IloEnv env;
    IloModel model(env);
    IloCplex cplex(env);

    cplex.setParam(IloCplex::Threads, 1);

    float capacidade_cartoletas;

    cout << "Insira a quantidade de cartoletas" << endl;
    cin >> capacidade_cartoletas;

    //IloNumVarArray itens = IloNumVarArray(env, MAX, 0, 1, ILOBOOL);

    bool itens[MAX];

    IloExpr obj = IloExpr(env);

    int max_posicao[] = {1, 1, 2, 2, 4, 2};
    int posicoes_usadas[6];
    for(int i = 0; i < MAX; i++){
        obj += jogadores[i].pontuacao_media*itens[i];
    }

    IloExpr cartoletas_totais = IloExpr(env);

    for(int i = 0; i < MAX; i++){
        cartoletas_totais += jogadores[i].custo*itens[i];
    }

    for(int i = 0; i < MAX; i++){
        for(int j = 0; j < MAX; j++){
            posicoes_usadas[j] += jogadores[i].posicao[j]*itens[i];
        }
    }

    model.add(cartoletas_totais <= capacidade_cartoletas);
    for(int i = 0; i < 6; i++){
        model.add(posicoes_usadas[i] <= max_posicao[i]);
    }

    model.add(IloMaximize(env,obj));

    cplex.extract(model);

    cplex.solve();

    for(int i = 0; i < MAX; i++){
        if(cplex.getValue(itens[i])){
            cout << jogadores[i].nome << endl;
        }
    }

}

int callback(void *NotUsed, int argc, char **argv, char **azColName){
    NotUsed = 0;
    vector<bool> aux;
    aux.assign(6, 0);
    if(!strcmp(argv[POSICAO], "Técnico")){
            aux[TECNICO] = 1;
    }
    else if(!strcmp(argv[POSICAO], "Goleiro")){
        aux[GOLEIRO] = 1;
    }
    else if(!strcmp(argv[POSICAO], "Zagueiro")){
        aux[ZAGUEIRO] = 1;
    }
    else if(!strcmp(argv[POSICAO], "Lateral")){
        aux[LATERAL] = 1;
    }
    else if(!strcmp(argv[POSICAO], "Meia")){
        aux[MEIA] = 1;
    }
    else if(!strcmp(argv[POSICAO], "Atacante")){
        aux[ATACANTE] = 1;
    }
    int id = atoi(argv[ID]);
    jogadores[id].id = id;
    jogadores[id].posicao = aux;
    jogadores[id].pontuacao_media = atof(argv[PONTUACAO_MEDIA]);
    jogadores[id].custo = atof(argv[PRECO]);
    jogadores[id].nome = argv[NOME];

    jogadores[id].provavel = !strcmp(argv[SITUACAO], "Provável");
    contador++;
    return 0;
}

I compile it with g++, but it gives an error:
cartola.cpp:116:55: error: no matching function for call to 'IloModel::add(bool)'
     model.add(posicoes_usadas[i] <= max_posicao[i]);

Another thing: I don't have much experience with CPlex, that code was based on a simpler problem my teacher solved using CPlex with C++

A: You are not modelling your problem using CPLEX modelling variables. This is a very common mistake for beginners. You need to think what data you have whose values you know (e.g. in your database tables) to describe your problem, and what decisions you want your solver (e.g. CPLEX) to make. Then you use normal C++ (or C#, or Java or whatever) variables for the data that you do know, and model those decisions (as yet unknown values) using the modelling variable types (IloNumVar etc) and constraints. You then add those constraints to the CPLEX model and let CPLEX solve the model and choose the best values for your modelling variables.


text:
Q: Securing specific nginx-ingress location with client cert verification I'm setting up an instance of ghost and I'm trying to secure the /ghost path with client cert verification.
I've got an initial ingress up and running that serves the site quite happily with the path specified as /.
I'm trying to add a second ingress (that's mostly the same) for the /ghost path. If I do this and add the annotations for basic auth, everything seems to work. i.e. If I browse to /ghost I am prompted for credentials in the basic-auth secret, if I browse to any other URL it is served without auth.
I then switched to client cert verification based on this example: https://github.com/kubernetes/ingress-nginx/tree/master/docs/examples/auth/client-certs
When I try this either the whole site or none of the site is secured, rather than the path-based separation, I got with basic-auth. Looking at the nginx.conf from the running pod the  proxy_set_header ssl-client-verify, proxy_set_header ssl-client-subject-dn & proxy_set_header ssl-client-issuer-dn elements are added under the root / path and the /ghost path. I've tried removing those (from the root only) and copying the config directly back to the pod but not luck there either.
I'm pulling nginx-ingress (Chart version 0.23.0) in as a dependency via Helm
Ingress definition for / location - this one works
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    certmanager.k8s.io/cluster-issuer: letsencrypt-staging
    kubernetes.io/ingress.class: nginx
    kubernetes.io/tls-acme: "true"
  labels:
    app: my-app
    chart: my-app-0.1.1
    heritage: Tiller
    release: my-app
  name: my-app
  namespace: default
spec:
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: my-app
          servicePort: http
        path: /
  tls:
  - hosts:
    - example.com
    secretName: mysite-tls

Ingress definition for /ghost location - this one doesn't work
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/auth-tls-verify-client: "on"
    nginx.ingress.kubernetes.io/auth-tls-secret: "default/auth-tls-chain"
    nginx.ingress.kubernetes.io/auth-tls-verify-depth: "1"
    nginx.ingress.kubernetes.io/auth-tls-error-page: "http://www.example.com/error-cert.html"
    nginx.ingress.kubernetes.io/auth-tls-pass-certificate-to-upstream: "false"
    kubernetes.io/ingress.class: "nginx"
  labels:
    app: my-app
    chart: my-app-0.1.1
    heritage: Tiller
    release: my-app
  name: my-app-secure
  namespace: default
spec:
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: my-app
          servicePort: http
        path: /ghost
  tls:
  - hosts:
    - example.com
    secretName: mysite-tls

A: You need a '*' on your path on your second ingress if you want to serve all the pages securely under /ghost and if you want just /ghost you need another rule. Something like this:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/auth-tls-verify-client: "on"
    nginx.ingress.kubernetes.io/auth-tls-secret: "default/auth-tls-chain"
    nginx.ingress.kubernetes.io/auth-tls-verify-depth: "1"
    nginx.ingress.kubernetes.io/auth-tls-error-page: "http://www.example.com/error-cert.html"
    nginx.ingress.kubernetes.io/auth-tls-pass-certificate-to-upstream: "false"
    kubernetes.io/ingress.class: "nginx"
  labels:
    app: my-app
    chart: my-app-0.1.1
    heritage: Tiller
    release: my-app
  name: my-app-secure
  namespace: default
spec:
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: my-app
          servicePort: http
        path: /ghost
      - backend:
          serviceName: my-app
          servicePort: http
        path: /ghost/*
  tls:
  - hosts:
    - example.com
    secretName: mysite-tls

However, if you want something like / unsecured and /ghost secured, I believe you won't be able to do it. For example, if you are using nginx, this is a limitation from nginx itself, when you configure a server {} block with TLS in nginx it looks something like this:
server {
    listen              443 ssl;
    server_name         example.com;
    ssl_certificate     example.com.crt;
    ssl_certificate_key example.com.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ...
}

The ingress controller creates paths like this:
server {
    listen              443 ssl;
    server_name         example.com;
    ssl_certificate     example.com.crt;
    ssl_certificate_key example.com.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ...

    location / {
       ...
    }

    location /ghost {
       ...
    }

}

So when you configure another server {} block with the same hostname and with no SSL it will override the first one.
You could do it with different - host: rules in your ingress for example ghost.example.com with TLS and main.example.com without TLS. So in your nginx.conf you would have different server {} blocks.
You can always shell into the ingress controller pod to check the configs, for example:
$ kubectl exec -it nginx-ingress-controller-xxxxxxxxx-xxxxx bash
www-data@nginx-ingress-controller-6bd7c597cb-8kzjh:/etc/nginx$ cat nginx.conf

A: You could add a location-snippet
  annotations:
    nginx.ingress.kubernetes.io/location-snippet: |
       if ($location ^~ ghost) {
          set $ban_info = "location";
       }

       if ($ssl_client_s_dn !~ "CN=ok_client") {
          set $ban_info = "${ban_info}+no_client";
       }

       if ($ban_info = "location+no_client") {
         return 403;
       }


text:
Q: Tags in Search Bar with Swift In the iOS photos app, after I search 'September', I can press on it in the list, and then it adds a tag to the search bar (like in the image)

How can I do something like that in my app using Swift?

A: In AppKit we have NSTokenField for something like that. Apple apparently hasn't released an equivalent for iOS that can be used out of the box at this time. There seem to be a couple of custom implementations though you might want to check out.

*

*https://github.com/nekonora/TaggerKit

*https://github.com/thermogl/TITokenField

*https://github.com/zoonooz/ZFTokenField

*https://github.com/jasarien/JSTokenField
Is there an iPhone equivalent to the NSTokenField control?
https://stackoverflow.com/search?q=nstokenfield+ios


text:
Q: Finding relevant sub ranges for bigdata tables in MS SQL RDBMS efficiently Following my question here.
I have MS SQL Server (regular SQL) that holds 2 tables. Each table contains ~500,000 records. When I write this query it stacks. How can I make it run in efficient way?
Here are the tables:
The first table - MajorRange
| From   |  To     | Group ....
|--------|---------|---------
| 1200   |   1500  | A
| 2200   |   2700  | B
| 1700   |   1900  | C
| 2100   |   2150  | D
...

The second table - SubRange
  | From   |  To     | Group ....
  |--------|---------|---------
  | 1208   |   1300  | E
  | 1400   |   1600  | F
  | 1700   |   2100  | G
  | 2100   |   2500  | H
    ...

The output table should be the all the SubRange groups who has overlap over the MajorRange groups. In the following example the result table is:
| Major  |  Sub |
|--------|------|-
| A      |   E  |
| A      |   F  |
| B      |   H  |
| C      |   G  |
| D      |   H  |

The query I used is something like:
select M.Group Major , S.Group Sub
From MajorRange M, SubRange S
where M.From <= S.To and M.To >= S.From


text:
Q: Confusion in hypothesis testing I'm working at a project in a distribution company. Let's say that in the beggining of this year some major change was made in the sale's area, and my job is to evaluate if this change actually increased the sales.
My thoughts were:
1 - I should do a hypothesis testing using data from 2 months before the change was applied versus the 2 first months of the change, then I shoud know if the change actually increased sales.
Or...
2 - Since I have all the complete sales data from these 4 months, there isn't really a need to use hypothesis testing, since it's only used when you have samples of the population, but in this case, the data I've got from these 4 months is the entire population. So all I needed to do is check the sales amount in the previous 2 months versus the 2 first months of the change.
My question is, which one of these 2 thoughts is correct?
I'm new to hypothesis testing so I'm still figuring it out.


text:
Q: How to find Post Which has more than one Comments in rails query? class Post
 has_many :comments
end

class Comment
 belongs_to :post
end

How to find Post Which has more than one Comments in rails query?

A: Most elegant way is to use rails counter-cache
The first thing you have to do is, add comments_count column to the Post model & add following in Comment model,
belongs_to :post, :counter_cache => true

So you can obtain posts with comments greater than 1 as below,
Post.where('comments_count > ?', 1)

This is rail-ish way to have implementation.

A: Below query should work
Post.joins(:comments).group('posts.id').having('count(comments.id) > ?', 1)


text:
Q: A form can return varying number of values, trying to use the returned values in doctrine query I have saved a bunch of parsed messages in a db, and I want to be able to pull out results depending on user input. I would like to sort by 1-4 values (more options later on), username, id, email or date and time. I've been using doctrine to do my other queries, but this one, I just can't figure out.
My issue is, I don't see how I could possibly check which values are passed into the method and only query for those.
For example:
User enters "bob" into username and "bob@example.com" into the email field. For this scenario I would need doctrine to look something like this:
$queryBuilder
            ->select('*')
            ->from('m2m_messages')
            ->where('username = ' . $queryBuilder->createNamedParameter($params[username]))
            ->andWhere('email = ' . $queryBuilder->createNamedParameter($params[email]))
        $query = $queryBuilder->execute();

But I would like it to change, without creating all the copies separately for each occasion... If I wanted to specify the ID and email, it should only take those values.
I am passing the values in through an array which only contain the search terms I need to use in the sql. For above example it would look something like this:
$params [
    username => 'bob',
    email => 'bob@example.com'
]

I haven't found a way to implement an if(isset) into my code that would allow me to automatically only use the values I passed into the method.
My goal is to be able to enter details into any number of fields, the values entered get passed in an array, and any combination of them is accepted and crafted into the sql script, without having to write 20+ different sql scripts separately.

A: Something like this?
$queryBuilder
    ->select('*')
    ->from('m2m_messages');

if (count($params) > 0) {
    $isFirst = true;
    foreach ($params as $paramKey => $paramValue) {
        if ($isFirst) {
            $queryBuilder->where(sprintf('%1$s = %2$s', $paramKey, $queryBuilder->createNamedParameter($paramValue)));
            $isFirst = false;
        } else {
            $queryBuilder->andWhere(sprintf('%1$s = %2$s', $paramKey, $queryBuilder->createNamedParameter($paramValue)));
        }
    }
}
$query = $queryBuilder->execute();

The concept is to iterate through your parameters and add the where conditions supplied in $params.


text:
Q: Android Compass point to my location instead of north I'm developing compass application where I want the compass to point to a particular latitude longitude position instead of the usual north. I found some questions related to my problem but I don't manage to make them worked for me. Here's my code:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
    private ImageView image;
    private float currentDegree = 0f;
    private SensorManager mSensorManager;
    private TextView tvHeading;
    private Location location = new Location("A");
    private Location target = new Location("B");
    private LocationManager locationManager;

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

        image = (ImageView) findViewById(R.id.imageViewCompass);
        tvHeading = (TextView) findViewById(R.id.tvHeading);

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        location.setLatitude(54.903535);
        location.setLongitude(23.979342);

        target.setLatitude(54.904618);
        target.setLongitude(23.978782);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this); // to stop the listener and save battery
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float degree = Math.round(event.values[0]);
        tvHeading.setText("Heading: " + Float.toString(degree) + " degrees");
        RotateAnimation ra = new RotateAnimation(
                currentDegree,
                -degree,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);
        ra.setDuration(210);
        ra.setFillAfter(true);

        image.startAnimation(ra);
        currentDegree = -degree;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // not in use
    }
}

currently my pointer shows only in north instead of my harcoded target location.

A: I think I found the way to do it:
Here's the method I have changed to get expected behaviour (Based on this question and CookieMonster answer)
@Override
    public void onSensorChanged(SensorEvent event) {
        // get the angle around the z-axis rotated
        float degree = Math.round(event.values[0]);
        degree += geoField.getDeclination();

        float bearing = location.bearingTo(target);
        degree = (bearing - degree) * -1;
        degree = normalizeDegree(degree);

        tvHeading.setText("Heading: " + Float.toString(degree) + " degrees");

        // create a rotation animation (reverse turn degree degrees)
        RotateAnimation ra = new RotateAnimation(
                currentDegree,
                -degree,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);

        // how long the animation will take place
        ra.setDuration(210);

        // set the animation after the end of the reservation status
        ra.setFillAfter(true);

        // Start the animation
        image.startAnimation(ra);
        currentDegree = -degree;
    }

private float normalizeDegree(float value) {
        if (value >= 0.0f && value <= 180.0f) {
            return value;
        } else {
            return 180 + (180 + value);
        }
    }


text:
Q: SuiteCommerce Advanced: Product Sharing Feature Not Working, OG Meta Tag in Shopping.ssp
*

*We are using SCA's default feature to Share Product's details on Social Platform.

*SCA's and Open Graph Protocol's  Documentation says to get the product  title, description, image, url, will require meta tags on html page.

*We tried configuring all require meta tags and it is coming under  of element(to view this you need to open console and in Element tab under head tag), but We are not able to see Image and Description on Social Platform after sharing the product url. It only gives us product url.
4. If you view source on product details page, you will not see any configured meta tags there(og tags), we thought this could be the reason. as Ptoduct details page comes under Shopping ssp, We tried adding heard coded meta tags in shopping.ssp file it self, That works for us.

*But the question here is that, We will require actual product image, description, title on shopping.ssp, how would we can get that on shopping.spp file.

*Or us there any way get the meta tags working with the default feature.
How I can add meta tags in shopping.ssp file, or how to get item details in shopping.ssp file.

A: Which social platform are you trying to use? Facebook has a resource to trouble shoot the implementation at https://developers.facebook.com/.
One thing we discovered is that the URL for the image has to match exactly, so because we were using a folder titled "item images", our images were not showing up because of the space between the two words.
There's also more information at the developer's site:
https://developers.suitecommerce.com/


text:
Q: Specified cast is not valid.. in sql data record I have used following code to insert the list values to table.
I refer this link to impletement this procedure. Passing list of objects to a SQL Server stored procedure and insert records using asp.net core
private List<SqlDataRecord> GetHotelList(List<HotelInfo> list, string RequestRef)
        {
            List<SqlDataRecord> datatable = new List<SqlDataRecord>();

            SqlMetaData[] sqlMetaData = new SqlMetaData[12];
            sqlMetaData[0] = new SqlMetaData("HotelID", SqlDbType.Int);
            sqlMetaData[1] = new SqlMetaData("RequestReference", SqlDbType.VarChar, 15);
            sqlMetaData[2] = new SqlMetaData("FromDate", SqlDbType.DateTime);
            sqlMetaData[3] = new SqlMetaData("ToDate", SqlDbType.DateTime);
            sqlMetaData[4] = new SqlMetaData("Nights", SqlDbType.Int);
            sqlMetaData[5] = new SqlMetaData("MealPlan", SqlDbType.VarChar, 10);
            sqlMetaData[6] = new SqlMetaData("LastUpdatedBy", SqlDbType.VarChar, 50);
            sqlMetaData[7] = new SqlMetaData("LastUpdatedDate", SqlDbType.DateTime);
            sqlMetaData[8] = new SqlMetaData("Status", SqlDbType.Int);
            sqlMetaData[9] = new SqlMetaData("StarCategory", SqlDbType.Int);
            sqlMetaData[10] = new SqlMetaData("CreatedDateTime", SqlDbType.DateTime);
            sqlMetaData[11] = new SqlMetaData("CreatedUserId", SqlDbType.VarChar, 15);

            foreach (var info in list)
            {
                SqlDataRecord row = new SqlDataRecord(sqlMetaData);
                int? hotelId = GetHoteId(info.HotelName);
                row.SetValues(hotelId, RequestRef, info.FromDate, info.ToDate, info.Nights, info.MealPlan, info.StarCategory, info.Status, info.LastUpdatedBy, DateTime.Now, DateTime.Now, info.CreatedUserId);
                datatable.Add(row);
            }

            return datatable;
        }

But I am getting 'specified cast is not valid' error in row.SetValues(). Can I get any clue?
Thanks.

A: Looks the order of your values is off. Specifically, you have:
sqlMetaData[5] = new SqlMetaData("MealPlan", SqlDbType.VarChar, 10);
sqlMetaData[6] = new SqlMetaData("LastUpdatedBy", SqlDbType.VarChar, 50);
sqlMetaData[7] = new SqlMetaData("LastUpdatedDate", SqlDbType.DateTime);
sqlMetaData[8] = new SqlMetaData("Status", SqlDbType.Int);
sqlMetaData[9] = new SqlMetaData("StarCategory", SqlDbType.Int);
sqlMetaData[10] = new SqlMetaData("CreatedDateTime", SqlDbType.DateTime);

But while you insert
info.MealPlan,
info.StarCategory,
info.Status,
info.LastUpdatedBy,
DateTime.Now,
DateTime.Now

Notice how StarCategory, Status and LastUpdatedBy are out of place.

A: Well you did not show us the SQL Sever part which is vital in this case.  Please update your question with the corresponding SQL Server code table to which you are inserting and the stored procedure you are using would be the best.
You are probably doing some value conversion for which the CAST (Cast and Convert function is not correct.

A: row.SetValues method want object
try this
row.SetValues(new object[]{hotelId, RequestRef, info.FromDate, info.ToDate, info.Nights, info.MealPlan, info.StarCategory, info.Status, info.LastUpdatedBy, DateTime.Now, DateTime.Now, info.CreatedUserId});


text:
Q: Taylor Polynomial Approximations I am asked to find a Taylor Polynomial approximation accurate to within $10^{-3}$ for the following function
$$f(x)=\frac{1}{x+1}, x \in [-\frac{1}{2},\frac{1}{2}]$$
We know the Taylor expansion for $f(x)$ is
$$\frac{1}{x+1} = 1 - x + x^2 - x^3 + x^4 - x^5 ...$$
Question 1:
Is the remainder for $f(x)$
$$|R_n(x)|\leq \frac{|x|^{n+1}}{(n+1)!}$$
Question 2:
I choose $n=5$ for an adequate approximation that is within the desired approximation of $10^{-3}$.
So
$$\max_{x\in[\frac{-1}{2},\frac{1}{2}]}|R_5(x)|\leq \frac{|x|^{6}}{7!}$$
Because
$$\frac{6}{7!} \leq 10^{-3}$$
Since I chose $n=5$ I would simply write out a 5th order Taylor polynomial for $f(x)$. Or am I completely wrong?

A: $f(x) = \sum \frac{a_n x^n}{n!}$
And if the series is an alernating series the error is less than the next term in the series.
So yes, in general, error = $\dfrac {|a_{n+1} x^{n+1}|}{(n+1)!}$
However, for this series $a_{n+1} = (-1)^{n+1}(n+1)!$
error $< x^{n+1}$
One more note.  $|x| < \frac{1}{2}, x^{n+1} < 2^{-(n+1)}$
you need nine terms.  $x^{10} < \frac{1}{1024}$


text:
Q: How to add a margin to a tkinter window So I have so far a simple python tkinter window and i'm adding text, buttons, etc.
snippet:
class Cfrm(Frame):

    def createWidgets(self):

        self.text = Text(self, width=50, height=10)
        self.text.insert('1.0', 'some text will be here')
        self.text.tag_configure('big', font=('Verdana', 24, 'bold'))

        self.text["state"] = "disabled"
        self.text.grid(row=0, column=1)

        self.quitw = Button(self)
        self.quitw["text"] = "exit",
        self.quitw["command"] = self.quit
        self.quitw.grid(row=1, column=1)

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

the problem is, I want to have about a 15-20 px margin around the window, I looked everywhere, and I couldn't find a solution. Also
self.text.tag_configure('big', font=('Verdana', 24, 'bold'))

doesn't work. Any possible solutions?

A: Ok, here is the solution I found for question 1:
self.grid(padx=20, pady=20)

Removing .text seems to change the whole frame. I still haven't solved problem 2.

A: A quick way to do it is adjust your relief style to flat, then you only have to adjust your border width.
self.Border = Tkinter.Frame(self, relief='flat', borderwidth=4)

A: You can add an innerFrame with some borderwidth or ipadx,ipady attributes to the root Tk() object. Then put everything in it. And to be sure that innerFrame's width and height values are as the window's, use fill and expand attributes.
root = tk.Tk()
innerFrame = tk.Frame(root, borderwidth=25, bg="red")
innerFrame.pack(fill="both", expand=True)

someButton = tk.Button(innerFrame, text="Button1")
someButton.pack()

or
root = tk.Tk()
innerFrame = tk.Frame(root, bg="red")
innerFrame.pack(ipadx=15, ipady=15, fill="both", expand=True)

someButton = tk.Button(innerFrame, text="Button1")
someButton.pack()

A: Use the pad options (padx, pady, ipadx, ipady) for the grid command to add padding around the text widget. For example:
self.text.grid(row=0, column=1, padx=20, pady=20)

If you want padding around the whole GUI, add padding when you pack the application frame:
self.pack(padx=20, pady=20)

When you say the tag command doesn't work, how do you define "doesn't work"? Are you getting an error? Does the font look big but not bold, bold but not big, ...? The command looks fine to me, and when I run it it works fine.
Your example doesn't show that you're actually applying that tag to a range of text. Are you? If so, how? If you do the following, what happens?
self.text.insert("1.0", 'is this bold?', 'big')


text:
Q: Work of friction on rolling objects In many cases when there is friction acting on a body which is rolling without slipping ( for eg : a body rolling down a inclined plane ),
We say, that the work done by the friction is zero as the velocity of point in contact is zero adn it works out.
But the question,I am having is how does friction still comes into play while the relative velocity of the point is zero ? , because as we know when relative velocity is zero , friction shouldn't act. But if the later is only true after friction comes into play then  why does it still keep acting after the relative velocity is zero?

A:
because as we know when relative velocity is zero , friction shouldn't act.

This is false. Static friction acts when the relative velocity between surfaces is $0$. For a simple example, take a heavy object and start pushing on it without it moving. Static friction is the force that opposes your applied force before the object starts moving.
Because of this, it is in fact true that static friction does not do work on a rolling object in the rest frame of the surface the object is rolling across.

A: If you are accelerating in your car, then the friction force from the road acting in the forward direction on the bottom of the wheels is moving forward with your car. As the only net external force, it is doing the work to accelerate the car.
If you apply the breaks, the friction force acts backwards, moves with the car, and does negative work to remove the cars kinetic energy.
If a wheel is rolling down an incline, friction provides the torque to increase the rotational energy.
In each of these cases, the object is gaining or losing energy in the rest frame. Clearly, there is something wrong with the logic that says that static friction cannot do work.


text:
Q: Switching "maven-assembly-plugin" on/off Our current DevOps environment runs mvn package and auto-deploys the jar artifact in a private Maven repository and all target folder is cached for later use. But the project has also a maven-assembly-plugin set up what packages a second jar file (a fat jar suffixed as -jar-with-dependencies).
We don't want the "fat jar" to be generated by maven-assembly-plugin and so stored in that cache along with other files in that case.
Is there a way to switch maven-assembly-plugin on and off by command line (or any other property or environment variable) to run it only when explicitly required?

A: You can set the property assembly.skipAssembly to true.
Either on command line ( with -Dassembly.skipAssembly=true) or in the POM itself.

A: The easiest approach (IMHO), would be to define the plugin in its own profile. Inside your pom.xml, you add a profiles section, and in that a profile that would include the plugin:
<profiles>
  <profile>
    <id>assemble</id>
    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-assembly-plugin</artifactId>
          <!-- All the configuration you have for the plugin -->
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

Then, by default, this plugin will not be called. When you want to call it, you can explicitly enable this profile with the -P flag:
mvn package -Passemble


text:
Q: Dropdowns being chopped off in IE 8 when used with jQuery tmpl plugin I need to show four select lists on a page with the following requirements:

*

*The total space allocated to the select lists is fixed (let's say 400 px) i.e. 100 px per select list.

*The options are much bigger than 100 px. The requirement is to ensure that they should not appear chopped off when the user clicks on the select list to see the options.

*The solution should work in IE7 and IE8.

*The 4 select lists will be part of a dynamic template that is being bound using knockoutjs and jquery tmpl plugin.
I was able to get the first 3 requirements going by using the code below (has hard-coded values for the options). When I did so, the select list options were not being chopped off when the user tried to see all the options in IE8.
I was also able to load this template dynamically using jquery tmpl plugin and knockout (requirement 4). However, when I did this, the select options start getting chopped off.
Here is the code:

        <select>
            <option value="a">This is just a random long line. We are using it to test dropdowns in IE 8</option>
            <option value="b">This is some more random text. </option>
            <option value="c">Still trying to fit in the text.</option>
        </select>

        <select>
            <option value="a">This is just a random long line. We are using it to test dropdowns in IE 8</option>
            <option value="b">This is some more random text. </option>
            <option value="c">Still trying to fit in the text.</option>
        </select>

        <select>
                <option value="a">This is just a random long line. We are using it to test dropdowns in IE 8</option>
                <option value="b">This is some more random text. </option>
                <option value="c">Still trying to fit in the text.</option>
        </select>

        <select>
            <option value="a">This is just a random long line. We are using it to test dropdowns in IE 8</option>
            <option value="b">This is some more random text. </option>
            <option value="c">Still trying to fit in the text.</option>
        </select>

                This is just a random long line. We are using it to test dropdowns in IE 8
                This is some more random text.
                Still trying to fit in the text.

                This is just a random long line. We are using it to test dropdowns in IE 8
                This is some more random text.
                Still trying to fit in the text.

                This is just a random long line. We are using it to test dropdowns in IE 8
                This is some more random text.
                Still trying to fit in the text.

                This is just a random long line. We are using it to test dropdowns in IE 8
                This is some more random text.
                Still trying to fit in the text.

Is this code supposed to work with dynamic templates? If not, how can I go about my requirements?

A: I remember seeing a similar issue in IE before with Knockout. I think a quick solution was to put in the following hack: $("select").width("100px"); (or whatever width you need) after the bindings had been applied. I remember it only affected IE too :-)


text:
Q: Writing unit tests for search engine project for a course I'm taking I'll be writing a pretty robust text search engine.
I was thinking of using test driven development to facilitate the development.
My problem is that I've never written unit tests before so I'm not sure what I should be testing for.
Would a test that for example runs a specific query expecting specific known results would be a good test (ie. run query "medicine", throw error if it does not return 5000 results) be a good candidate, or should my tests be smaller, testing smaller parts of the code instead of the whole program?
If that is the case what are some good examples of unit tests in a search engine application?
What are some good resources to get started at test driven development thinking ?