text:
Q: Ошибка при подключении к БД mysql с использованием родного коннектора для .net Authentication to host '192.168.0.14' for user 'root' using method 'mysql_native_password' failed with message: Reading from the stream has failed

Ошибка возникает в момент открытия соединения.
Причем через Workbench я спокойно подключаюсь к БД с этим же логином и паролем.
Вот фрагмент кода, где возникает данная ошибка:
conStrBilder = new MySqlConnectionStringBilder();
conStrBilder.Server = "192.168.0.14";
conStrBilder.Database = "login";
conStrBilder.UserID = "root";
conStrBilder.Password = "root";
DataTable dt = null;
var con = new MySqlConnection(conStrBilder.ConnectionString);
var command = new MySqlCommand(query, con);
try
{
    //здесь вываливается исключение
    con.Open()
    var dr = command.ExecuteReader();
    If(dr.HasRows)
    {
        dt = new DataTable();
        dt.Load(dr);
    }
}
catch(Exceprion ex)
{
    errorString = ex.Message;
}
finally
{
    con.Close();
}

Версия mysql на сервере(RHEL): 14.4 Distrib 5.7.11
Версия коннектора для .net: 6.9.8 (скачал с официального сайта). Также попробовал версию 7.0.2

A: Проблема решена.
Заработало с вот этим коннектором MySQL Connector NET 6.8.3

A: Попробуйте отключить Pooling соединений (добавить "Pooling=False;" в ConnectionString)
https://bugs.mysql.com/bug.php?id=76597


text:
Q: Responsive Chess Board Issue As can be seen in the fiddle below, the chessboard responds as it should which is no more then 512px wide, while shrinking to fit whatever device. The pieces also respond with the board as they should. The problem I am having is that when I add a piece to the board / inside a square div, its like the img is creating a bunch of extra space below. Looks like its twice the size of the img... I know that the img's are causing the issue because I removed all the img's from the top of the board and the squares are completely square as they should be. Yes, the img's I am using are 64px x 64px. Any ideas of whats happening here? Any help would be great. Thanks!
http://jsfiddle.net/4vxLP

.fl{

    float:left;
}

.board{

    max-width:512px;
    margin: 0 auto;
}

.whiteSquare{

    max-height: 64px;
    max-width: 64px;
    width:12.5%;
    padding-bottom:12.5%;
    background-color:#F7F7F7;
}

.blackSquare{

    max-height: 64px;
    max-width: 64px;
    width:12.5%;
    padding-bottom: 12.5%;
    background-color:#29BEE8;
}

.piece{

    max-width: 100%;
    max-height: 100%;
}

A: You can just add position:absolute; to your .piece class: http://jsfiddle.net/4vxLP/2/
The problem you are having is the padding-botton you are using to keep the size in the empty divs. Remember when you use padding it sums space to the total of the container, so when you add the image you have the image size plus the padding added.

redpajama_set_name: RedPajamaStackExchange


text:
Q: selenium:socket.error: [Errno 61] Connection refused There are 10 links I want to catch
When I run spider,I can get the links in json file ,but there are still errors like this:
It seems like selenium run twice.What's the problem is?
Please guide me Thank you
2014-08-06 10:30:26+0800 [spider2] DEBUG: Scraped from <200 http://www.test/a/1>
{'link': u'http://www.test/a/1'}
2014-08-06 10:30:26+0800 [spider2] ERROR: Spider error processing <GET
http://www.test/a/1>
Traceback (most recent call last):
 ........
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection
    raise err
socket.error: [Errno 61] Connection refused

Here is my code:
from selenium import webdriver
from scrapy.spider import Spider
from ta.items import TaItem
from selenium.webdriver.support.wait import WebDriverWait
from scrapy.http.request import Request

class ProductSpider(Spider):
    name = "spider2"
    start_urls = ['http://www.test.com/']
    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)
        self.driver.implicitly_wait(20)
        next = self.driver.find_elements_by_css_selector("div.body .heading a")
        for a in next:
            item = TaItem()
            item['link'] =  a.get_attribute("href")
            yield Request(url=item['link'], meta={'item': item}, callback=self.parse_detail)

    def parse_detail(self,response):
        item = response.meta['item']
        yield item
        self.driver.close()

A: The problem is that you are closing the driver too early.
You should close it only when the spider finishes it work, listen to spider_closed signal:
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from selenium import webdriver
from scrapy.spider import Spider
from ta.items import TaItem
from scrapy.http.request import Request

class ProductSpider(Spider):
    name = "spider2"
    start_urls = ['http://www.test.com/']
    def __init__(self):
        self.driver = webdriver.Firefox()
        dispatcher.connect(self.spider_closed, signals.spider_closed)

    def parse(self, response):
        self.driver.get(response.url)
        self.driver.implicitly_wait(20)
        next = self.driver.find_elements_by_css_selector("div.body .heading a")
        for a in next:
            item = TaItem()
            item['link'] =  a.get_attribute("href")
            yield Request(url=item['link'], meta={'item': item}, callback=self.parse_detail)

    def parse_detail(self,response):
        item = response.meta['item']
        yield item

    def spider_closed(self, spider):
        self.driver.close()

See also: scrapy: Call a function when a spider quits.


text:
Q: Pass client-side javascript variable to server-side php I try again to ask my question. I hope that this time it's clear enough.
Here's the live demo of my script:
http://www.virusgaming.net/test/
And this is the code:
<? // I set the starting percentage to 0%.
$something = 0; ?>

Multi Color Bar

Loading...

« Select Options

I want to pass the client-side javascript percentage to server-side php variable. I did tens of tries with GET and POST javascript (hidden fields, forms, anchor, onclick event etc) with no success. Basically with the onclick="alert(manualPB2.getPercentage()); function i stamp the current percentage in an alert. Is possible edit this alert so that it post/get the variable to php?

A: Instead of the alert, try this ajax call,
 var url = 'YourServerSideScript.php';
 var pars = 'percentage=' + pbObj.getPercentage(); // you have to use $_POST['percentage'] on your script
 var target = 'targeDivId';
 var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars});

A: As a variation on jose's answer (there's no need to use Ajax.Updater unless you're expecting an HTML response) Prototype really does provide everything you need.
document.observe('dom:loaded', function() {
    // after existing initialising code...

    $$('.getOption a').first().observe('click', function(event) {
        new Ajax.Request('YourServerSideScript.php', {
            parameters: {
                percentage: parseInt(manualPB2.getPercentage())
            }
        });
        event.stop();
    });
});

...and the value will be $_POST['percentage'] in your script. I didn't set method since it will be POST anyway, and parameters is an object which means Prototype will urlencode it for you, so saving the effort. Remember to read the manual.
parseInt will strip out any % characters if they exist in the percentage. event.stop() neatly prevents the anchor's normal click behaviour.


text:
Q: ParallaxViewPager Right to Left I am working a project on ParallaxViewPager. I have 3 pages. Everything working normal and the background is parallax as supposed to. But when I add parallaxViewPager.setCurrentItem(2); the background does not appear and it gets default android background. Here is the full code:
MainActivity:
package com.example.myapplication3.app;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.RelativeLayout;

import com.andraskindler.parallaxviewpager.ParallaxViewPager;

import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends FragmentActivity {

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

        final ParallaxViewPager parallaxViewPager = ((ParallaxViewPager) findViewById(R.id.parallaxviewpager));
        parallaxViewPager.setOverlapPercentage(0.25f);
        parallaxViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        parallaxViewPager.setCurrentItem(2);

        }
    }

PagerAdapter:
package com.example.myapplication3.app;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class MyPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        this.fragments = new ArrayList<Fragment>();

        fragments.add(new view1());
        fragments.add(new view2());
        fragments.add(new view3());
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}

View 1,2,3:
package com.example.myapplication3.app;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class view1 extends Fragment { //view2, view3 on the others

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.view1, container, false); //same here view 2,3

        return rootView;
    }
}

and the layouts are:
MainActivitys' layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame" >

    <com.andraskindler.parallaxviewpager.ParallaxViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/parallaxviewpager"
        android:layout_width="match_parent"
        android:background="@drawable/sanfran"
        android:layout_height="match_parent"/>

    </RelativeLayout>

View 1,2,3' layout:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>

Thanks in advance for your time and help.

A: I had the same problem with this component. It something like a conflict between the canvas and the destination rect so anything is drawn where it should be done.
I made a fork of the original source repository to update it. When setCurrentItem is invoked I check the position and store an adjust value that I use later in the onDraw method.
You can check it at https://github.com/yuraksisa/parallaxviewpager

A: Here is a modification of the ParallaxViewPager:
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;

@SuppressLint("NewApi")
public class ParallaxViewPager extends ViewPager {

    public static final int FIT_WIDTH = 0;
    public static final int FIT_HEIGHT = 1;
    public static final float OVERLAP_FULL = 1f;
    public static final float OVERLAP_HALF = 0.5f;
    public static final float OVERLAP_QUARTER = 0.25f;
    public Bitmap bitmap;
    private Rect source, destination;
    private int scaleType;
    private Paint paint;
    private OnPageChangeListener secondOnPageChangeListener;

    public ParallaxViewPager(Context context) {
        super(context);
        init();
    }

    public ParallaxViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        source = new Rect();
        destination = new Rect();
        scaleType = FIT_HEIGHT;
        setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                if (bitmap != null) {
                    if (position == 0) {
                        source.left = (int) ((getWidth() / 8) * positionOffset);
                        source.right = getWidth() + source.left;
                        destination.left = (int) ((getWidth() * positionOffset) - getWidth());
                        destination.right = (int) (0 + (getWidth() * positionOffset));

                    } else {
                        source.left = (int) ((getWidth() / 8) - (getWidth() / 8)
                                * positionOffset);
                        source.right = getWidth() + source.left;
                        destination.left = (int) ((0 - getWidth()
                                * positionOffset));
                        destination.right = (int) (getWidth() - (getWidth() * positionOffset));
                    }

                    postInvalidate();
                }

                if (secondOnPageChangeListener != null) {
                    secondOnPageChangeListener.onPageScrolled(position,
                            positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                if (secondOnPageChangeListener != null) {
                    secondOnPageChangeListener.onPageSelected(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (secondOnPageChangeListener != null) {
                    secondOnPageChangeListener.onPageScrollStateChanged(state);
                }
            }
        });
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        destination.top = 0;
        destination.bottom = h;
        if (getAdapter() != null && bitmap != null)
            calculateParallaxParameters();
    }

    private void calculateParallaxParameters() {
        if (bitmap.getWidth() < getWidth()
                && bitmap.getWidth() < bitmap.getHeight()
                && scaleType == FIT_HEIGHT) {
            Log.w(ParallaxViewPager.class.getName(),
                    "Invalid bitmap bounds for the current device, parallax effect will not work.");
        }
        source.top = 0;
        source.bottom = bitmap.getHeight();

    }

    /**
     * Sets the background from a resource file.
     *
     * @param resid
     */
    @Override
    public void setBackgroundResource(int resid) {
        bitmap = BitmapFactory.decodeResource(getResources(), resid);
    }

    /**
     * Sets the background from a Drawable.
     *
     * @param background
     */
    @Override
    public void setBackground(Drawable background) {
        bitmap = ((BitmapDrawable) background).getBitmap();
    }

    /**
     * Deprecated. Sets the background from a Drawable.
     *
     * @param background
     */
    @Override
    public void setBackgroundDrawable(Drawable background) {
        bitmap = ((BitmapDrawable) background).getBitmap();
    }

    /**
     * Sets the background from a bitmap.
     *
     * @param bitmap
     * @return The ParallaxViewPager object itself.
     */
    public ParallaxViewPager setBackground(Bitmap bitmap) {
        this.bitmap = bitmap;
        return this;
    }

    public ParallaxViewPager setScaleType(final int scaleType) {
        if (scaleType != FIT_WIDTH && scaleType != FIT_HEIGHT)
            throw new IllegalArgumentException(
                    "Illegal argument: scaleType must be FIT_WIDTH or FIT_HEIGHT");
        this.scaleType = scaleType;
        return this;
    }

    /**
     * Sets the amount of overlapping with the setOverlapPercentage(final float
     * percentage) method. This is a number between 0 and 1, the smaller it is,
     * the slower is the background scrolling.
     *
     * @param percentage
     * @return The ParallaxViewPager object itself.
     */
    public ParallaxViewPager setOverlapPercentage(final float percentage) {
        if (percentage <= 0 || percentage >= 1)
            throw new IllegalArgumentException(
                    "Illegal argument: percentage must be between 0 and 1");
        return this;
    }

    /**
     * Recalculates the parameters of the parallax effect, useful after changes
     * in runtime.
     *
     * @return The ParallaxViewPager object itself.
     */
    public ParallaxViewPager invalidateParallaxParameters() {
        calculateParallaxParameters();
        return this;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (bitmap != null) {
            canvas.drawBitmap(bitmap, source, destination, paint);
        }
    }

    public void addOnPageChangeListener(OnPageChangeListener listener) {
        secondOnPageChangeListener = listener;
    }
}

And here is how to use:
viewPager = (ParallaxViewPager)findViewById(R.id.lock_viewpager);
viewPager.setBackgroundDrawable(new BitmapDrawable());
viewPager.setAdapter(new MyViewPagerAdapter());
viewPager.addOnPageChangeListener(this);
viewPager.setCurrentItem(mList.size());


text:
Q: A UIView isn't placed right on top of a collection view cell when inserted to the view controller view's hierarchy I have a horizontal collection view, which cells don't cover the whole screen. I want to insert a UIView to a view controller's hierarchy and place it right on top of the selected cell.
In order to do that I need the frame of the selected cell. To get it I've tried the following inside the didSelectItem method:
1)
let frame = collectionViewLayout.layoutAttributesForItem(at: indexPath)?.frame

2)
 let selectedCell = collectionView.cellForItem(at: indexPath)

In both cases I get the same result and that's the right one. For inserting a UIView into the hierarchy I use the following code:
    self.view.insertSubview(mimicView, aboveSubview: collectionView)
    mimicView.frame = frame

    print ("mimicView frame:", mimicView.frame)

The print statement prints the right frame (it is the same as the one of the selected cell). However, mimicView position isn't exactly on top of the cell when it is drawn. For the first cell the view's y has a small negative value. For the subsequent cells the view is drawn further and further to the left. So, for example, for the second cell, the view is drawn almost on top of the third one. And for the third one, it is drawn almost on top of the fifth one. In Interface Debugger I see that its x value is way too big and y value is a small negative number (like -20 - -40 points), however, the print statement still shows the same values as for the selected cell.
If someone knows why this is happening, I would really appreciate your help.

A: Make sure that you convert the cell's bounds to the view's coordinate system (the view to which you want to add the new subview) and use the resulting rectangle as your covering view's frame:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.cellForItem(at: indexPath) else { return }
    let cellFrame = cell.convert(cell.bounds, to: view)

    let coverView = UIView(frame: cellFrame)
    coverView.backgroundColor = .darkGray
    view.addSubview(coverView)
}


text:
Q: Swift enum both a string and an int I have a situation where I'm trying to do binary decoding of some data and the data types have both a numerical value and a string value and a name.  I was thinking of using an enum such as:
enum TARGET_TRACK_TYPE : String {
    case TT_INVALID          = "Invalid"
    case TT_TRUE_TRACK_ANGLE = "True Track Angle"
    case TT_MAGNETIC         = "Magnetic"
    case TT_TRUE             = "True"
}

However I also know that:
TT_INVALID = 0 and TT_TRUE_TRACK_ANGLE = 1, etc.  Is there an easy way to encapsulate both these "things" the string and the numerical value into an enum construct or do i need to make some sort of struct/class to handle this?
I guess I'd like to do something like
let a = TARGET_TRACK_TYPE.rawValue(value: 2)
println(a)
which would print True Track Angle
Again, I know this can be done with a struct or a class but I'm specifically interested in the enum
Or for another example:
/// Emitter Category is defined in section 3.5.1.10 of the GDL90 Spec
struct EmitterCategory {

let category : Int

func getString() -> String {

    switch(category) {
    case 0:
        return "No aircraft type information";
    case 1:
        return "Light";
    case 2:
        return "Smalle";
    case 3:
        return "Large";
    case 4:
        return "High Vortex Large";
    case 5:
        return "Heavy";
    case 6:
        return "Highly Manuverable";
    case 7:
        return "Rotorcraft";
    case 8:
        return "(Unassigned)";
    case 9:
        return "Glider/sailplane";
    case 10:
        return "Ligther than air";
    case 11:
        return "Parachutist/sky diver";
    case 12:
        return "Ultra light/hang glider/paraglider";
    case 13:
        return "(Unassigned)";
    case 14:
        return "Unmanned aerial vehicle";
    case 15:
        return "Space/transatmospheric vehicle";
    case 16:
        return "(Unassigned)";
    case 17:
        return "Surface vehicle - emergency vehicle";
    case 18:
        return "Surface vehicle - service vehicle";
    case 19:
        return "Point obstacle";
    case 20:
        return "Cluster Obstacle";
    case 21:
        return "Line Obstacle";
    default:
        return "(reserved)";
    }
}
}

Is there a way to refactor this struct into an enum such that I construct the enum with an integer value but I "read" the enum as a string?  I'm pretty sure the answer is no.

A: I think this will do it for me.  Thank you self.. :)
protocol GDL90_Enum  {
      var description: String { get }
}

enum TARGET_ADDRESS_TYPE : Int, GDL90_Enum {
   case ADSB_ICAO_ADDRESS = 0
   case ADSB_SELF_ADDRESS = 1
   case TISB_ICAO = 2
   case TISB_TRACK_ID = 3
   case SURFACE_VEHICLE = 4
   case GROUND_STATION = 5

   var description: String {
      switch self {
   case .ADSB_ICAO_ADDRESS:
      return "ADS-B with ICAO address"
   case .ADSB_SELF_ADDRESS:
      return "ADS-B with Self-assigned address"
   case .TISB_ICAO:
      return "TIS-B with ICAO address"
   case .TISB_TRACK_ID:
         return "TIS-B with track file ID"
   case .SURFACE_VEHICLE:
         return "Surface Vehicle"
   case .GROUND_STATION:
         return "Ground Station Beacon"
   default:
         return "Reserved"
      }
   }
}

A: With Swift 4.2 this can be done using CaseIterable. One, relatively concise way is to do the following
enum Directions: String, CaseIterable {
    case north, south, east, west

    static var asArray: [Directions] {return self.allCases}

    func asInt() -> Int {
        return Directions.asArray.firstIndex(of: self)!
    }
}

print(Directions.asArray[2])
// prints "east\n"

print(Directions.east.asInt())
// prints "2\n"

print(Directions.east.rawValue)
// prints "east\n"

A: You should use RawRepresentable
@objc enum AppEvent:Int, RawRepresentable  {
    case appLaunch
    case homeScreen

    public typealias RawValue = String

    public var rawValue: RawValue {
        switch self {
        case .appLaunch                      : return "appLaunch"
        case .homeScreen                    : return "homeScreen"
    }

    public init?(rawValue: RawValue) {
        switch rawValue {
        case "appLaunch"                    : self = .appLaunch
        case "homeScreen"                   : self = .homeScreen
    }

A: Have you considered using a dictionary?
 let targetTrackDict: [Int: String] =
      [99: "Invalid",
       1: "True Track Angle",
       2: "Magnetic",
       5: "True"]

Note the number codes don't have to be ordered or contiguous. Being specific about the dictionary's type in its declaration prevents a lot of warnings or errors in the following snippets.
Getting the name for a code is easy:
var code = 2
if let name = targetTrackDict[code] {
  print("\(name) has code \(code)")
} else {
  print("\(code) is not a valid track type")
}

I haven't found a tidy way of getting the code for a name, but this does it:
let magneticCode = targetTrackDict.first(where:
    {key, value in value == "Magnetic"})?.key
// returns an optional

and you would of course dress it up as a function. What you don't get automatically is an internal name for your track type, but do you need one? And the line above does it for you in a way.

A: Summing up @Jeef's answer and @NobodyNada's comment, here's a solution
public enum Animal: Int, CustomStringConvertible {
    case Dog, Cat

    public var description: String {
        switch self.rawValue {
        case 0: return "Dog"
        case 1: return "Cat"
        default: return ""
        }
    }
}

var animal = Animal.Dog
print(animal) // Dog


text:
Q: Oscillation of Howland DC current source I am trying to build a DC voltage controlled current source based on two op-amps as in the following schematic.
The Spice simulation results are quite ok, but when I test the PCB with an oscilloscope, there is an unwanted oscillation at the output.
Note: DC input(+) at OPA 547.

A: You are using an LM324 op-amp configured as a non-inverting amplifier with a gain of 26. The GBWP of the LM324 is 1 MHz and this means that it will just about work with a gain of 26 at no higher than 38 kHz. Your signal input is 150 kHz so, at this frequency, you WILL get bad results.

A: Spice models of opamps are crude approximations at best. They never contain all parasitics or accurately model the transfer characteristics. You have coupled two opamps in a feedback loop, which can be unstable quite easily. Look at the datasheet what the transfer characteristic of your opamps is, calculate from there what your phase margin is. Then tweak your circuit until your phase margin is at least 45°, as you need some head room for the variation in opamps due to production and temperature.


text:
Q: How can a timestamp (nestled in a firebase Double or String) be retrieved via snapshot as an int for use in an if statement? The question seems easy bit it is a bit more complicated. Here is the relevant database structure:
"people" : {
    "q3up6CyAe5PoEAooJwCclOGGcZd2" : {
      "peopleWhoLike2" : {
        "NMNQYJ5z64fATK2MMs7m0ggHl0k2" : 1571089433551

We are interested in the 1571089433551 timestamp. The first user id (q3up6CyAe5PoEAooJwCclOGGcZd2) is the user whom the current user liked. The current user is NMNQYJ5z64fATK2MMs7m0ggHl0k2
We want to write an if statement for when the current time minus 1571089433551 is larger than 8000 seconds. That part I can do. The question is not for that. It is for how to get to 1571089433551 as an int via a snapshot
This is how the timestamp was made:
      ref.child("people").child(self.postID).observeSingleEvent(of: .value, with:  {(snapshot) in
            if let people1 = snapshot.value as? [String: AnyObject] {

                let current = Auth.auth().currentUser!.uid
                let p3 = ServerValue.timestamp()as! [String : Any]
                let updateLikes: [String: Any] = [current: p3]

                ref.child("people").child(self.postID).child("peopleWhoLike2").updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in .....

This is where I tried to user it for the IF statement
          let thisUsersUid = Auth.auth().currentUser?.uid //Mr. Dunn's uid

          refArtists = Database.database().reference().child("people").child(self.postID).child("peopleWhoLike2")

          refArtists.observe(DataEventType.value,  with: {snapshot in

    ---------

let secondsInDay = 86400

if (Int(-date.timeIntervalSinceNow) < secondsInDay){

That ------ part between the above is what I need to figure out. How to read the firebase snapshot and get the 1571089433551 as an int.

A: This is a literal answer - I suspect there may be more to it so I can update as needed.
Start with a structure similar to yours
people
   uid_0 //the user whom the current user liked,
      peopleWholike2
         uid_1: 123456 //the current user with a timestamp

Here's one way to get directly to the timestamp: 123456. I added some extra vars so you can see the path and self.ref points to my Firebase.
func readChildTimestamp() {
    let peopleRef = self.ref.child("people")
    let thisPersonRef = peopleRef.child("uid_1")
    let peopleThatLikeThisPersonRef = thisPersonRef.child("peopleWhoLike2")
    peopleThatLikeThisPersonRef.observeSingleEvent(of: .childAdded, with: { snapshot in
        let personUidKey = snapshot.key
        let timestamp = snapshot.value as? Int ?? 0
        print(personUidKey, timestamp)
    })
}

I leveraged .childAdded in this case because it only will ever read the first node when used with .observeSingleEvent. In your question you are looking for that specific timestamp so this will do it.
Edit:
Based on some additional information we need to expand this answer. It appears there may be multiple child nodes within the peopleWhoLikeMe2 node like this
people
   uid_0
      peopleWholike2
         uid_1: 123
         uid_2: 456
         uid_3: 789

Suppose user with uid_3 logs in and wants to read their timestamp from uid_0's node. Here's the code
func readChildTimestamp() {
    let myUid = "uid_3" //this is the currently logged in user
    let peopleRef = self.ref.child("people")
    let thisPersonRef = peopleRef.child("uid_0")
    let peopleThatLikeThisPersonRef = thisPersonRef.child("peopleWhoLike2")
    let myRef = peopleThatLikeThisPersonRef.child(myUid)
    myRef.observeSingleEvent(of: .value, with: { snapshot in
        let personUidKey = snapshot.key
        let timestamp = snapshot.value as? Int ?? 0
        print(personUidKey, timestamp)
    })
}

and the out is
uid_3 789


text:
Q: spring-cloud-starter-stream-source-file delete the file after processing I'm trying to utilize spring-cloud-starter-stream-source-file app (https://github.com/spring-cloud-stream-app-starters/file/tree/master/spring-cloud-starter-stream-source-file) to poll a directory and send the file ref to custom processor for further processing.
Is there an option available to delete the file after being processed by the source app?

A: We don't have the option to delete the processed file for the file-source yet. Feel free to add a story in the file-source backlog - we welcome contributions, too!
As an alternative, you could use the sftp-source, and that includes an option to delete the remote files on successful ingest.


text:
Q: How to correctly add some node_modules to externals property in webpack config? I'm trying to run unit tests with generating code coverage report, but I'm getting warnings and an error related to some node_modules, how I can fix it? Also if I'm removing express from externals property I see warning message for this dependency and error message for grcp dependency
webpack base config

const path = require("path")
const nodeExternals = require("webpack-node-externals");

const resolve = dir => path.join(__dirname, "..", dir)
const createLintingRule = () => ({
    test: /\.(js)$/,
    loader: "eslint-loader",
    enforce: "pre",
    include: [resolve("server"), resolve("test")],
    options: {
        formatter: require("eslint-friendly-formatter"),
    }
})

module.exports = {
    context: path.resolve(__dirname, "../"),
    target: "node",
    node: {
        __filename: true,
        __dirname: true
    },
    externals: { ...nodeExternals(),
        express: "express",
        bufferutil: "commonjs bufferutil",
        "utf-8-validate": "commonjs utf-8-validate",
        memcpy: "bytebuffer",
        encoding: "node-fetch",
        grpc: "grpc",
        "dtrace-provider": "dtrace-provider",
        "@opencensus": "@opencensus",

    },
    output: {
        path: path.join(__dirname, "../dist"),
        filename: "server.js"
    },
    devServer: {
        inline: false,
        contentBase: "./dist",
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.mjs', '.js', '*', '.json', '.gql', '.graphql']
    },
    module: {
        rules: [
            createLintingRule(),
            {
                test: /\.mjs$/,
                include: /node_modules/,
                type: 'javascript/auto'
                // resolve: {
                //     fullySpecified: false,
                // },
            },
            {
                test: /\.html$/i,
                loader: "html-loader",
            },
            {
                test: /\.js$/,
                include: path.resolve("src"),
                loader: "istanbul-instrumenter-loader"
            },
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules/,
                options: {
                    sourceMaps: true,
                    plugins: [
                        "@babel/plugin-transform-regenerator",
                        "@babel/plugin-transform-named-capturing-groups-regex"
                    ],
                    presets: [
                        [
                            "@babel/preset-env", {
                            useBuiltIns: "entry",
                            shippedProposals: true,
                            corejs: 3,
                        }
                        ],
                    ],
                }
            },
            { test: /\.ts$/, use: 'ts-loader' }
        ],
    },
}

package.json

{
  "name": "zing-graphql",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack --config build/webpack.prod.conf.js --progress",
    "dev": "webpack --config build/webpack.dev.conf.js",
    "dev:mock": "MOCK=ALL webpack --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "clean": "rm -rf dist/ node_modules/",
    "lint": "./lint.sh",
    "test": "nyc test/test.sh",
    "testspec": "test/test.sh",
    "tdd": "mochapack --webpack-config build/webpack.prod.conf.js --require test/setup.js --watch 'server/v2/**/*.spec.js'",
    "graphql:codegen": "graphql-codegen"
  },
  "engines": {
    "node": ">= 10.0.0"
  },
  "description": "ZING GraphQL service",
  "main": "server/index.js",
  "repository": "git@github.com:zenoss/graphql.git",
  "author": "Zenoss <dev@zenoss.com>",
  "private": true,
  "resolutions": {
    "**/@opencensus/core": "^0.0.22",
    "**/@types/continuation-local-storage": "3.2.1",
    "**/grpc": "^1.24.4",
    "**/grpc-create-metadata": "3.0.0"
  },
  "dependencies": {
    "@axelspringer/graphql-google-pubsub": "^2.1.0",
    "@elastic/elasticsearch": "7",
    "@google-cloud/opentelemetry-cloud-trace-exporter": "^1.0.0",
    "@google-cloud/pubsub": "^2.11.0",
    "@graphql-codegen/cli": "^1.20.1",
    "@graphql-codegen/typescript": "^1.21.0",
    "@graphql-codegen/typescript-resolvers": "^1.18.2",
    "@opencensus/core": "^0.0.22",
    "@opencensus/nodejs": "^0.0.22",
    "@opentelemetry/api": "^1.0.4",
    "@opentelemetry/auto-instrumentations-node": "^0.27.2",
    "@opentelemetry/core": "^1.0.1",
    "@opentelemetry/exporter-jaeger": "^1.0.1",
    "@opentelemetry/exporter-trace-otlp-http": "^0.27.0",
    "@opentelemetry/propagator-grpc-census-binary": "^0.25.1",
    "@opentelemetry/propagator-jaeger": "^1.0.1",
    "@opentelemetry/resources": "^1.0.1",
    "@opentelemetry/sdk-node": "^0.27.0",
    "@opentelemetry/sdk-trace-base": "^1.0.1",
    "@opentelemetry/sdk-trace-node": "^1.0.1",
    "@opentelemetry/semantic-conventions": "^1.0.1",
    "@stackpath/node-grpc-error-details": "^1.0.0",
    "@types/continuation-local-storage": "3.2.1",
    "@zenoss/opencensus-node-exporter": "^0.0.4",
    "apollo-datasource": "^0.9.0",
    "apollo-server": "^2.25.3",
    "apollo-server-express": "^2.18.2",
    "apollo-server-plugin-response-cache": "^0.5.2",
    "bunyan": "~1.8.12",
    "bunyan-gke-stackdriver": "^0.1.2",
    "clone": "^2.1.2",
    "cookie-parser": "^1.4.4",
    "cors": "^2.8.4",
    "dataloader": "^2.0.0",
    "dompurify": "2.0.17",
    "express": "^4.16.2",
    "google-auth-library": "^7.11.0",
    "google-protobuf": "^4.0.0-rc.2",
    "graphql": "^14.0.2",
    "graphql-iso-date": "^3.5.0",
    "graphql-middleware": "^3.0.2",
    "graphql-schema-modules": "^0.0.4",
    "graphql-subscriptions": "^1.2.0",
    "graphql-tools": "^4.0.5",
    "graphql-type-json": "^0.2.0",
    "grpc": "^1.24.4",
    "http": "^0.0.1-security",
    "jsdom": "15.2.1",
    "json-stable-stringify": "^1.0.1",
    "lodash": "^4.17.21",
    "nanoid": "^3.1.31",
    "opencensus-exporter-stackdriver": "zenoss/opencensus-exporter-stackdriver#v0.1.0",
    "pb-util": "^0.1.2",
    "phonetic": "^0.1.1",
    "protobufjs": "^6.8.8",
    "prufer": "^0.0.1",
    "subscriptions-transport-ws": "^0.9.18",
    "url-parse": "1.5.7",
    "workerpool": "^6.1.4",
    "yamr-js": "zenoss/yamr-js#4.6.4",
    "zing-grpc-clients": "zenoss/zing-proto#v11.16.2"
  },
  "devDependencies": {
    "@babel/core": "^7.17.5",
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/plugin-proposal-function-sent": "^7.0.0",
    "@babel/plugin-proposal-json-strings": "^7.0.0",
    "@babel/plugin-proposal-numeric-separator": "^7.0.0",
    "@babel/plugin-proposal-throw-expressions": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/plugin-transform-modules-commonjs": "^7.0.0",
    "@babel/plugin-transform-runtime": "^7.17.0",
    "@babel/preset-env": "^7.16.11",
    "apollo-server-testing": "^2.9.13",
    "babel-eslint": "^9.0.0",
    "babel-loader": "^8.2.3",
    "babel-plugin-istanbul": "^6.1.1",
    "babel-plugin-dynamic-import-node": "^2.3.0",
    "chai": "^4.2.0",
    "clean-webpack-plugin": "^0.1.19",
    "eslint": "^7.19.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-friendly-formatter": "^3.0.0",
    "eslint-import-resolver-webpack": "^0.8.3",
    "eslint-loader": "^2.0.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-mocha": "^9.0.0",
    "html-loader": "^3.1.0",
    "istanbul-instrumenter-loader": "^2.0.0",
    "jsonwebtoken": "^8.5.1",
    "mocha": ">=6 <9",
    "mochapack": "^2.0.6",
    "nyc": "^15.1.0",
    "sinon": "^7.5.0",
    "sinon-chai": "^3.3.0",
    "start-server-webpack-plugin": "^2.2.5",
    "ts-loader": "^8.0.17",
    "typescript": "^4.1.5",
    "webpack": "^4.0.0",
    "webpack-cli": "^4.5.0",
    "webpack-merge": "^5.7.3",
    "webpack-node-externals": "^2.5.2"
  }
}

pic with errors


text:
Q: How to parse Flat File Schema to mulesoft object I have requirement where I need to parse MuleSoft Flat File Schema to parse incoming file content, input file row to parse it and convert to Mule object. It should include parsing of multiple rows in a file with 5-7 attributes per row. I have seen many examples but no one is explaining how can we create flatFile schema to process the flat file in anypoint studio.
Could you please help me for the same.
Input file -
1220612WEBL23555606CA01
200000162608361   FFVV220606D915552982635 4TKTT0140MAZUR/ISWAR APRIL                                             C    YXYYXY    /C9F6R1     MTHO                             DTD 0000
G002389100000000000CAD2070231 0 996AC                              001          RESLE BALANCE
700CAD     0.00            NO ADC      00                                                                                0                                                                                00142152020558 Y262990535
889486594HGMRNL8785   00000000000082204CAD2  CC5  0423                             0423                     000000000020512   00000000000      CAD2  EX                                                                  000000
8002389                   00000000000      CAD2  CA                                                                  00000000000                   00000000000                                                                                00000000000
9002389                                                                                AGT6490/00                                    CASH
Z00625

A: The basic steps are simple:

*

*Define the structure of the file. You need to understand the records
and fields of the file completely.

*Convert that definition into a Flat file schema. Read the documentation, if the file has simple records structure it should be
very direct.

*Use the schema in a DataWeave transformation

Flat file format are usually custom defined. It is very very unlikely that there is a tool to automatically translate it to a flat file definition since they lack delimiters and structure. You will have to read the definition of the structure and create the flat file schema manually. For that you need to understand how the flat files schemas are structured by reading the documentation. They are not complex, but you may want to start with simpler examples until you get the hang of it.


text:
Q: count the number of changes of value in an array I am relatively new in R and I am working with behaviour data of an animal and I am trying to establish the number of times an individual animal change its behaviour in a given time frame (session in this case).
My dummy dataset is as:-
session = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2)
activity = c("V","F","D","F","F","W","V","R","R","S","V","U","W","V","V","V","R","R","R","R")
df = data.frame(session,activity)

I would like to count the number of times that the activity is changed in each session. For example, in session 1 it will be 8 times and in session 2 it will be 5 times.
I have tried options of following other suggestion on the internet to use rle() but I am wondering how I can code it since in most of the cases it will be summing up different modalities in a given array.

A: I found out from a friend that I had to aply the rle to the "activity" column of my df, making sure that this column is a character and not a vector df$activity=as.character(df$activity)
I then applied the function only to the rows of a single session for instance, the rows of session 1:
res<-rle(df[which(df$session==1),2])#rle() function applied to the activity column of df and to the rows of the session 1
length(res$lengths)# will give you the number of changes within a session

but to apply it to the big data set, I could apply it in a loop:
df[,2]=as.character(df[,2])# to treat session as a character
ls.session=unique(df$session)
nb.session=length(ls.session)
new.df=data.frame(ls.session,rep(0,nb.session))#create an empty data.frame where we can apply the loop
names(new.df)=c("session","nb.change")
for(i in 1:nb.session){
res.rle.sess.i=rle(df[which(df$session==ls.session[i]),2])
nb.chang.sess.i=length(res.rle.sess.i$lengths)
new.df[i,2]=nb.chang.sess.i
}
new.df

A: change.f = function(x) c(FALSE, x[-1] != x[-length(x)])
aggregate(change.f(df$activity)&!change.f(df$session), by=list(df$session), FUN=sum)

Output:
  Group.1 x
1       1 7
2       2 4


text:
Q: Svn authorizing over sasl+ldap failing after Ubuntu update 10.04 -> 12.04 I have working svnserve solution on Ubuntu 10.04 for authorizing svn users over SASL to Active directory (LDAP, not LDAPDB). Config files are at the bottom.
After upgrading server to 12.04 release, this does not work anymore.
I can authorize user over SASL to LDAP with
 testsaslauthd -u ldap_username -p his_password
 => 0: OK "Success."

But when i try to "svn update" on folder at the same server, it ask me three times for credentials and end with
 svn: Authentication error from server: SASL(-4): no mechanism available:

I do not know how to track communication between svn and sasl.
Circumstances:

*

*Ubuntu 10.04 + subversion 1.6.6 (with Cirrus SASL  support) => working

*Ubuntu 12.04 + subversion 1.6.17 (with Cirrus SASL  support) => not working (with same configuration)

file  /usr/lib/sasl2/svn.conf
 pwcheck_method: saslauthd
 auxprop_plugin: ldap
 mech_list: PLAIN

file  /usr/lib/sasl2/subversion.conf -> symlink to /usr/lib/sasl2/svn.conf
file  /opt/svn/repos/conf/svnserve.conf
 [general]
 anon-access = none
 auth-access = write
 #password-db = passwd
 authz-db = authz
 realm = smartsvn

 [sasl]
 use-sasl = true
 min-encryption = 0
 max-encryption = 256

Any idea, how to fixit or trace the problem?

A: Had the same problems like above only on debian squeeze after a dist-upgrade. After hours of config, restart and reinstalling madness I gave following "svn.conf" a try:
pwcheck_method: saslauthd
#auxprop_plugin: ldap
mech_list: plain login cram-md5 digest-md5

IMO, "mech_list: plain" should be enough. the other mechs are overlefts from previous tryouts.
Here is my  /etc/saslauthd.conf
ldap_servers: ldap://xxx.xxx.xxx.xxx
ldap_use_sasl:no
ldap_search_base: DC=domain,DC=tdl
ldap_bind_dn: xxxx@domain.tdl
ldap_bind_pw: magic_word:)
ldap_mech: PLAIN
ldap_auth_method: bind
ldap_filter: (sAMAccountName=%U)
log_level: 7

And here my /etc/default/saslauthd
START=yes
DESC="SASL Authentication Daemon"
NAME="saslauthd"
MECHANISMS="ldap"
MECH_OPTIONS=""
THREADS=5

Update Dez 14:
Today I had the same issue again after an svnserve upgrade (r1615264):
I had to add the following to the svn.conf:
ldapdb_uri: ldap://myldadphost.tld

Don´t ask me why, I just tried it, because three or four years ago the param was already  (with other ldap params) in the svn.conf...

A: (1) In /etc/sasl2/svn.conf you can set a log level for saslauthd like:
log_level: 7

In sasl.h I found:
#define SASL_LOG_NONE  0    /* don't log anything */
#define SASL_LOG_ERR   1    /* log unusual errors (default) */
#define SASL_LOG_FAIL  2    /* log all authentication failures */
#define SASL_LOG_WARN  3    /* log non-fatal warnings */
#define SASL_LOG_NOTE  4    /* more verbose than LOG_WARN */
#define SASL_LOG_DEBUG 5    /* more verbose than LOG_NOTE */
#define SASL_LOG_TRACE 6    /* traces of internal protocols */
#define SASL_LOG_PASS  7    /* traces of internal protocols, including passwords */

It seems it logs to /var/log/auth.log.
I have almost the same problem (migrating from Ubuntu 11.04 to 12.04) and get in auth.log:
svnserve: could not find auxprop plugin, was searching for 'ldap'

Interestingly, the log says "svnserve" and not saslauthd. Which lead me to ...
(2) You could try
ldd /usr/bin/svnserve

For me, the working server (Ubuntu 11.04) shows:
libldap_r-2.4.so.2 => /usr/lib/libldap_r-2.4.so.2

but the failing server (12.04) does not.

A: Try changeing configuration to your /usr/lib/sasl2/svn.conf config file (SVN sasl configuration):
auxprop_plugin: ldapdb
mech_list: PLAIN
ldapdb_mech: PLAIN
saslauthd_path: /var/run/saslauthd/mux
ldapdb_uri: <address of your ldap server (ldap://hostname)>


text:
Q: MSSQL update set from output clause Context
I got a temporary table which is filled/adjusted by users. Let's call the table tmp, with columns ID, updated_at, price, foreign_ID. Every time the user enters a new price, the price column is filled and the updated_at and ID are created automatically. foreign_ID is NULL until the record is processed to another table, when my foreign_ID should contain the ID of the other table.
Periodically I update a table with prices, let's call it prices. Here are all prices stored from different sources, among them from the tmp table. The prices table has the columns ID, updated_at, price.
question
I want to insert the data from my tmp table into prices table, and update the column foreign_ID with the corresponding ID from my prices table. How can I insert new rows in a table and update/set a IDs in another table?
My desired result after the periodic update is a new entry in the prices table with the new prices which were not yet processed, and a foreign_ID in my tmp table which corresponds with the ID in my prices table.
I know I can output the inserted IDs using the following query:
insert into prices
output inserted.ID
select price
from tmp;

I'm struggling to see how I can use the inserted.ID to update my tmp.foreign_ID column with the output above.
Help is appreciated!

A: You can also INSERT the values from the OUTPUT clause into another table as well, so if you need those you can still reference them.
Without proper sample data and behaviour, this is just an example but should, hopefully, set you on the right path as it shows you how to get the values from inserted into another object. You can then use that object to do the additional task(s) you need:
CREATE TABLE dbo.SomeTable (ID int IDENTITY(1,1),
                            SomeString varchar(10));
GO

DECLARE @IDs table (ID int);

INSERT INTO dbo.SomeTable (SomeString)
OUTPUT inserted.ID
INTO @IDs (ID)
VALUES('asdjgkde'),('sdflhdglf');

SELECT *
FROM @IDs;
GO

DROP TABLE dbo.SomeTable;


text:
Q: WCF MTOM attachment how to set content-type I need to set a specific content type(application/pdf) for the binary part in an MTOM configured binding.
Is there anything in the config or in code I can do to have the content type set? For the filepart it's always "Content-Type: application/octet-stream"
Config:
<binding name="FileTransferServicesBinding"
 closeTimeout="00:01:00" openTimeout="00:01:00"
 receiveTimeout="00:10:00" sendTimeout="00:01:00"
 messageEncoding="Mtom" transferMode="Buffered"
 maxBufferSize="67108864" maxReceivedMessageSize="67108864">
 <security mode="Transport" />
</binding>

What's currently sent to the service. The multipart header for the file should be application/pdf instead of application/octetstream
POST https://somewebservice HTTP/1.1
MIME-Version: 1.0
Authorization: Basic authhash
SOAPAction: ""
Host: webservicehost
Content-Length: 24517
Expect: 100-continue
Accept-Encoding: gzip, deflate

--uuid:b8366a06-3ecc-4bc4-9809-8c87ad459981+id=1
Content-ID: <http://tempuri.org/0>
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Header>[The soapmessageitself]</s:Envelope>
--uuid:b8366a06-3ecc-4bc4-9809-8c87ad459981+id=1
Content-ID: <http://tempuri.org/1/636787311873257476>
Content-Transfer-Encoding: binary
Content-Type: application/octet-stream // This must be application/pdf

%PDF-1.4
%
1 0 obj
<</Type /Catalog/Pages 2 0 R>> ...

A: As time grew short I solved this issue by manually constructing the soap call. As there is a bounty on this question I'll mark the answser that does the same but using the WCF libraries as the correct answer. Code sample below starring "byteContent.Headers.Add("Content-Type", "application/pdf; name=test.pdf");" what I needed to do with WCF
static HttpClient client;
static object mutex = new object();
static HttpClient Client
{
    get
    {
        if (client == null)
        {
            lock (mutex)
            {
                if (client == null)
                {
                    client = new HttpClient();
                    client.DefaultRequestHeaders.Add("MIME-Version", "1.0");
                    client.DefaultRequestHeaders.Add("SOAPAction", "\"\"");
                    client.DefaultRequestHeaders.ConnectionClose = true;
                    client.DefaultRequestHeaders.ExpectContinue = false;
                    client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Username + ":" + Password)));
                }
            }
        }

        return client;
    }
}

public static TResponse Send<TResponse>(string endpoint, string payload, byte[] file)
{
    string boundary = Guid.NewGuid().ToString("N");
    MultipartContent multipart = new MultipartContent("related", boundary);

    multipart.Headers.Remove("Content-Type");
    multipart.Headers.TryAddWithoutValidation("Content-Type", "multipart/related; boundary=\"" + boundary + "\"");
    multipart.Add(new StringContent(payload, Encoding.UTF8, "text/xml"));

    ByteArrayContent byteContent = new ByteArrayContent(file);
    byteContent.Headers.Remove("Content-Type");
    byteContent.Headers.Add("Content-Type", "application/pdf; name=test.pdf");
    byteContent.Headers.Add("Content-Transfer-Encoding", "binary");
    byteContent.Headers.Add("Content-ID", "<test.pdf>");
    byteContent.Headers.Add("Content-Disposition", "attachment; name=\"test.pdf\"; filename=\"test.pdf\"");

    multipart.Add(byteContent);

    var result = Client.PostAsync(endpoint, multipart).Result;
    result.EnsureSuccessStatusCode();

    var resultString = result.Content.ReadAsStringAsync().Result;
    TResponse resultTyped = XmlHelper.ToObject<TResponse>(resultString);
    return resultTyped;
}

A: I'm having to guess that you're encoding a response to a request. If so, you just need to add the content type header to your outgoing message:
OperationContext
  .Current
  .OutgoingMessageHeaders
  .Add ("Content-Type", "application/pdf" );

Not 100% sure, but you may need to clear any existing outgoing Content-Type header, first. I don't think it matters that your message is MTOM-encoded. That is theoretically transparent.
Also...just asking...why allow a 64MB buffered message when a streamed message takes so much less memory to transfer...and is likely to be just as fast or faster? You're pretty much guaranteed better performance in a heavily loaded service.
Update:
If you're lucky enough to be using a web api-type of binding (WebHttpBinding)...you can stream out your content pretty easily, specifying the content type. It's not that different than what I'd put in my answer above, but as you'd replied, those headers go to the wrong place.
Instead, it should be:
WebOperationContext
  .Current
  .OutgoingResponse
  .ContentType = "application/pdf";

There's a fantastic article/example here that fully develops the idea...in a way consistent with your objectives.
If you're bound to an older soap binding, then you probably need is to write a custom message encoder. The technique is straightforward enough (if tedious). The basic idea is that you can take control of writing the body of the message in ways that are appropriate to your needs.
The encoder itself is trivial. The boilerplate that goes around it will be the tedious part. A custom encoder derives from the abstract  MessageEncoder. The important things to do are to override the ContentType, MediaType, MessageVersion properties and the ReadMessage and WriteMessage methods. There are variations of the ReadMessage and WriteMessage methods for dealing with streamed and buffered messages.
The ugly part is the boilerplate that you have to write to deploy your encoder. You have make an encoder factory, and a custom binding element. Not 'orrible, but noisy. There's a couple of examples of the whole ball of wax (including the factory and binding element support) in the in the example code package here...which can save you some time.


text:
Q: Conditions for convergence of fixed-point iterations (not necessarily to a unique fixed-point) Let $X \in R^n$ be a compact convex set, and $f:X \to X$ be a continuous function. Then, can we say that from all $x_0 \in X$, the fixed-point iterations $x_{k+1}=f(x_k)$ to converge to some fixed-point $\bar{x}(x_0) \in X$?
If not, what are the conditions that $f$ must satisfy such that the iterations $x_{k+1}=f(x_k)$ always converge to some fixed-point $\bar{x}(x_0) \in X$ starting from any $x_0 \in X$?
Please note that the fixed-point $\bar{x}(x_0)$ need not be unique.
If I understand correctly, the Brouwer fixed-point theorem states that there exists atleast one $\tilde{x} \in X$ satisfying $\tilde{x} =f(\tilde{x})$, but does it say something about the convergence of fixed-point iterations?

A: That's not true. For example, let $X$ be the closed unit ball and $f$ be a non-trivial rotation. Then unless $x_0$ is the origin (which is the unique fixed point of $f$), the sequence $x_{k+1} = f(x_k)$ is not convergent.
Of course if $f$ is a contraction, then any such sequence converges to the unique fixed point.

A: Similar to Arctic Char's answer.
No. What about $\ X=\ $ unit circle in $\ \mathbb{R}^2\ $ and $\ f\ $ is reflection in the $\ y-$axis. $\ X\ $ is compact and convex, and $\ f\ $ is continuous. However, $\ f\ $ repeatedly acting on  $\ x_0=(0,-1)\ $ looks like: $\ (0,-1)\to(0,1)\to (0,-1)\to(0,1)\to\ldots\ $ which does not converge.


text:
Q: how do I add to a total if an operation is repeated over and over by a user in VB? Ok so I have a simple maze game and i'm trying to make it so that when the user wins, a random number of points between 1-7 is generated, which to be clear I got to work. What I can't figure out is when the user resets the game I want the points to stay displayed until the user wins again. When the user wins, I want another number between 1-7 to be added to the previous number, again and again. How do I add to a previous number?

A: Public Sub Form4_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    Dim r As New Random
    Dim r2 As New Random

    Dim randoms1 = r2.Next(1, 20)
    Dim randoms = r.Next(1, 7)
    Integer.TryParse(Label3.Text, total)

    If PictureBox2.Bounds.IntersectsWith(finishLabel.Bounds) Then
        Label3.Text = 0
        Label3.Text = total + randoms
        total = Label3.Text
        PictureBox2.Location = New Point(350, 30)
    ElseIf Nothing Then

finally got it to work, here was what I was looking for.


text:
Q: Add Column to table with jQuery Is it possible to add a column to an existing table like this:

with js?

A: you can do like this
 $('#tutorial').find('tr').each(function(){
        $(this).find('td').eq(n).after('new cell added	');
   });

n can be replaced by the number after which column you want to add new column

A: You mean column not row?
$('#tutorial tr').each(function()
{
    $(this).append('	');
});

Which selects the
 element inside id "tutorial" (that is your table is this case) and append new contents behind its original contents

A: You can use .append() to append a new td to the rows
$('#tutorial tr').append('new	')

Demo: Fiddle

A: An alternative option to those above is to create the column together with the other and a style of display:none; and then using the method .Show() to display.


text:
Q: How to stop Grommet component from looping in Safari I created a dynamic editor component with Grommet in my header and footer tabs. When the site is viewed in safari, each editor is changing its position when I make a change in the data like font size. It is an issue only in safari: it works normal in Chrome and Firefox on Macintosh, windows, and Linux.
It also doesn't occur in safari Big Sur, but it does in previous versions of mac, like Catalina and High Sierra.
Here is my code and a screenshot of the component:
{toPairs(footerTexts).map(
  ([key, text]) =>
    text !== undefined && (
      <Box
        id={text.id}
        key={text.id}
        style={{
          height: 132,
          width: 500,
          paddingTop: 20,
        }}
      >

A: Try to see if replacing the styles with actual grommet props does the the trick, and on top of it, just to seal it off a little more, see if adding flex={false} does the trick as follows:
{toPairs(footerTexts).map(
  ([key, text]) =>
    text !== undefined && (
      <Box
        id={text.id}
        key={text.id}
        height="132px"
        width="500px"
        pad={{top: "20px"}}
        flex={false}
      >

A: I fixed it by adding a sorter, such that the sorter function sorts the object by the time it was created, basically, the issue was where I update the state
{toPairs(headerTexts)
    .map(([, text]) => text)
    .sort(sorter)
    .map(
      (text) =>
        text !== undefined && (
            <Box
              key={text.id}
              style={{
                width: 500,
                marginTop: 20,
              }}
            >

Updating the state will push the updated object to the end of the object so the one editor that is updated now will go to the bottom of the object, that's why it was looping.
const updateTextFooter = (text, key) => {
    if (key !== "") {
      setFooterTexts({
        ...footerTexts,
        [key]: {
          ...footerTexts[key],
          text,
        },
      });
    }
  };

to fix this issue this is the sorter that i added
const sorter = (a, b) => {
    const first = a.createdAt;
    const second = b.createdAt;
    let comparison = 0;
    if (first > second) {
      comparison = 1;
    } else if (first < second) {
      comparison = -1;
    }
    return comparison;
  };

Thank you all for the help, feels good to be in here.


text:
Q: Selenium Webdriver-Unable to find any element inside second child iframe(having dynamic name) ![Child frames are having dynamic name/id][1]
Browser-IE8
I have to find a prompt box inside the second child iframe.
the parent iframe is having fixed id.Able to find element inside that
using driver.switchTo().frame(0)
The first child iframe is having dynamic name/id.
cframe_ms_id59 .Only last part changes.i.e. id59
I am able to find this element using xpath
driver.findElement(By.xpath("//iframe[contains(@id, 'cframe_ms']"))
But my prompt box having a textbox resides in the Second Child iframe (green color )****having dynamic name/id.**I am not able to enter inside this iframe and not able to find any element inside that.
Plz suggest some solution

Here is the HTML code structure-

    **//Parent Iframe-Able to
      |                       find this iframe using          driver.switchto().frame(0)**
      |------

                |                   ------code----
                |                   ------------code---
                |------------  **//first child iframe last part of name and id changing dynamically**
                |                    -------------
                |                     ------------
                |------------- <table class="mdiwindow" id =dwindow_ms_99"
                                        |

                                        |---
                                               |-- **//Second child iframe  last part of name and id changing dynamically.IFrame where our text box of prompt box resides**                                  |
                                                      |------------
                                                      | -----------------
                                                      |-----  <input name=balance_val class="x27" id="balance_val>**//textbox**

A: i think it's usefull for you.
get xpath from child frame before type this code line -

driver.switchTo().frame(1);

than you switch to child frame so you get easily xpath or class/id of child frame elements.
back to default frame type this code line -

driver.switchTo().defaultContent();

where is your attached screenshot ??

A: Looking at the HTML, you seem to have an iframe inside an iframe inside an iframe which contains the input you want to find. For this you need to switch into frames sequentially. See below for C# code.
var textbox = driver.SwitchTo()
                .Frame("adviseDesktop")    //control in frame with id="adviseDesktop"
                .SwitchTo()
                .Frame(1)                  //control in frame with id="cframe_ms_id54"
                .FindElement(By.Id("balance_val")); //input with id="balance_val"

Once you are done with the actions in that frame, you need to switch out to default content.
    //control in frame with id="cframe_ms_id54"
    _driver.SwitchTo()
                     .ParentFrame() //control in frame with id="adviseDesktop"
                     .SwitchTo()
                     .DefaultContent(); //control in topmost body of the document


text:
Q: Start MySQL Server as a service (Win 8) I am trying out MySQL (Windows 8), with the workbench (gui) installed as well.
I am still in the installation / configuration process. I would like to create a new database. So, on the workbench's welcome screen, I have selected New Server Instance- Register a new Server instance to manage.
In order to do this, I have went through following configuration steps:

*

*Specify localhost as server host,

*Give it the username and password I am using.
It then tests a database connection, and, in the next step, asks me to

Select the Service to manage from the list below.
  It will also help find the configuration file.

However, the list of possible Services is empty and if I click [next], it says

Error: In Order to manage a MySQL Service it must be installed as a Service. The wizard can not find any MySQL Service at the target machine, so the Server instance cannot be started.

I think that I have to somehow start the MySQL Service, as it might already been installed when I had installed the whole MySQL Toolset.
So: How would I start this MySQL Service under Windows 8?
Some things I've tried:
The Manual says to try:
C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld"

in order to install it as a Service.  Yet, nothing happens and I get the following (some verbose [Note]s were removed):
2013-04-13 23:44:22 0 [Warning] TIMESTAMP with implicit DEFAULT value is depreca
ted. Please use --explicit_defaults_for_timestamp server option (see documentati
on for more details).
2013-04-13 23:44:22 2592 [Warning] Can't create test file c:\Program Files\MySQL
\MySQL Server 5.6\data\gast.lower-test
2013-04-13 23:44:22 2592 [Warning] Can't create test file c:\Program Files\MySQL
\MySQL Server 5.6\data\gast.lower-test
[...]
2013-04-13 23:44:22 2592 [ERROR] InnoDB: read can't be opened in .\ibdata1 mode
2013-04-13 23:44:22 2592 [ERROR] InnoDB: The system tablespace must be writable!

2013-04-13 23:44:22 2592 [ERROR] Plugin 'InnoDB' init function returned error.
2013-04-13 23:44:22 2592 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGIN
E failed.
2013-04-13 23:44:22 2592 [ERROR] Unknown/unsupported storage engine: InnoDB
2013-04-13 23:44:22 2592 [ERROR] Aborting

2013-04-13 23:44:22 2592 [Note] Binlog end
[...]
2013-04-13 23:44:22 2592 [Note] mysqld: Shutdown complete

To install the server as a service, I've used this command (per the manual).
C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --install

Again, "nothing" happens, I get (again, most of the verbose [Note]s are removed):
Install/Remove of the Service Denied!

c:\Program Files\MySQL\MySQL Server 5.6\bin>mysqld -p --install
2013-04-13 23:43:24 0 [Warning] TIMESTAMP with implicit DEFAULT value is depreca
ted. Please use --explicit_defaults_for_timestamp server option (see documentati
on for more details).
2013-04-13 23:43:24 3764 [Warning] Can't create test file c:\Program Files\MySQL
\MySQL Server 5.6\data\gast.lower-test
2013-04-13 23:43:24 3764 [Warning] Can't create test file c:\Program Files\MySQL
\MySQL Server 5.6\data\gast.lower-test
[...]
2013-04-13 23:43:24 3764 [ERROR] InnoDB: read can't be opened in .\ibdata1 mode
2013-04-13 23:43:24 3764 [ERROR] InnoDB: The system tablespace must be writable!

2013-04-13 23:43:24 3764 [ERROR] Plugin 'InnoDB' init function returned error.
2013-04-13 23:43:24 3764 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGIN
E failed.
2013-04-13 23:43:24 3764 [ERROR] mysqld: unknown option '-p'
2013-04-13 23:43:24 3764 [ERROR] Aborting

2013-04-13 23:43:24 3764 [Note] Binlog end
[...]
2013-04-13 23:43:24 3764 [Note] mysqld: Shutdown complete

A: I have the same Problem. I started the Command Prompt in administrator mode and then went to C:> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" and then just Enter. And it works fine.
Second way: While installing the mysql workbench it ask for username and password. By default username is root so if you have set password and still remember it then start MySQL Command Line Client and enter the password and then start the workbench. It will work fine.
Hope this may help you.

A: Type cmd in start and right click and Run as administrator,
then paste the below text in your command prompt,
"C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin\mysqld" --install

If you don't run cmd as Administrator, you'll see Install/Remove of service denied.,
So run the elevated command prompt(Start->cmd->Run as Administrator) to see the Service Successfully installed message.

Note: This is even if you have logged in as administrator in windows 7/8.
If u want to uninstall the service do the following, copy paste the following in command prompt(again elevated command prompt) run this,
sc delete MySQL
Here MySQL in the command is the service name mysql creates by default in Windows PC. Make sure you see the service is installed in the Services List(Task Manager -> Services Tab -> Check the Mysql service Name column).

A: Hans, first of all, the MySQL installer should install the new server as service already. There's no need for you to do this manually. Look in your services list if you already see the service there. Did you get an error message in the MySQL Installer when it came to server/service installation?
Another point is that the server cannot start up as you can see in the log output. Something is seriously wrong with the InnoDB storage. Did you change the configuration somehow? Keep in mind that MySQL data must not be written in the application folder, but in the application data path. By default the MySQL Installer should also take care of this.
And finally, if you start MySQL Workbench with no connections/server instances it will scan the services to find existing MySQL servers and auto create connections and instances for them.

A: That's how I install mysqld:
"e:\denwer\usr\local\mysql-1-5.5\my.ini" --install "mysqld" --defaults-file="e:\denwer\usr\local\mysql-5.5\my.ini"

Also I ran command prompt as administrator.


text:
Q: file_get_contents funciona en ciertas paginas y en otras no Saque este codigo para probarlo en una parte mas entendible  (puesto que viene de otras funciones y archivos) y noto que funciona el file_get_contents en ciertas paginas pero no en todas.
Lo que hace es extraer un archivo pdf de la pagina del DOF, para sacar el tipo de cambio dependiendo de cuantos registros no se hayan actualizado, el problema es que la pagina niquiera la lee: https://dof.gob.mx/indicadores_detalle.php?cod_tipo_indicador=158&hfecha=15/02/2023&dfecha=15/02/2023&accionI=imprimir
<?php
 ini_set('display_errors', 1);
 ini_set('log_errors', 1);
    $fromD = "15/02/2023";
    $toD = "15/02/2023";
    echo $fromD;
    echo $toD;
    ini_set('default_socket_timeout' , 2);
    $ratediario = array();
    /*$ctxtc = stream_context_create(array('http'=>
        array(
            'timeout' => 10,  //10 Seconds tiempo de carga para el servicio
        )
    ));*/
    $archivo = 'http://dof.gob.mx/indicadores_detalle.php?cod_tipo_indicador=158&hfecha='.$toD.'&dfecha='.$fromD.'&accionI=imprimir';
    echo "
";
    echo $archivo;
    echo "
";
    $xml = @file_get_contents($archivo);
    echo $xml;
    $moneda=substr($xml,strpos($xml,''));
    $resdiario = explode('',$moneda);

    for ($elem=1;$elem<count($resdiario);$elem++) {
        $ratediario[$elem]['date'] = substr($resdiario[$elem],0,10);
        $ratediario[$elem]['rate'] = substr($resdiario[$elem],strpos($resdiario[$elem],'class="txt">')+12,9);

    }
    var_dump($ratediario);

?> ```

Ya probe con diferentes paginas como wikipedia, la documentacion oficial de php e inclusive la pagina del SAT pero solo con la del DOF no funciona


text:
Q: Easy proof of $\mathcal{P}(\mathbb{Q})$ is uncountable [Big list] I'm looking for a easy proof of  uncountability of $\mathcal P(\mathbb Q)$. I'll contribute with this:

Let $\mathcal{P}(A)$ denote the power set of  $A$, since $\mathbb{N}\subset\mathbb{Q}\Rightarrow\mathcal{P}(\mathbb{N})\subset\mathcal{P}(\mathbb Q)$ let be $f:\mathcal{P}(\mathbb{N})\to\mathcal{P}(\mathbb Q)$ such $A\mapsto A$. then $f$ is injective and since $\mathcal{P}(\mathbb{N})$ is uncountable, then $\mathcal{P}(\mathbb Q)$ is uncountable

A: For each real number $x$ pick a strictly increasing sequence $x_n$ of rationals converging to $x$.
Then
$$f(x)=\{ x_n| n \}$$
is a one to one function from $\mathbb R$ to $P(Q)$. As $\mathbb R$ is uncountable....

A: Define $f : \mathbb{R} \to \mathcal{P}(\mathbb{Q})$ as $f(x) = (-\infty, x) \cap \mathbb{Q}$. It is injective, so $|\mathbb{R}| \leqslant |\mathcal{P}(\mathbb{Q})|.$

A: Follows directly by Cantor's Theorem.
(Note that you asked a proof that $\mathcal{P}(\mathbb{Q})$ is uncountable, not that its cardinality is the same of $\mathbb{R}$)

A: By transfinite induction, I will show that every countable ordinal $\alpha$ there is a set of rationals $S_\alpha\subseteq (0,1)$ which has order type $\alpha$. Then we will have $\omega_1$ clearly distinct sets of rationals.
For $S_0$ we can (indeed, we have to) take an empty set. For set $S_{\alpha+1}$ we can take $\frac{1}{2}S_\alpha\cup\{\frac{1}{2}\}$, where $\frac{1}{2}S_\alpha=\{\frac{1}{2}x:x\in S_\alpha\}$.
Now if $\alpha$ is sum of countably many ordinals $\beta_i$ (some of which could be 0) then we could take $S_\alpha=\frac{1}{2}S_{\beta_1}\cup\frac{1}{4}S_{\beta_2}+\frac{1}{2}\cup\frac{1}{8}S_{\beta_3}+\frac{1}{4}\cup...$ where $aS_\beta+b=\{ax+b:x\in S_\beta\}$.


text:
Q: Angular 2 and webpack, import images with [src] syntax Im trying to import a picture in my angular 2 application like this:
<img *ngIf="person.status" [src]="{{IMAGE_URL}}" width="20" height="20" />

But when I use the [src] tag webpack doesn't include the picture in the output files of my bundled project. If I include the picture in the following way, everything works as expected.
<img *ngIf="person.status" src=require('IMAGE_URL') width="20" height="20" />

My webpack config looks like this(it's based on the webpack tutorial found in the angular 2 offical docs):
module.exports = {
  entry: {
    'polyfills': './app/polyfills.ts',
    'vendor': './app/vendor.ts',
    'app': './app/main.ts'
  },

  resolve: {
    extensions: ['', '.js', '.ts']
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['ts', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=./assets/[name].[hash].[ext]'
      },
      {
        test:/\.scss$/,
        exclude: /node_modules/,
        loader:'style!css!sass'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw'
      },
      {
        test:/\.json$/,
        exclude: /node_modules/,
        loader:'json'
      }
    ]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'app/index.html'
    })
  ]
};

The reason why I want to use [src] is that the picture is changing dynamically during runtime and the url has to be able to change. Do anybody know how I can configure webpack to include pictures imported in my application with the [src] tag?

A: Put the require() statement in your component file:
ngOnInit(): void {
    this.IMAGE_URL = require('../../public/images/' + this.imageName + '.png');
}

then your can write your html the same way:
<img *ngIf="person.status" [src]="{{IMAGE_URL}}" width="20" height="20" />


text:
Q: Same name for function and method, cannot call the former within the latter I'm trying to use the same method name for both a function and a method (a function of an object) and calling the function from inside the method. However, the function does not get called at all. These are the relevant bits of the function:
function post(url, data, success, error) {

  console.log("Sending");      // This doesn't get even called

  var request = new XMLHttpRequest();      // Nor a request is made

  // ... (more code here)
  }

And the relevant bits of the method
function u(parameter) {

  // ... more code here

  this.post = function(success, error) {     // post request

    this.on("submit", function(e) {     // Loop through all the nodes

      e.preventDefault();     // Stop the browser from sending a request

      console.log("Going to send your data");     // This works

      post(u(this).attr("action"), u(this).serialize(), success, error);     // Post the actual data

      console.log("Got here");     // Well it's async, but it also gets here
      });

    return this;
    }

  return this;
  }

It is supposed to be called from this script when the form is sent:
u("form").post(function(){
  alert("Yay, it worked");
  }, function(){
  alert("Something went wrong");
  });

It successfully calls the method and both of the messages are shown. However, the Sending from the function is NOT logged and no request is performed. I'm thinking either a problem with scope or with the function name being overwritten, but I'm not an expert here so any help would be appreciated. Why is the function post() not being called?. There's absolutely no error shown in the console.
After some testing, I can confirm the problem is that they share the name. So, how could I have the same name shared for a method and a function? The method would only be called like u("form").post(callA, callB); and the function like post(url, data, callA, callB)l;

A: It's your call of the u function that is problematic. You forgot the new keyword, which made the this context be the global scope object - on which you then are overwriting the global post variable.
Two fixes:

*

*Use (new u("form")).post(…); or make your constructor new-agnostic

*Don't put the post function in the global scope. Use the module pattern.


text:
Q: Poor performance using conditional where clause in Sybase I have the following SQL I am trying to execute in Sybase. In SQL Server, these types of queries are standard, but the performance makes this unusable in Sybase.
DECLARE
    @pMEME_FIRST_NAME char(100),
    @pMEME_LAST_NAME char(100)

SET @pMEME_FIRST_NAME = 'Lisa'
SET @pMEME_LAST_NAME = 'Spivey'

    SELECT TOP 1 CMC_MEME_MEMBER.MEME_FIRST_NAME,
        CMC_MEME_MEMBER.MEME_LAST_NAME,
        CMC_MEME_MEMBER.MEME_SEX,
        CMC_MEME_MEMBER.MEME_SFX,
        CMC_SBSB_SUBSC.SBSB_ID,
        CMC_MEME_MEMBER.MEME_REL,
        CMC_SBAD_ADDR.SBAD_ADDR1,
        CMC_SBAD_ADDR.SBAD_ADDR2,
        CMC_SBAD_ADDR.SBAD_CITY,
        CMC_SBAD_ADDR.SBAD_STATE,
        CMC_SBAD_ADDR.SBAD_ZIP,
        CMC_GRGR_GROUP.GRGR_ID,
        CMC_GRGR_GROUP.GRGR_NAME,
        CMC_MEME_MEMBER.MEME_SSN,
        CMC_MEME_MEMBER.MEME_BIRTH_DT,
        CMC_MEME_MEMBER.MEME_CK,
        CMC_MEME_MEMBER.SBSB_CK,
        CMC_MEME_MEMBER.GRGR_CK,
        CMC_MEME_MEMBER.MEME_FAM_LINK_ID
    FROM CMC_MEME_MEMBER CMC_MEME_MEMBER
        INNER JOIN CMC_SBSB_SUBSC CMC_SBSB_SUBSC
        ON CMC_MEME_MEMBER.SBSB_CK = CMC_SBSB_SUBSC.SBSB_CK
        AND CMC_MEME_MEMBER.GRGR_CK = CMC_SBSB_SUBSC.GRGR_CK

        INNER JOIN CMC_SBAD_ADDR CMC_SBAD_ADDR
        ON CMC_MEME_MEMBER.SBSB_CK = CMC_SBAD_ADDR.SBSB_CK
        AND CMC_MEME_MEMBER.GRGR_CK = CMC_SBAD_ADDR.GRGR_CK

        INNER JOIN CMC_GRGR_GROUP CMC_GRGR_GROUP
        ON CMC_MEME_MEMBER.GRGR_CK = CMC_GRGR_GROUP.GRGR_CK
    WHERE (@pMEME_FIRST_NAME IS NULL OR (CMC_MEME_MEMBER.MEME_FIRST_NAME = @pMEME_FIRST_NAME))
    AND (@pMEME_LAST_NAME IS NULL OR (CMC_MEME_MEMBER.MEME_LAST_NAME = @pMEME_LAST_NAME))
--    WHERE ((CMC_MEME_MEMBER.MEME_FIRST_NAME = @pMEME_FIRST_NAME))
--    AND ((CMC_MEME_MEMBER.MEME_LAST_NAME = @pMEME_LAST_NAME))

If I take out one of the IS NULL checks, the query runs in milliseconds.
Any ideas?


text:
Q: Incompatible block pointer types sending 'void (^__strong)(__strong id)' to parameter of type 'swizzleBlock' (aka 'void (^)(void)') Trying to fix issues with FBSDKEventBindingManager.m error for few days but still having hard time to find solution.
Error:

Incompatible block pointer types sending 'void (^__strong)(__strong id)' to parameter of type 'swizzleBlock' (aka 'void (^)(void)')

Error in this line => withBlock:blockToSuperview named:@"map_control"];
void (^blockToSuperview)(id view) = ^(id view) {
    [self matchView:view delegate:nil];
};

void (^blockToWindow)(id view) = ^(id view) {
    [self matchView:view delegate:nil];
};

[FBSDKSwizzler swizzleSelector:@selector(didMoveToSuperview)
                       onClass:[UIControl class]
                     withBlock:blockToSuperview named:@"map_control"];

[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow)
                       onClass:[UIControl class]
                     withBlock:blockToWindow named:@"map_control"];

A: The problem is where FBSDK using typedef for swizzleBlock
typedef void (^swizzleBlock)();

This can be explained like
typedef void (^swizzleBlock)(void); //void (^)(void) format
Line 24 here:
And the parameter being passed is of type
void (^blockToSuperview)(id view) = ^(id view) // void (^__strong)(__strong id)'

Which leads to type mismatch and showing you error

Incompatible block pointer types sending 'void (^__strong)(__strong id)' to parameter of type 'swizzleBlock' (aka 'void (^)(void)')

Refer this, it will helps you to understand the Objective-C block syntax at various points.
You should update the typedef to match the passing block.
typedef void (^swizzleBlock)(id);

Fixing, this will fix the error at a point, but in the same file there are many other types of block with different format, e.g tableViewBlock(line 185), collectionViewBlock(line 200) checkout here. so, you will have to look for some generic workaround to fix it.
Hope it helps.


text:
Q: c++ assignment operator overloading Hello everyone i'm trying to write an assignment operator for this class so i can assign an array like thisint[] = {0, 1, 2, 3} to my Tableau class
originally i wanted to do this
Tableau<T>& operator=(T arr[])
{
 return Tableau(tab, sizeofarray);
}

because i already wrote a constructor that takes and array and the size as its argument
and i ran into a problem with the size of the the array i don't know how to find it
how can i find the size of the array or is there a better way to do this
template<typename T>
class Tableau
{
public:
Tableau(int s = 0) : size(s), ptr(new T[size])
{
    for (int i = 0; i < size; i++)
    {
        ptr[i] = 0;
    }
}
Tableau(T tab[], int s = 0) : size(s), ptr(new T[size])
{
    for (int i = 0; i < size; i++)
    {
        ptr[i] = tab[i];
    }
}

~Tableau()
{
    delete[] ptr;
}
Tableau<T>& operator=( T tab[])
{

}
T commule()
{
    T com = 0;
    for (int i = 0; i < size; i++)
    {
        com += ptr[i];
    }
    return com;
}
T& operator[](const int index)
{
    return ptr[index];
}
private:
int size;
T* ptr;
};

int main()
{
int k[] = { 8, 12, 5, 9, 55};
Tableau<int> TI(k, 2);
TI = k;
return 0;
}

A: You can use:
template <std::size_t N>
Tableau<T>& operator=(T (&arr)[N])
{
    // This is not right.
    // The returned value is a temporary.
    // return Tableau(arr, N);

    // Update the contents of the object.

    // ...

    // Then, return a reference to this object.
    return *this;
}

With that member function template, when you invoke:
int k[] = { 8, 12, 5, 9, 55};
Tableau<int> TI(k, 2);
TI = k;

The operator= function is instantiated with N = 5 and k as the value of arr. Hence, you get the size of the array as well as the contents of the array.
However, it is worth pointing out that if you use:
int k[] = { 8, 12, 5, 9, 55};
int* k2 = k;
Tableau<int> TI(k, 2);
TI = k2;

it won't work. k2 is not an array. It is a pointer to an int, which happens to point to the first element of k.


text:
Q: Need to display list of followers information I am a ruby on rails beginner.
I have two models with one-to-many relationships and i want to get followers_id from relationships model and display the followers information
model1

Users  -> has_many
id firstname lastname....
 1    sample

model2

Relationships -> belongs_to
user_id follower_id following_id
 1         2
 1         3

I have tried using 'pluck' method of rails in (rails console)
u  = Users.find(1)

r  = u.relationships.pluck(:follower_id)
//gives me a array of id

But I don't know how to use these arrays of ids to get followers info(firstname,lastname)
Could someone please guide me..
Is there any better way to get followers info.
Thanks in advance :)

A: Ok, what You basically need is to connect Users with Followers through Relationships this is done like this:
class User < ActiveRecord::Base
  has_many :relationships
  has_many :followers, through: :relationships
end

class Relationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :follower
end

After that You can just do user.followers

A: Based on Your Model relationship
@user  = Users.find(1)

@follower_ids  = @user.relationships.pluck(:follower_id)

You get all the follower ids in @followers_ids
@followers = User.where("id in (?)", @followers_id)

You get all information of followers inside @followers variables


text:
Q: Create column in dataframe that divides number by days in a month I have a Panda's DataFrame with a column of months and a column that gives a total for each month. What I need to do is divide the total for each month by the number of days in that month and put it in a new column.
So something like this
Month          Total        Daily Total
Nov. 2019      45345
Dec. 2019      87493
Jan. 2020      45765
Feb. 2020      38756

How do I do this? How do I know how many days are in a given month using Python? Thanks

A: You can use .dt.daysinmonth
df['Daily Total'] = df['Total'] / pd.to_datetime(df['Month']).dt.daysinmonth

print(df)

       Month  Total  Daily Total
0  Nov. 2019  45345  1511.500000
1  Dec. 2019  87493  2822.354839
2  Jan. 2020  45765  1476.290323
3  Feb. 2020  38756  1336.413793


text:
Q: Invalid query: You have an error in your SQL syntax; (ERROR ON INSERT) So I am a newb to php & mysql. I keep getting this error each time I fill out a form that I created. When I check phpmyadmin to see if the information from the form has been added to the table, it's nowhere to be found. I found a similar question on here and their problem was fixed by running a query to turn the strict mode off of SQL. I tried to do so and it added an entry to the table but all the values in the entry were 0. Here's my php block:
<?php

    require('connect2.php');
    session_start();
    $username = $_SESSION['username'];

    //My queries will be here
    $bloodquery = mysql_query("SELECT * FROM `CodesBloodType` ORDER BY `BloodTypeText`");
    $donor_add = "INSERT INTO `Donor`(`DonorID`, `PersonID`, `DateRegistered`, `AgeRegistered`, `DonorPreRegistered`, `MedicalFacilityID`, `NationalLocalRegistry`, `NationalLocalRegistryID`, `Height`, `Weight`, `BloodTypeCode`, `OrganCriteriaID`, `LivingDonor`, `DirectedDonor`) VALUES ($donorid,$personid,$dateregistered,$ageregistered,$donorpreregistered,$medicalfacilityid,$nationallocalregistry,$nationallocalregistryid,$height,$weight,$bloodtypecode,$organcriteriaid,$livingdonor,$directeddonor)";

//Check to see if something is entered in my fields, if so then define variables

// Loop over field names, make sure each one exists and is not empty

$required = array('donorid', 'personid', 'dateregistered', 'ageregistered','medicalfacilityid','nationallocalregistry','nationallocalregistryid', 'height', 'weight','organcriteriaid');
$error = false;
$var = $_POST['submit'];
if($var){
foreach($required as $field) {
  if (empty($_POST[$field])) {
    $error = true;
    if ($error) {
    echo $field. ' is empty';
    ?>

    <?php
    }
}

  else{
    $error = false;

        }

}

 if(!$error){

    $donorid = $_POST['donorid'];
    $personid = $_POST['personid'];
    $dateregistered = $_POST['dateregistered'];
    $ageregistered = $_POST['ageregistered'];
    if(isset($_POST['donorpreregistered'])){
    $donorpreregistered = "1";}
    else{
        $donorpreregistered = "0";
    }
    $medicalfacilityid = $_POST['medicalfacilityid'];
    $nationallocalregistry = $_POST['nationallocalregistry'];
    $nationallocalregistryid = $_POST['nationallocalregistryid'];
    $height = $_POST['height'];
    $weight = $_POST['weight'];
    $bloodtypecode = $_POST['bloodtypec'];
    $organcriteriaid = $_POST['organcriteriaid'];
    if(isset($_POST['livingdonor']))
    {
        $livingdonor = "1";
    }
    else{
        $livingdonor = "0";
    }

    if(isset($_POST['directeddonor'])){
    $directeddonor = "1";}
    else{
        $directeddonor = "0";
    }

    $result = mysql_query($donor_add);
    if (!$result) {
    die('Invalid query: ' . mysql_error());
    //echo "Form Submitted Successfully";

        }
    }

}

?>

Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',,,,,,,,,,,,)' at line 1

A: You don't need to use single quotes for any table or column name... mySQL may be recognizing them as an alias and doesn't recognize any table to execute the query.  Your INSERT syntax is also wrong, you need to concatenate the values to your query String, the correct sintax to concat a value in PHP is using "." For example...   "INSERT INTO myTable values (".$myValue.")" or   "INSERT INTO myTable (column1, column2) values (".$value1.", ".$value2.")"


text:
Q: SQLite cumulative sum and WHERE containing nested SUBSTR() How do I get a cumulative sum based on the code of title records?
Consider:
 tbl_A:
 --------------------------------
 |  is_title  |  code  | amount |
 --------------------------------
 | 1          | "1"    |   null |
 | 0          | "11"   |     10 |
 | 0          | "12"   |     15 |
 | 1          | "13"   |   null |
 | 0          | "131"  |      3 |
 | 0          | "132"  |      3 |
 | 1          | "2"    |   null |
 | 0          | "21"   |     30 |
 | 0          | "22"   |     40 |
 --------------------------------

I would like to get:
 --------------------------------
 |  code  | amount | cumulative |
 --------------------------------
 | "1"    |   null |         25 |
 | "11"   |     10 |       null |
 | "12"   |     15 |       null |
 | "13"   |   null |          6 |
 | "131"  |      3 |       null |
 | "132   |      3 |       null |
 | "2"    |   null |         70 |
 | "21"   |     30 |       null |
 | "22"   |     40 |       null |
 --------------------------------

My attempts are failing for aliasing a column on SELECT and using it on WHERE of a a nested SELECT.


text:
Q: Javascript - Is passing array[0] directly vs array[0] by i= 0 array[i] fundementally different inside an "if" statement? Working on a programming challenge. The objective is to create a function that "Drop[s] the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true."
dropElements([1, 2, 3, 4], function(n) {return n > 5;});

function dropElements(arr, func) {
    for (i = 0; i < arr.length-1; i++) {
        if(func(arr[i])) {
            break;
        }
        else {
            arr.splice(i,1);
            i--;
        }
    }
    return arr;
}

returns [4] which is the incorrect answer
However the following:
dropElements([1, 2, 3, 4], function(n) {return n > 5;});

function dropElements(arr, func) {
    for (i = 0; i < arr.length; i++) {
        if (func(arr[0])) {
            break;
        }
        else {
            arr.shift();
            i--;
        }
    }
    return arr;
}

returns [] which is the correct answer
I wrote it all out by hand and it looks like it should out put the same. Is it something to do with coercion that I don't understand?

A: Your first loop is up to arr.length-1 while the second is arr.length.


text:
Q: Java Google Calendar parse events I'm not able to parse the Google Calendar events with the Google Calendar API.
URL feedUrl = new URL("https://www.googleapis.com/calendar/v3/calendars/"+ emailAddress +"/events/");
EventFeed eventFeed = calendarService.getFeed(feedUrl, EventFeed.class);

Exception, last line:
com.google.gdata.util.ParseException: Unrecognized content type:application/json;charset=UTF-8

A: gdata.util leads me to believe that you are trying to use the Gdata client library.
But you appear to be trying to feed it the end point for V3 of the Google Calendar API.  Which isn't going to work because the V3 of the Google Calendar is a discovery service API and not a GData API.   Discovery API return jSon, gData APIs return xml so there is no way the gData Client library can understand what the V3 API is trying to tell it.  Hence the Unrecognized content type:application/json
I think you should start by downloading the current Google API java client library.
Also note that the GData version of the Google Calendar API was shut down November 17, 2014   So I don't believe you will be able to use the gdata client library to access Google Calendar


text:
Q: Laravel Solarium how to add csv file to Solr core? I am trying to make a laravel project. Users can upload a csv file to Solr via Laravel. I am already connect solr and can upload a csv file. But i dont know how to add the csv file to solr's core. Any suggestions, what should i do ?

A: If you want to index the csv info in Solr you have two options:

*

*Send the info using a "update" request handler. More info here

*Use Solarium functions to add documents. Some examples here and Solarium Documents documentations here


text:
Q: RecyclerVIew item width doesn't fill screen width I'm filling a RecyclerView with custom view as a list item, ListItem, creating it from the onCreateViewHolder function.
The problem is, the list item view's width isn't filling the recyclerview (the parent) width, but in reality it wraps the width of the content (it's set to match_parent not wrap_content).
I'm guessing that since I'm creating the view programmatically, it has no knowledge of it's parent.
Here's where I create the ListItem in the adapter:
@NonNull
@Override
public ListItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new ListItemHolder(new ListItem(parent.getContext()));
}

And the code for ListItem
public class ListItem extends LinearLayout {

    private ListItemBinding binding;
    private final Context mContext;

    public ListItem(Context context) {
        super(context);
        mContext = context;
        setUp();
    }

    public ListItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setUp();

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ListItem, 0, 0);
        setBigText(a.getString(R.styleable.ListItem_bigText));
        setSmallText(a.getString(R.styleable.ListItem_smallText));
        setImageDrawable(a.getDrawable(R.styleable.ListItem_src));
        setHeaderText(a.getString(R.styleable.ListItem_header));
        showHeader(binding.listItemHeaderText.getText() != null);
        a.recycle();
    }

    public void setUp() {
        binding = ListItemBinding.inflate(LayoutInflater.from(mContext), this, true);
        setClickable(true);
        setFocusable(true);
    }

    public void setBigText(@Nullable String text) {
        binding.listItemBigText.setText(text == null ? "" : text);
    }

    .
    .
    .
    .
    .
}

I tried passing the parent as a parameter to the ListItem constructor and inflating with that but it raised an error relating to the context.
How can I inflate the ListItem while keeping it as a seperate class and making it fill it's parent width?
I could create a layout of the list item and inflate from a layout in onCreateViewHolder instead of inflating from a custom view class but I want to
have it separated and reusable.
SOLUTION
Thanks to @Zain, hes solution was just to set the width to MATCH_PARENT through the view class,
apparently it ignores the xml.
The change I did:
public class ListItem extends LinearLayout {
    .
    .
    .

    public void setUp() {
        binding = ListItemBinding.inflate(LayoutInflater.from(mContext), this, true);
        setClickable(true);
        setFocusable(true);
        *setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));*
    }

    .
    .
    .
}

A: Try to set it while instantiating it in onCreateViewHolder():
@NonNull
@Override
public ListItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    ListItem listItem = new ListItem(parent.getContext());
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                                     MATCH_PARENT, WRAP_CONTENT);
    listItem.setLayoutParams(params);
    return new ListItemHolder(listItem);

}


text:
Q: Is MySQL smart enough to stop considering rows once HAVING condition must be true? Imagine a query like
SELECT col1
FROM t
GROUP BY col2
HAVING COUNT(col3) > 1;

where there's a usable index on col2. As MySQL scans the col2 index and calculates COUNT(col3), will it stop counting as soon the count exceeds 1 and scan ahead to the next unique col2 value? Or will it consider every row and get an accurate count, then compare it against 1 once it's done aggregating in full?

A: This is informed speculation.  MySQL is not smart enough to stop when the HAVING clause is true.  Why?  Because MySQL does the GROUP BY first and then does the ORDER BY.  As far as I know, it does not push the filtering into the aggregation step -- even when using an index.
Let met ignore the SELECT col1, which makes no sense in this query.
If col2/col3 pairs are unique, then you might get better performance with:
SELECT col1
FROM t
WHERE EXISTS (SELECT 1
              FROM t t2
              WHERE t2.col2 = t.col2 AND t2.col3 <> t.col3
             );

This will stop at the first col3 row that matches.  If the situation is that you are really checking for NULL values of col3, then:
SELECT col1
FROM t
WHERE EXISTS (SELECT 1
              FROM t t2
              WHERE t2.col2 = t.col2 AND t2.col3 IS NOT NULL AND t2.id <> t.id
             ) AND
      col3 IS NOT NULL;

These latter two queries assume you have an index on t(col2, col3).