text:
Q: Infinispan with Hibernate: Objects are not added to the cache or removed after an update We currently have some problems with our Infinispan 2nd level cache. We've prepared two test cases:
1) Newly created objects are not put in the 2nd level Cache.
We create a new object (TestEntity) in a first transaction. We see that it is not put in the 2nd level cache, even if we flush it. When we close the transaction (container managed) and create a second transaction, the newly created object still isn't found in the 2nd level cache, but if we load it we find it in the database. So we are sure that it is created and committed in the first transaction. But why isn't the newly created object put into the 2nd level cache after the first transaction is closed?
2) updated objects are removed from the 2nd level cache after flush
We are loading an entity from the database, so it is in the 2nd level cache. Now we are updating an attribute of this loaded entity and do a flush. If we check the 2nd level cache again, the entity is not cached anymore. Why is it removed from the cache after updating + flushing and how can we prevent this?
Case 1:
Code:
private static String tmpInsId = " ";
public void onMessages(final Message[] messageBulk) {
 boolean isInCache = this.entityManager.getEntityManagerFactory().getCache().contains(TestEntity.class, tmpInsId);
 System.out.println("+++++ new TestEntity (" + tmpInsId + "): " + isInCache);
 if (!isInCache) {
  final TestEntity ri = this.entityManager.find(TestEntity.class, tmpInsId);
  if (ri != null) {
   System.out.println("+++++ new TestEntity (" + tmpInsId + "): Loaded!");
   isInCache = this.entityManager.getEntityManagerFactory().getCache().contains(TestEntity.class, tmpInsId);
   if (!isInCache) {
    System.out.println("+++++ new TestEntity (" + tmpInsId + "): Not in cache!"); // shouldn't be possible
   }
   else {
    System.out.println("+++++ new TestEntity (" + tmpInsId + "): Cached!");
   }
  }
  else {
   tmpInsId = ("TMP" + String.valueOf(System.currentTimeMillis()) + "0000000000").substring(0, 16);
   final TestEntity tmp = new TestEntity(tmpInsId, 0L, "N", "N", new Date());
   this.entityManager.persist(tmp);
   System.out.println("+++++ new TestEntity (" + tmpInsId + "): "
     + this.entityManager.getEntityManagerFactory().getCache().contains(TestEntity.class, tmpInsId));
   this.entityManager.flush();
   System.out.println("+++++ new TestEntity (" + tmpInsId + "): "
     + this.entityManager.getEntityManagerFactory().getCache().contains(TestEntity.class, tmpInsId));
   this.entityManager.find(TestEntity.class, tmpInsId);
   System.out.println("+++++ new TestEntity (" + tmpInsId + "): "
     + this.entityManager.getEntityManagerFactory().getCache().contains(TestEntity.class, tmpInsId));
  }
 }

Log output 1nd Transaction:
17:54:30,730 INFO [stdout] (default-threads - 2) +++++ new TestEntity ( ): false
17:54:30,745 INFO [stdout] (default-threads - 2) +++++ new TestEntity (TMP1366041270730): false
17:54:30,761 INFO [stdout] (default-threads - 2) +++++ new TestEntity (TMP1366041270730): false
17:54:30,761 INFO [stdout] (default-threads - 2) +++++ new TestEntity (TMP1366041270730): false

Log output 2nd Transaction:
17:55:00,058 INFO [stdout] (default-threads - 2) +++++ new TestEntity (TMP1366041270730): false
17:55:00,058 INFO [stdout] (default-threads - 2) +++++ new TestEntity (TMP1366041270730): Loaded!
17:55:00,058 INFO [stdout] (default-threads - 2) +++++ new TestEntity (TMP1366041270730): Cached!

Case 2:
Preparation: PreLoad of entity "TMP0000000000043" which is already in DB
Code:
 System.out.println(" TestEntity          : " + this.entityManager.getEntityManagerFactory().getCache().contains(TestEntity.class, "TMP0000000000043"));
 testEntity().setLstUpdTmstmp(currentTimestamp);
 this.entityManager.flush();
 System.out.println(" TestEntity          : " + this.entityManager.getEntityManagerFactory().getCache().contains(TestEntity.class, "TMP0000000000043"));

Log output:
17:21:17,685 INFO [stdout] (default-threads - 6) LifecycleEngine TestEntity : true
17:21:17,857 INFO [stdout] (default-threads - 6) LifecycleEngine TestEntity : false

We are using the following setup:
- EAP-6.0.1
- Hibernate 4.2
- Infinispan as provided by EAP-6.0.1 as 2nd level cache
Subsystem configuration:
<subsystem xmlns="urn:jboss:domain:infinispan:1.3">
<cache-container name="hibernate" default-cache="local-query" module="org.jboss.as.jpa.hibernate:4">
<local-cache name="entity">
<transaction mode="NON_XA"/>
<eviction strategy="LRU" max-entries="10000"/>
<expiration max-idle="100000"/>
</local-cache>
<local-cache name="local-query">
<transaction mode="NONE"/>
<eviction strategy="LRU" max-entries="10000"/>
<expiration max-idle="100000"/>
</local-cache>
<local-cache name="timestamps">
<transaction mode="NONE"/>
<eviction strategy="NONE"/>
</local-cache>
</cache-container>
</subsystem>

Enabling of level 2 cache:
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="javax.persistence.sharedCache.mode" value="ENABLE_SELECTIVE" />
<property name="hibernate.cache.default_cache_concurrency_strategy" value="transactional" <property
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>

The annotations on the entities are :
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)


text:
Q: T-SQL: Query to eliminate non-unique results I'm trying to select the create date for the most recent request # for each unique business unit. Because there are more unique create dates then there are business units, I get non-unique business units in my business unit column. I don't need all create dates, just the most recent one.
If you look at the CTE in v2, I want the most recent CreateDate for each value returned from the CTE.
Any assistance is appreciated.
Version 1:
SELECT
    SQ.[Business Unit Impacted] [BU],
    COUNT(RD.RequestID) [ReqCount],
    (SELECT TOP 1 RD.CreateDate) [Create]
FROM
    REP_RequestData RD
LEFT JOIN
    REP_StandardQuestionResponses SQ ON SQ.RequestDataId = RD.Id
WHERE
    RD.ProductID = 'Firewall.Change.Request'
GROUP BY
    SQ.[Business Unit Impacted], RD.CreateDate

Version 2:
WITH D AS
(
    SELECT
        SQ.[Business Unit Impacted] [BU],
        COUNT(RD.RequestID) [ReqCount]
    FROM
        REP_RequestData RD
    LEFT JOIN
        REP_StandardQuestionResponses SQ ON SQ.RequestDataId = RD.Id
    WHERE
        RD.ProductID = 'Firewall.Change.Request'
    GROUP BY
        SQ.[Business Unit Impacted]
)
SELECT
    D.BU,
    D.ReqCount,
    (SELECT TOP 1 RD.CreateDate) [create]
FROM
    D
LEFT JOIN
    REP_StandardQuestionResponses SQ ON SQ.[Business Unit Impacted] = D.BU
LEFT JOIN
    REP_REQUESTDATA RD on SQ.RequestDataId = RD.Id
WHERE
    RD.ProductID = 'Firewall.Change.Request'
GROUP BY
    D.BU, D.ReqCount, RD.CreateDate

A: In Version 2, you need to add a where clause inside of your subselect statement (select top 1 RD.CreateDate) to limit the return to the Business Unit returned on the same line along with an order by to get the latest CreateDate. It would look something like the code below:
(select top 1 RD.CreateDate where RD.BU = D.BU order by RD.CreateDate desc)

That should return the latest CreateDate based on the Business Unit.

A: if I understood correctly you just need the latest date so it's a matter of grouping only by BU and obtain the max(date):
SELECT
    SQ.[Business Unit Impacted] [BU],
    COUNT(RD.RequestID) [ReqCount],
    MAX(RD.CreateDate) [Create]
FROM
    REP_RequestData RD
LEFT JOIN
    REP_StandardQuestionResponses SQ ON SQ.RequestDataId = RD.Id
WHERE
    RD.ProductID = 'Firewall.Change.Request'
GROUP BY
    SQ.[Business Unit Impacted]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Billing access denied, tho Ive granted all access to an IAM user I currently cant watch or edit Billing (through IAM User Access to Billing Information) because the AWS console says that I dont have permissions.
I am the only user in the account, with a full IAM access in the group and directly on the user as well, including a the AWS Billing policy and fullBuillingAccess (that I created). But when I navigate to billing I cannot look further:
You Need Permissions
You don't have permission to access billing information for this account. Contact your AWS administrator if you need help. If you are an AWS administrator, you can provide permissions for your users or groups by making sure that (1) this account allows IAM and federated users to access billing information and (2) you have the required IAM permissions.
I granted access as a user but I cant do clause 1 for it directly prompt me this message.
Can anyone help?

A: The answer:
After further checking I found out that only a ROOT USER can enable billing access to IAM users.
If you have the same problem you need to ask the root user or login as root the enable access.


text:
Q: Google Domain and AWS S3 Static Page Good Afternoon,
I have followed a few tutorials on this topic and I have researched to see what I may be missing, but so far I haven't come up with anything. I'm sure it's a simple fix I just need a bit of help.
So I have the domain brandonkjones.dev that I purchased through Google Domains and I am trying to forward it to a static page hosted on S3. I created the hosted zone in Route 52 with the name brandonkjones.dev.

and I changed the Google Domain name servers to match those generated by the hosted zone.

I also added the additional records to forward the subdomain www to the root domain.

and Finally, I added the CNAME entry to the custom resource records on Google.

I'm sure this tutorial left off a step and I'm missing something because the original tutorial didn't even mention adding the CNAM resource within Google. Any help is greatly appreciated.

A: I had this same issue, tried with multiple browsers and triple checked that I'd done all the Route 53 and Google Domains steps correctly to no avail. Then I opened my terminal and tried:
curl http://my-domain.dev

and it returned my index.html that I uploaded to my S3 bucket, meaning I'd done everything correctly, but my browser wouldn't let me access the website over HTTP. In my devtools network tab, I could see that even if I explicitly typed in http://my-domain.dev it would do a 307 internal redirect to https://my-domain.dev. This is a security feature that browsers have to keep users from navigating to insecure sites over http.
Since the tutorials I followed for setting up S3 static hosting with a custom domain registered on Google Domains did not setup any SSL certificates for enabling HTTPS, the only way I could access my website was over HTTP. One way to fix this issue is to turn off HSTS as outlined here. Or, you could use something like AWS CloudFront to serve your S3 site over https, which you'll probably want to do if you want other people to access your site without this issue.


text:
Q: Elliptical Triangle As per my proposal of a new geometric shape as outlined at: http://ellipticaltriangle.blogspot.com/
I tentatively think the figure could be reduced to something like this in polar coordinates:
r = sqrt(3)/sqrt(8-1 cos(3 theta))
This is a more desirable form as it's centered at the origin.
In Cartesian coordinates (shifted, not centered at the origin and rotated relative to the polar form), I came up:
y^2=(1/2-(sqrt(3-4(x-sqrt(3)/2)^2)-(x-sqrt(3)/2))/sqrt(3))^2
for 0 < x < sqrt(3)/2, combined with
y^2=1/2-x^2/3
for sqrt(3)/2 < x < sqrt(6)/2
However, in checking the perimeter of such, I am off by a small amount.
Anyone able to help me get to a clean equation for which I am seeking?


text:
Q: Python: TypeError: unsupported operand type(s) for +: 'int' and 'range' import datetime

def logger(fn):
 def wrapper(*args, **kwargs):
  print(f"{fn.__name__} : {args} | {kwargs}")
  start = datetime.datetime.now()
  ret = fn(*args, **kwargs)
  delta = datetime.datetime.now()
  print(f"The function takes {(delta - start).total_seconds()} seconds")
  return ret
 return wrapper

@logger  # add=logger(add)
def add(*args, **kwargs):
 return sum(args) + sum(kwargs.values())

print(add(range(100)))

This is the effects
add : (range(0, 100),) | {}

When I tried to run the code, it will report an error.
    return sum(args) + sum(kwargs.values())
           ^^^^^^^^^
TypeError: unsupported operand type(s) for +: 'int' and 'range'

Changing sum(args) to sum(*args) will solve the problem, but I want to know why, as sum(range(10)) is totally Ok and why would it fail in a wrapper?

A: I think I have made a ridiculous mistake. The args in the program is (range(100),). It is a tuple, not simple 'range(100). So I must destruct it with *`.


text:
Q: How to set minDate/maxDate from array in jQuery ui datepicker widget I have a html table where each row contains a datepicker field. In each row in a separate td, I have a input field with a class of product_id. Lastly there is an array of objects with these product ids as its keys, and looks something like:
dateDetails[2].start_date = '2014-08-10' //year-month-day
dateDetails[2].end_date = '2014-10-10'
dateDetails[5].start_date = '2014-08-14'
dateDetails[5].end_date = '2014-12-16'

The code I am trying is:
$(".txt_DatePicker").datepicker({
    beforeShowDay: function(date){
        //Logs the expected date
        console.log(dateDetails[$(this).closest('tr').find('.product_id').val()].start_date);
        .......
        ...
    },
    minDate: new Date(dateDetails[$(this).closest('tr').find('.product_id').val()].start_date),//Throws undefined error
    maxDate: new Date(dateDetails[$(this).closest('tr').find('.product_id').val()].end_date),
    dateFormat: "dd MM, yy"
});

As you can see, the code shows the value within the beforeShowDay but throws an Undefined error, during the minDate\maxDatelines. I am guessing this happens because at that point the datepicker hasn't been initialized so it cannot find $(this). But this is only my guess, and I have no idea how to fix it.

A: .datepicker({dateFormat:'yy-mm-dd',minDate:'2013-09-10' ,maxDate:'2013-10-10'});


text:
Q: Finding extremal of the functional Find the stationary point of the functional $$
J[y]=\int \left( x^2y'^2+2y^2 \right) dx
$$
where $y(0)=0, y(1)=2.$
My Solution:
E-L equation: $x^2y''+2xy'-2y=0.$
This is also Cauchy-Euler equation.
Let $y(x)=x^m$. Substituting to eqn. , we get $m_1=-2, m_2=1$ and
I found the general solution $y(x)=c_1x^{-2}+c_2x$.
Now, we will find $c_1,c_2.$
Since $y(1)=2$, we have $c_1+c_2=2$. But when I write $x=0$ to general solution, $0=y(x)=c_1.0^{-2}+c_20$, there is a uncertainty. Please help me.

A: Your general solution is correct:
$$y(x)=c_1\dfrac{1}{x^2}+c_2x.$$
From $y(x=0)=0$ we see that $c_1=0$ must be given or your solution will explode. One way to show this would be to multiply the equation with $x^2$ to obtain
$$x^2y(x)=c_1+c_2x^3 \implies 0 = c_1 + c_2 \cdot 0^3 \implies c_1=0.$$
Using $y(x=1)=2=c_2\cdot 1$, will give you $c_2=2$.
The final solution is $y(x)=2x$.


text:
Q: What is mathematical identity behind Charge continuum? Lorentz force (per unit 3-volume) f on a continuous charge distribution (charge density ρ) in motion. The 3-current density J corresponds to the motion of the charge element dq in volume element dV and varies throughout the continuum.

A: Divergence theorem is mathematical identity which says in calculus:
$$\frac{\partial{\rho}}{\partial{t}}+\nabla \cdot \textbf{J}$$
Yes? Is worked backwards:
$$I=\iint_{\partial\lambda}{\textbf{J}\cdot d \textbf{S}}=\frac{dq}{dt}$$
I hope is help. In fact, Maxwell there was no tensor knowledge, was ONLY calculus of numbers and vector! He work each number out for each vector! Amazing!


text:
Q: ArrayList retrieved from another class is null I am attempting to access an arraylist I created in another class in order to perform a search function. However, the arraylist is null.
 `public class RssParser extends Activity{
    Calendar calendar = null;
List<RssItem> items = new ArrayList<RssItem>();
ArrayList<String> list;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState== null){
    setContentView(R.layout.fragment_layout);}}

public List<RssItem> build(InputStream inputStream) throws XmlPullParserException, IOException, ParserException {
    try {
        CalendarBuilder builder = new CalendarBuilder();

        calendar = builder.build(inputStream);

        return readFeed(calendar);
    } finally {
        inputStream.close();
    }
}

private List<RssItem> readFeed(Calendar calendar) throws XmlPullParserException, IOException {

    java.util.Calendar today= java.util.Calendar.getInstance();
    Period period= new Period(new DateTime(today.getTime()), new Dur(today.getTime(), today.getTime()) );
     Filter filter= new Filter(new PeriodRule(period));
    ComponentList events = (ComponentList) filter.filter(calendar.getComponents(Component.VEVENT));

     for (Object balling: events){
         VEvent event1 = (VEvent) balling;
        Date jobs = event1.getStartDate().getDate();
         String honey = null;
        String event = event1.getSummary().getValue();
         String happy=event1.getCategories().getValue();
          list= new ArrayList<String>();
         list.add(event);
         list.add(happy);
         Log.i ("list", ""+ list);

        SimpleDateFormat format =
                 new SimpleDateFormat("MMM dd yyyy h:mm a");
         SimpleDateFormat format2 =
                 new SimpleDateFormat("MMM dd yyyy");
         if (jobs.toString().length()>12){
         DateFormat[] formats = new DateFormat[]{
                     format
             };
         for (DateFormat df : formats) {
              honey = (df.format(jobs));
         }}
         else if( jobs.toString().length()!= 0){
             DateFormat[] formats = new DateFormat[] {
                     format2
             };
             for (DateFormat df : formats) {
                 honey = (df.format(jobs));
             }}
         else {honey= "no time/date given";}

        if (happy.equals ("KGHS Athletics" )){
             if (event != null) {
                 RssItem time= new RssItem(event, honey, happy);
                 items.add(time);

             }}
          if (happy.equals("Division Testing")){
              if (event != null) {
             RssItem time= new RssItem(event, honey, happy);
             items.add(time);

           }
     }
         if (happy.equals("King George High")){
             if (event != null) {
                 RssItem time= new RssItem(event, honey, happy);
                 items.add(time);
             }
         }
    if (happy.equals("Division Calendar")){
        if (event != null) {
            RssItem time= new RssItem(event, honey, happy);
            items.add(time);
        }
    }}
    return items;
}
public ArrayList<String> getList(){

    return list;
}

}`

Here is the class where I am attempting to get the arraylist.
public class RssFragment extends Fragment implements AdapterView.OnItemClickListener, SearchView.OnQueryTextListener,
    SearchView.OnCloseListener {

private ProgressBar progressBar;
private View view;
private JazzyListView listView;
private SearchView searchView;
private SearchableActivity mDbHelper;
private RssAdapter adapter;
ArrayList<String> array;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState==null) {

         mDbHelper = new SearchableActivity(getActivity().getBaseContext());
        try {
            mDbHelper.open();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //Clear all names
        mDbHelper.deleteAllNames();}

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (savedInstanceState == null){
    if (view == null ) {

        view = inflater.inflate(R.layout.fragment_layout, container, false);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        listView = (JazzyListView) view.findViewById(R.id.listView);
        searchView = (SearchView) view.findViewById(R.id.searchView);

        //Sets the default or resting state of the search field. If true, a single search icon is shown by default and
        // expands to show the text field and other buttons when pressed. Also, if the default state is iconified, then it
        // collapses to that state when the close button is pressed. Changes to this property will take effect immediately.
        //The default value is true.
        searchView.setIconifiedByDefault(false);

        searchView.setOnQueryTextListener(this);
        searchView.setOnCloseListener(this);
        listView.setOnItemClickListener(this);
        listView.setSmoothScrollbarEnabled(true);

        startService();}
     else {
        // If we are returning from a configuration change:
        // "view" is still attached to the previous view hierarchy
        // so we need to remove it and re-attach it to the current one
        ViewGroup parent = (ViewGroup) view.getParent();
        parent.removeView(view);
    }}
    return view;
}

private void startService() {
    Intent intent = new Intent(getActivity(), RssService.class);
    intent.putExtra(RssService.RECEIVER, resultReceiver);
    getActivity().startService(intent);
}

/**
 * Once the {@link RssService} finishes its task, the result is sent to this ResultReceiver.
 */
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
    @SuppressWarnings("unchecked")
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {

  List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService.ITEMS);
        adapter = new RssAdapter(getActivity(), items);

        if (items != null) {
            listView.setAdapter(adapter);
            RssParser parser= new RssParser();
           array= parser.getList();
            Log.i("array List", "" + array);
            for (String name : array) {
                mDbHelper.createList(name);
            }

        } else {
            Toast.makeText(getActivity(), "The feed is unable to be downloaded at this time",
                    Toast.LENGTH_LONG).show();
        }

        progressBar.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
         listView.setTransitionEffect(JazzyHelper.GROW);
    };
};

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    RssAdapter adapter = (RssAdapter) parent.getAdapter();
    RssItem item = (RssItem) adapter.getItem(position);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    startActivity(intent);
}
@Override
public void onDestroy() {
    super.onDestroy();

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

@Override
public boolean onClose() {
    listView.setAdapter(adapter);
    return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
    displayResults(query + "*");
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    if (!newText.isEmpty()){
        displayResults(newText + "*");
    } else {
        listView.setAdapter(adapter);
    }

    return false;
}

/**
 * Method used for performing the search and displaying the results. This method is called every time a letter
 * is introduced in the search field.
 *
 * @param query Query used for performing the search
 */
private void displayResults(String query) {

    Cursor cursor = null;
    try {
        cursor = mDbHelper.searchByInputText((query != null ? query : "@@@@"));
    } catch (SQLException e) {
        e.printStackTrace();
    }

    if (cursor != null) {

        String[] from = new String[] {SearchableActivity.COLUMN_NAME};

        // Specify the view where we want the results to go
        int[] to = new int[] {R.id.listView};

        // Create a simple cursor adapter to keep the search data
        SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(getActivity().getBaseContext(), R.layout.fragment_layout, cursor, from, to);
       listView.setAdapter(cursorAdapter);

        // Click listener for the searched item that was selected
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView parent, View view, int position, long id) {

                // Get the cursor, positioned to the corresponding row in the result set
                Cursor cursor = (Cursor) listView.getItemAtPosition(position);

                // Get the state's capital from this row in the database.
                String selectedName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
                Toast.makeText(getActivity(), selectedName, Toast.LENGTH_SHORT).show();

                // Set the default adapter
                listView.setAdapter(adapter);

                // Find the position for the original list by the selected name from search
                for (int pos = 0; pos < array.size();
                pos++){
                    if (array.get(pos).equals(selectedName)) {
                        position = pos;
                        break;
                    }
                }

                // Create a handler. This is necessary because the adapter has just been set on the list again and
                // the list might not be finished setting the adapter by the time we perform setSelection.
                Handler handler = new Handler();
                final int finalPosition = position;
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        listView.setSelection(finalPosition);
                    }
                });

                searchView.setQuery("", true);
            }

        });

    }
}

}

And so basically what I am trying to do is get an arraylist from an ics file I downloaded for the searchview. But this arraylist is null because of the order of class execution. Maybe it will help if I show RssItem.
  public class RssItem {

    private final String title;
    private final String date2;
private final String categories;
    public RssItem(String title, String date2, String categories) {
        this.title = title; this.date2= date2; this.categories= categories;
    }
 public String getTitle() {
        return title;
    }
    public String getDate(){return date2;}
public String getCategories(){return categories;}}

A: It looks like retrieving the list works up to a certain point, since the logging shows something in the first line. But shortly thereafter, in the same method it crashed. I'm not 100% percent sure which line is line 70 in RssParser.java, but it looks like jobs can be null.
Did you try to step through the code with a debugger? Can you verify the correct value for jobs?


text:
Q: What is the best way to add lagged features for time-series predictions with a long prediction period? I am currently dealing with a time-series problem and want to add lag feature(s) to my data. The point is, that I should predict 1 month of daily sales based on 4 months of training data. So if I add for example a lag feature by shifting the data by 1 day, this can't help me for my predictions because I just have this information for the first day in my test data..
Any suggestions what is the best way to deal with this problem?
I am thankful for any advice! :-)


text: Q: How are floating IP's and system subnet provided for External Network effecting actual hypervisor Intalled openstack 17.0.3 in my centOS VM using packstack installation method. I want to know How are floating IP's and system subnet provided for External Network effecting actual hypervisor.


text:
Q: How do I convert my while loop to a for loop? I am a beginner coder using Netbeans Java. I have created a code that initially asks how many gallons are in your gas tank. Then, it will have a while loop asking how many miles you will be traveling for this first run and how fast are you traveling. This will repeat with a while loop until you input '0' to stop adding trips. I am stumped on how to convert this while loop into only using For loops. I would greatly appreciate the assistance. Here is my code that has while loops.
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
            int tank;
            double miles;
            double speed;
            double totalMiles = 0.0;
            int choice;
            double time;
            double totalTime = 0.0;
            double fuelConsumption;

            System.out.print("How many gallons of gas is in your tank (Integer 1-15)? ");
            tank = input.nextInt();
            System.out.printf("%s%d%s\n\n" , "You have ", tank , " gallons of gas in your tank.");

            System.out.print("Are you going on a trip (1 = Yes or 0 = No)? ");
            choice = input.nextInt();

            while (choice == 1)
            {
                System.out.print("How many miles are you traveling? ");     // miles
                miles = input.nextFloat();

                System.out.print("What is your speed for this run (MPH)? ");      // speed
                speed = input.nextInt();
                System.out.print("\n");

                totalMiles = totalMiles + miles;
                time = (miles/speed);
                totalTime += (time*60);
                fuelConsumption = (20*(tank/totalMiles));

                System.out.print("Is there another leg in your trip (1 = Yes or 0 = No)? ");    // asking another leg
                choice = input.nextInt();

                if (choice == 0)
                {
                    System.out.printf("%s%5.2f%s\n","Your data for this trip is: \n"
                            + "You traveled a total of about ", totalMiles , " miles.");
                    System.out.printf("%s%.2f%s\n" , "You traveled about " , totalTime , " minutes.");

                    if (fuelConsumption >= 2)
                    {
                        System.out.println("Your car has enough gas to return.");
                        break;

                    }
                    else
                    {
                        System.out.println("Your car will need more gas to return.");
                        break;
                    }

                }
            }

}

}

A: That is not a use case for a for loop, where we iterate over a known number of elements for do a known number of iterations. Like, repeat 10 times or such.
Technically it can be solved with a for loop, but that is abusing the concept a bit. The while loop is a perfect fit for that task.

A: This is not a place to use a for-loop, you use a for loop for something like this:

printAmount = 10;

for (int i = 0; i < printAmount; i++) {

   System.out.println("Hello World");

}

Here you are using the for loop to print "Hi" for the amount in printAmount.
Your case is different: You want the while-loop to repeat while the input is "1" so you use a WHILE-loop.


text:
Q: Limit of $\sum_{k=1}^\infty \frac{f(k)}{k!}$ Does this limit always exist when $f(k)$ is a polynomial?
$$
\sum_{k=1}^\infty \frac{f(k)}{k!}
$$
(My guess is yes, based on the root test, but I'm not entirely sure I applied it correctly.)

A: It suffices to show that $\sum_{k=1}^\infty \frac{k^m}{k!}$ converges for each $m \ge 0$. You can use the ratio test to show this series converges. Then note that your original series is a finite sum of series of this form.

A: For sure as
$$F(f) =
\sum_{k=1}^\infty \frac{f(k)}{k!}
$$ is linear and defined for all monomial $f_n(x)=x^n$ as can be verified with the ratio test. Therefore it is defined for all polynomials by addition of a finite number of monomials.


text:
Q: How to trigger ripple effect on Switch click for its container I want to replicate the effect used in the Settings app for Android 12, where the ripple effect is automatically triggered whenever an option is clicked (including the Switch itself). However, in my app, the ripple effect does not happen at all, only the Switch animates.
@Composable
fun ComposableSettingSimpleMode() {
    val isChecked = remember { mutableStateOf(false) }

    Row(modifier = Modifier
        .fillMaxWidth()
        .clickable(onClick = {})) {
        Text(text = stringResource(id = R.string.simple_mode))
        Switch(checked = isChecked.value, onCheckedChange = {
            isChecked.value = it
        })
    }
}

A: You can use the toggleable modifier:
@Composable
fun ComposableSettingSimpleMode() {
    val isChecked = remember { mutableStateOf(false) }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .toggleable(
                value = isChecked.value,
                onValueChange = { isChecked.value = it },
            ),
    ) {
        Text(text = "Hello")
        Switch(checked = isChecked.value, onCheckedChange = null)
    }
}

The important points are:

*

*The entire row is made "toggleable" (i.e. whatever you want to have the ripple effect on);

*The toggleable modifier requires a value, which should have the same value as the switch, and an onValueChange, which should perform the actual switch state change (which currently is on the Switch's onCheckedChange);

*The Switch's onCheckedChange should be set to null, otherwise it will "steal" the click from the row when the Switch is clicked, and the row won't ripple;

A: This is where you pass in your own InteractionSource
    var isChecked by remember { mutableStateOf(false) }
    val interactionSource = remember { MutableInteractionSource() }
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(
                interactionSource = interactionSource,
                indication = LocalIndication.current,
                onClick = {
                    isChecked = !isChecked
                }
            )
    ) {
        Text(text = "Dummy Text", Modifier.weight(1f))
        Switch(
            checked = isChecked,
            interactionSource = interactionSource,
            onCheckedChange = {
                isChecked = it
            })
    }


text:
Q: VBA: Create New Workbook on a specific Directory I would like to create a new workbook on a specific directory using a button from an activeworkbook.
Directory will be Drive D:\SALES_RFQ Database
WorkBook name is "M.O Control Number Database"
Condition:
The code has to check if the workbook does exists, if not, if has to create the workbook on the given directory.
Any help with much appreciated.
Thanks in advance

A: Option Explicit

Sub test()

    Dim Path As String, DocName As String

    Path = "D:\SALES_RFQ Database"
    DocName = "M.O Control Number Database"

    If Dir(Path & "\" & DocName & ".xlsx") = "" Then
        Workbooks.Add
        ActiveWorkbook.SaveAs Path & "\" & DocName & ".xlsx"

    End If

End Sub


text:
Q: When taking the exponential of a diagonalizable matrix, why can the eigenvector matrices be taken out of the exponential? Given diagonalizable matrix $A$ with diagonal form $D$, $A=PDP^{-1}$ where $P$ is the matrix of eigenvectors, why is it that that $e^A=e^{PDP^{-1}}=Pe^DP^{-1}$?

A: $e^{A}=I+A+A^2/2+ \ldots$
$A^{n}=(PDP^{-1})^{n}=PDP^{-1}PDP^{-1}\cdots PDP^{-1}=PD^{n}P^{-1}$
Thus
$e^{A}=PP^{-1}+PDP^{-1}+PD^{2}P^{-1}/2+\ldots$.
Factoring out the $P$ and $P^{-1}$ on the left and right gives
$e^{A}=P(I+D+D^{2}/2+\ldots)P^{-1}=Pe^{D}P^{-1}$.

A: $$e^{PDP^{-1}}=I+PDP^{-1}+\frac{1}{2}PDP^{-1}PDP^{-1}+\frac{1}{6}PDP^{-1}PDP^{-1}PDP^{-1}+\cdots$$
$$=PIP^{-1}+PDP^{-1}+P\frac{1}{2}D^2P^{-1}+P\frac{1}{6}D^3P^{-1}+\cdots$$
$$P(I+D+\frac{1}{2}D^2+\frac{1}{6}D^3+\cdots)P^{-1}$$
$$=Pe^D P^{-1}$$

A: It is a consequence of the fact that conjugation by an invertible matrix $A$ preserves products of matrices, i.e., that $A(XY)A^{-1} = (AXA^{-1})(AYA^{-1})$ for any matrices $X,Y$.
So you have $$e^{PDP^{-1}} = \sum_{k=0}^{\infty} \frac {(PDP^{-1})^{k}}{k!} = \sum_{k=0}^{\infty} \frac {PD^{k}P^{-1}}{k!} = P \left(\sum_{k=0}^{\infty} \frac {D^{k}}{k!}\right)P^{-1} = Pe^{D}P^{-1}$$


text:
Q: Shiny download report cannot run examples locally I want to create a shiny app that lets me download reports.  As such I have found two examples by Yihui.  Example 1, Example 2.
I can run the gist (example 1) by shiny::runGist() and it works fine.  I am able to download the example document.  When I copy the code and run the app from R Studio I receive the following error when I try to download the document:
 Running 'texi2dvi' on 'input.tex' failed.
    Messages:
    /usr/bin/texi2dvi: pdflatex exited with bad status, quitting.
    /usr/bin/texi2dvi: see input.log for errors.

I have researched this error and came upon this link and it seems to be the same problem, although it remains unresolved.
I have gone through the suggestions and I believe it has something to do with my PATH, although this is a subject I am unfamiliar with and trying to understand.  Typing the command $PATH into terminal I receive the following:
-bash: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin:/usr/texbin: No such file or directory
I also opened the app in my browser.  I received the following different error when trying to download the document from the browser:
.onLoad failed in loadNamespace() for 'tcltk', details:
call: system2("otool", c("-L", shQuote(DLL)), stdout = TRUE)
error: error in running command

I continue to receive this error when I try to run the app in R Studio and X11 now opens.
I receive the same error when I try to load the package tcltk package.
The example 2 I am able to run and download a document on my machine, but it is only partially compiled, and does not look like the document I download from the same app running on the shiny gallery here.
My document looks like

Here is my regression model:
options(digits = 4)  fit <- lm(regFormula(), data = mtcars)b <-
  coef(fit)summary(fit)The fitting result is          mpg = r b[1] + r
  b[2]r inputx $. Below is a scatter plot with the regression line.
par(mar = c(4, 4, 1, 1)) plot(regFormula(), data = mtcars, pch = 19,
  col = 'gray')abline(fit, col = 'red', lwd = 2)

I am not sure if these problems are linked or separate.
I am hesitant to make changes to my PATH because it is unfamiliar to me, but if this is what I need to focus on please let me know. I appreciate any help and direction offered.
This is on mac OS X Lion version 10.7.5


text:
Q: How to get source of html page from a https adress in java I am trying to implement a download manager in java for rapidshare, I am using the rapidshare API.
The problem is that for example if you go to the following link
it redirects to a https page, but then when I read the content it always return me null in the InputStream
When I try to put a https link in the HttpURLConnection it always throws an exeption
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path     validation failed: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors

A: Use Apache Commons HTTPUtils .  You can make a connection to HTTPS (thereby decrypting it) if you override the DefaultTrustManager class (to do nothing), create a new TrustManager with it, then bypass the hostname verifier with ALLOW_ALL_HOSTNAME_VERIFIER.   Since your opening the connection to a place that you trust, there isn't a problem bypassing these things.


text:
Q: Java Programing about HTMLEditorKit My source code is below.
I want to control font color only css.
I insert HTML like this.
I love apple pie.

In case of tag1, I expect "I love apple" turns red font.
But only "I love" turns red font.
How do I fix it ??
    doc.getStyleSheet().addRule(".tag1 {color : red;}");

    try {

        kit.insertHTML(doc, doc.getLength(), "I love apple pie.", 0, 0, null);
    } catch (IOException e1) {

        e1.printStackTrace();
    } catch (BadLocationException e1) {

        e1.printStackTrace();
    }

A: This happens because you set red color to .tag1 only, when apple is a span inside .tag1, so it doesn't get the color css attribute directly.
As @hoosssein said, if you have a default (or any) css color value for span, it won't use the parent's style, and this is what happens here.
You need to add:
doc.getStyleSheet().addRule(".tag1 span {color : red;}");

So every span inside .tag1 cls will also have red color.


text:
Q: c# XML conversion to object unfixed complexity I've been researching a lot of XML parsing and serializing methods from MSDN. Looking at Linq and XSD.exe there doesn't seem to be a golden solution that stands out as the one I'm looking for.
My question is what is the best method for this, if it exists.
Let's say I have a XML of arbitrary complexity. One that could be satisfiable by classes such as these, assume they are substantial.
    public class nameVal
    {
        string name { get; set; }
        object value { get; set; }
    }
    public class node
    {
        nameVal self { get; set; }
        List<nameVal> properties { get; set; }
        List<node> children { get; set; }
    };

How would one, from the source of a string or file and using c# and MSDN Libraries achieve this. Some arbitrary way like, foreach(var prop in node) trunk.properties.add(prop)
I've read through a dozen posts here and articles around the web, but I haven't found a way to do this without precursor knowledge of the XML, or an XSD schema created from the XML. I just found it really odd that there wasn't an arbitrary parsing method for putting an XML document into a generic iterable data structure.
So... methods, libraries, the reason this doesn't exist, any information would be really good.

A: If I understand your question correctly, you want to map any xml to your classes. Here is my try:
var nodes = ParseXml(XDocument.Load(filename).Root);

node ParseXml(XElement root)
{
    var node = new node();

    node.self = new nameVal() { name = root.Name.LocalName, value = (string)root };

    node.properties = root.Attributes()
                          .Select(a => new nameVal() { name = a.Name.LocalName, value = a.Value })
                          .ToList();

    node.children = root.Elements()
                        .Select(e => ParseXml(e))
                        .ToList();

    return node;
}

A: There are two possible approaches that I can think of.
The first way would be to infer the XML schema from the XML itself, and then code-generate C# classes from that schema.  We already know this is possible, because XSD.EXE can infer a schema from an XML file.
The second way would be to parse the XML and populate an ExpandoObject.  This would be the preferred method, if the XML is totally fluid in its structure (i.e. it has an arbitrary schema).  Code would look something like this:
public static IEnumerable<dynamic> GetExpandoFromXml(string file, string descendantid)
{
    var expandoFromXml = new List<dynamic>();

    var doc = XDocument.Load(file);
    var nodes = doc.Root.Descendants(descendantid);

    foreach (var element in doc.Root.Descendants(descendantid))
    {
        dynamic expandoObject = new ExpandoObject();
        var dictionary = expandoObject as IDictionary<string, object>;
        foreach (var child in element.Descendants())
        {
            if (child.Name.Namespace == "")
                dictionary[child.Name.ToString()] = child.Value.Trim();
        }
        yield return expandoObject;
    }
}

http://phejndorf.wordpress.com/2011/11/20/using-expandoobject-dynamic-with-xml-data/

A: There are several different supported ways of XML in C#, but no single best answer for an hypothetical.
If you want real serialization, i.e. mapping the XML into instances of classes you define, you will need to modify your classes (for example, the properties need to be declared public) and members with a type of object are tricky (how would the deserializer know what type to put there?)   This approach requires embedding knowledge of the structure of the XML into the classes, which doesn't sound like what you want.
A more generic solution, these approaches use framework-defined classes for the XML nodes and values, not classes you define.  Common choices for this include the DOM-like classes in the System.XML namespace, or newer ones more suited to Linq style processing in the System.Xml.Link namespace.   There are good StackOverflow articles about choosing between these options, like XDocument or XmlDocument .
But with the generic approaches, the XML tags and attributes don't map directly to C# property names and collections, as I think you may be looking for.    Instead you have to use some methods on the framework class to select what data you want, e.g. XmlDocument has a SelectSingleNode() method that can be used to extract specific data using an XPath query.   This results in knowledge of the structure of the XML being limited to the XPath string, rather than embedded in code.
Hope that helps you clarify your question and get it answered.


text:
Q: Convert event delegate from C# to VB.NET Tried to convert this code to VB.NET using the various online converters but none worked (got an error on the event handler declaration). I'm using VS 2012 and .Net 4.5. Any ideas?
readonly Action<IDialogManager, Action<bool>> closeCheck;

public void Execute(ActionExecutionContext context) {
        closeCheck(Shell.Dialogs, result => Completed(this, new ResultCompletionEventArgs { WasCancelled = !result }));
    }

public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };

A: I created dummy types in LinqPad and got this:
ReadOnly closeCheck As Action(Of IDialogManager, Action(Of Boolean))

Public Sub Execute(ByVal Context As ActionExecutionContext)
    closeCheck(Shell.Dialogs, Sub(Result) RaiseEvent Completed(Me, New ResultCompletionEventArgs With { .WasCancelled = Not Result }))
End Sub

Public Event Completed As EventHandler(Of ResultCompletionEventArgs)


text:
Q: Disable clicking on header elements of django-table2 I am getting some data from DB and displaying it to the users using django-table2. My application need user to select any row and based on that I am loading a different page with data relevant to the row selected in the last page. To get this working I am using two hidden fields who's value will be set when I click on some row and that will be passed at the server side for further processing..
The problem I am facing is when i click on the rows it sets the hidden field with correct value but if i click on the header of the table everything gets messed-up. To allow post back on click of the table I have used {{render_table table_name}} in a form tag..
My tables.py
class testTable(tables.Table):  // Have used orderable=False for all the rows
  release_date = tables.Column(verbose_name="Release date",orderable=False)
  product_name = tables.Column(verbose_name="Product name",orderable=False)
  ...
  class Meta:
  orderable = False

Views.py
 table = productTable(dic)
 table.paginate(page=request.GET.get('page', 1), per_page=5)
 params['table'] =table

product.html
 <div>
    <form method="POST" name="form-product-list" action="{% url "product" %}" id="form-product-list" enctype="multipart/form-data">
        <input type="hidden" name="prod_ver" value="0" id="prod_ver" />
        <input type="hidden" name="release_date" value="0" id="release_date" />
        {% render_table table %}
    </form>
</div>

Javascript
 function addRowHandlers() {
        var table = document.getElementById("prod_details");
        var rows = table.rows;
        for (var i = 0; i < rows.length; i++) {
            rows[i].onclick = (function() {
            return function() {
                $("#prod_ver").val(this.cells[1].innerHTML);
                $("#release_date").val(this.cells[0].innerHTML);
            };
            })(i);
        }
    }

Currently when I click on any row I will get prod_ver = 1 and release_date = somedate but when I click on the header I am getting prod_ver = prod_ver and release_date =release_date..
Please look into this and ask if you need any clarification.

A: So it work, as it is supposed to. You should try to loop over table  rows only inside "tbody".
in jquery it should look like this:
$("body").on("click","tableSelector >tbody >tr", function(){
    $("#prod_ver").val($(this).children().eq(1));
    $("#release_date").val($(this).children().eq(0));
});


text:
Q: SQL Server Analysis Services Error (Data mining) Dear I write this DMX query :
Select flattened PREDICTHISTOGRAM(disease)
From patient_examination
NATURAL PREDICTION JOIN
(Select
52 as patient_age
,1 as chest_pain_type_id
,112 as rest_blood_pressure
,0 as blood_sugar
,3 as rest_electro_type_id
,96 as max_heart_rate
,1 as exercice_angina
) as t

but this error happened:

Executing the query ... Error (Data mining): Either the user, 'Server
  Name', does not have permission to access the referenced mining model
  or structure, 'patient_examination', or the object does not exist. Run
  complete


text:
Q: C# project, can't reset/clear array, setting array to zero not the answer problem solved
I am working on a project where an array holds the scores of 5 tests, but the user does not have to fill the array with 5 scores total. there is a button that displays a message box that lists the 5 scores values. The user needs to be able to run the program twice in a row without restarting the program, every time the 2nd round comes around, the array is still holding the last rounds values. I can't set the values to zero, because a live average is calculated and displayed after each score is entered, and the zeros throw off the average.
This is the button that displays the scores. If the user enters fewer than 5 scores (5 is size of array) the message box should display only those 4 or less scores, the way I have it now, it is displaying zeroes for the unused values.
 private void btnDisplayScores_Click(object sender, EventArgs e)
    {
     for (int x = 0; x < counter; x++)
      {
        Convert.ToString(scoreArray[x]);
       }
      MessageBox.Show(scoreArray[0] + Environment.NewLine
               + scoreArray[1] + Environment.NewLine + scoreArray[2]
               + Environment.NewLine+ scoreArray[3] + Environment.NewLine
               + scoreArray[4]);

We have only learned to use null with strings, we have not gotten into nullable integers and decimals. We are expected to do it without using a nullable numerical type.
This resets the values so the user can start another round.
    private void Restart()
    {
        scoreTotal = 0;
        txtScore.Clear();
        txtScoreTotal.Clear();
        txtScoreCount.Clear();
        txtAverage.Clear();
        for (int x = 0; x <= counter; x++)
        {
            scoreArray[x] = 0;
        }
        counter = 0;
    }

And maybe this will help.
private void btnAdd_Click(object sender, EventArgs e)
        {
          int currentScore;
          if (counter < 5)
            {
              if (DataValid() && DataRange())
                {
                    currentScore = Convert.ToInt32(txtScore.Text);
                    Input(currentScore);
                    Process();
                }
                else
                {
                    MessageBox.Show("Data was invalid, please enter valid data.", "Error");
                }
                counter++;
            }
           else
            {
                Restart();
            }
            txtScore.Focus();
        }

edit* i mistakenly thought i needed to convert the array to string to display it in the message box, fixed that but its not at the core of my problem.
i may try to the -1 suggestion tonite or tommarow
havnt learned list yet, array is declared global
edit2* problem solved, used the -1 solution, thanks to mfussenegger


text:
Q: Show that $\Delta u$, $\Delta v= 0$ Let $f=u+iv$ be a complex differentiable function. Then $u$ and $v$ are harmonic.
My solution:
We have Cauchy-Riemann equations held: $u_x=v_y$ and $u_y=-v_x$. Now:
$u_{xx}=v_{yx}$ and $u_{yy}=-v_{xy}$. Adding both terms we have $\Delta u =0$ (from continuity of partial derivatives). The $v$ case is analogical.

A: A complex differentiable function is infinitely differentiable, so all the partial derivatives are continuous.


text:
Q: During Pytorch tutorial a ModuleNotFoundError: 'pycocotools._mask' occurs Hello I'm new to Pytorch and I've been trying to work through this tutorial.
[https://github.com/pytorch/tutorials/blob/master/intermediate_source/torchvision_tutorial.rst]
I'm using Visual Studio Code, conda installed the Pytorch. Initially the issue was that it was missing the module engine. But this problem was solved here:
So how do we get the references/detection/ folders? What should we download and install? I have installed the pytorch, torchvision in my environment, but I could not find those files. Thanks
With a step I misread.
So I downloaded and copied the pycocotools into the project directory and the vision/detection/ .py files in to it too.
That being done it fixed that issue but the error it is now giving is.
(base) C:\Users\Sean\Desktop\Project\Test\Tutorial>D:/Anaconda/python.exe c:/Users/Sean/Desktop/Project/Test/Tutorial/tv-training-code.py
Traceback (most recent call last):
  File "c:/Users/Sean/Desktop/Project/Test/Tutorial/tv-training-code.py", line 13, in <module>
    from engine import train_one_epoch, evaluate
  File "c:\Users\Sean\Desktop\Project\Test\Tutorial\engine.py", line 8, in <module>
    from coco_utils import get_coco_api_from_dataset
  File "c:\Users\Sean\Desktop\Project\Test\Tutorial\coco_utils.py", line 9, in <module>
    from pycocotools import mask as coco_mask
  File "c:\Users\Sean\Desktop\Project\Test\Tutorial\pycocotools\mask.py", line 3, in <module>
    import pycocotools._mask as _mask
ModuleNotFoundError: No module named 'pycocotools._mask'

I'm not quite sure what the issue here is or how to fix it. Given that the _mask.pyx is present and is what I think is being imported. As I said I'm not to sure what the issue is but I would appreciate the help.
Python Version : 3.7.4
Pytorch: 1.2.0 (Cuda 10)

A: The problem is you copied the files for pycocotools instead of installing them. Files ending in .pyx are Cython files which need to be installed into extension modules (on Windows these would be a .pyd file). If you do an installation of the package instead of a file copy that should fix your problem.


text:
Q: convexity of mutual information-like function I would like to maximize the following functional $F(q)$ w.r.t. the probability mass function $q:\mathcal{Z}\rightarrow [0,1]$ with $\sum_{z \in \mathcal{Z}} q(z)=1$, where $\mathcal{Z}$ is a finite set:
\begin{equation}
\label{eq:one}
\max_q F(q) = \max_{q} \sum_{x,y} p(x) \left(\sum_{z} p(y|x,z) q(z)\right) \log \frac{\sum_{\bar{z}} p(y|x,\bar{z}) q(\bar{z})}{\sum_{\bar{x}} p(\bar{x}) \sum_{\tilde{z}} p(y|\bar{x},\tilde{z}) q(\tilde{z})}
\end{equation}
Just like $Z$ the random variables $X,Y$ are finite.
In case of convexity this would be much easier so I am trying to establish whether this functional is convex in $q$ or not. If you see that it is or is not then you may stop reading here and just tell me why (If you know how to optimize this function reliably w.r.t. q let me know and I'll write an additional question). Below is just my failed attempt up to now.
One way to show convexity is to identify convexity preserving operations. If we substitute
$$r(y|x):=\sum_{z} p(y|x,z) q(z)$$
we can see that $F(r(q))$ is a mutual information:
$$F(r) = \sum_{x,y} p(x) r(y|x) \log \frac{r(y|x)}{\sum_{\bar{x}} p(\bar{x}) r(y|\bar{x})}=I(X:Y)$$
This is known to be convex in $r(y|x)$ (see e.g. [1]). We can also easily see that $r(q)$ is convex in $q$ because it is actually linear in $q$. Now we know that if $F(r)$ is convex in $r$ and nondecreasing in every component $r_{yx}:=r(y|x)$, and each of those components $r_{yx}(q)$ is convex in $q$ then $F(r(q))$ is convex in $q$ (see [2], p.86).
The problem is, that $F(r)$ is not nondecreasing in every component $r_yx:=r(y|x)$. This can be seen by taking the derivative of $F$ w.r.t. some $r(y'|x')$ which gives:
$$\frac{\partial}{\partial r(y'|x')} F(r)= p(x') \log \frac{r(y'|x')}{\sum_{\bar{x}} p(\bar{x}) r(y'|\bar{x})}.$$
Since examples with $r(y'|x')<\sum_{\bar{x}} p(\bar{x}) r(y'|\bar{x})$ are easy to construct this derivative can be negative so that $F(r)$ is not nondecreasing in general.
As far as I can see this does not imply that $F(q)$ is not convex, only that this way of showing it fails.
[1] Cover, Thomas M.; Thomas, Joy A., Elements of information theory, Wiley Series in Telecommunications. New York: John Wiley & Sons, Inc. xxii, 542 p. (1991). ZBL0762.94001.)
[2] Boyd, Stephen; Vandenberghe, Lieven, Convex optimization., Cambridge University Press (ISBN 0-521-83378-7/hbk). xiii, 716 p. (2004). ZBL1058.90049.


text:
Q: Laravel auth session cookie not sending So I have a pretty basic Laravel login script
$email = Input::get('email');
$password = Input::get('password');
if(Auth::attempt(array('Email'=>$email, 'password'=>$password), true)){
    return Response::json(array('success' => true,'logged_in'=>Auth::check() ));
}

I'm logging in with a valid Email and Password. I've put "logged_in" in the response array just as a test, and it returns true after the attempt. However, the "laravel_session" cookie is not returned on the response, and subsequent calls do not see the user as logged in. This is only happening on my Production server, my local environment and test environment both work with no issue.
As another note, I noticed that Response::json is returning the text/html MIME type, instead of application/json. I wasn't sure what was causing that, so I just set the jQuery.ajax dataType to "json" to get around it. This only happens on my production server as well. I'm all out of ideas on this one, and would be very thankful for some help.

A: Deep in one of my configuration files, someone (probably me) had inserted a space before the <? beginning of a PHP file. This was before any headers were set, and so they weren't allowed to be changed (meaning no cookies could be set) since data had already been written to the output stream. So if you're searching for why this is happening to you, make sure you look for that.

A: Probably, your controller works good and sets cookie truely.But your browser can't save your cookies. Because of headers domain restrictions.
Can you sure your cookie system works good. Can you check app/config/session.php domain field looks like this.
'domain' => null,

A: Try removing the second boolean parameter (Auth::check(array, boolean)) or check if your user table has a remember_token column.

If you would like to provide "remember me" functionality in your application, you may pass true as the second argument to the attempt method, which will keep the user authenticated indefinitely (or until they manually logout). Of course, your users table must include the string remember_token column, which will be used to store the "remember me" token.

Also, either your code is flawed (you made a typo) or you have a weird database structure, because the email fields is written with uppercase.
array('Email'=>$email, 'password'=>$password)

to
array('email'=>$email, 'password'=>$password)

A: Since I had a similar problem, there is one other problem it could be:
You forgot to use the "web" middleware group.
'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    // ... and more
],

If you do not, the queued cookies are never set.


text:
Q: Ansible: Create dictionary from an intent file shell> cat myfile.yml
"ABC":
    "ABC-C01":
       - host: "a1"
         prefixlen: "19"
       - host: "a2"
         prefixlen: "19"
"DEF":
    "DEF-C01":
       - host: "d1"
         prefixlen: "19"
       - host: "d2"
         prefixlen: "19"

My expected answer below from the intent file :
  ABC-C01:
    - a1.domain
    - a2.domain
  DEF-C01:
    - d1.domain
    - d2.domain

I was able to get the list individually.
- include_vars:
    file: myfile.yml
    name: myfile
- set_fact:
    dc: "{{ myfile.keys()|list }}"

Gives: 'ABC' and 'DEF'
- set_fact:
    cl: "{{ cl|default([]) + myfile[item].keys()|list }}"
  with_items: "{{ dc}}"

Gives: 'ABC-C01' and 'DEF-C01'

A: Put the below declarations into the vars
myfile: "{{ lookup('file', 'myfile.yml')|from_yaml }}"
myfile_groups: "{{ dict(myfile.values()|
                        map('dict2items')|
                        json_query(_query)) }}"
_query: '[].[key, value[].join(``,[host, `.domain`])]'

gives what you want
myfile_groups:
  ABC-C01:
    - a1.domain
    - a2.domain
  DEF-C01:
    - d1.domain
    - d2.domain


text:
Q: Which class do I place the fields related to an object in? Hi I'm new to OOP and I can't seem to find information on this problem I have. Any help would be great. I'm working in C#
So I have a base abstract class Animal, and a derived class Pig. I want to have other derived classes such as a cow etc. Each animal need to have a name.
Do I place the AnimalName field as protected in the base class and use base.AnimalName to access? Or should the name field belong to the derived class as a private/protected field?
My thinking is that if I have abstract methods that need to be overwritten, should be name field not follow a similar format or should it rather just be declared in the derived class.
Is there is a convention to this?

A: If the attribute Name is inherent to being an Animal (every Animal must have it), then place it in the Animal abstract class, as protected, or as private with getters and setters (more common).

A: An abstract class, as @Ivan describes, is a good idea. But, sometimes your namespace will actually benefit from using nested classes. Then, you can overwrite AnimalName in a similar manner.
Check out this answer for more: https://stackoverflow.com/a/10507130/14414944
Edit: Per CoolBots request, check out this C# Fiddle. There are some good nuggets there to chew on.
I would also recommend supplementing your OOP learning by reading about Composition vs. Inheritance in C#.


text:
Q: Finding the different possible combinations File A has rows of genes:

A,B,C,D,E
  P,Q,R
  G,D,V,K
  L,Q,X,I,U,G and so on.

Taking each row at a time, how can one get the following type of output:
For the first row:

A,B,C
  B,C,D
  C,D,E

For the second row:

P,Q,R

For the third row:

G,D,V
  D,V,K

Essentially, what I would like is to find "triplets" of genes from each row. The first triplet will have the first three genes. The second triplet will have the second,third,fourth genes. The last triplet will end with the last gene in the row.
Achieving this manually will be a mammoth task. Since I have yet to master Linux, Perl or Python scripts to be able to write a script for this, help from this community will be appreciated!

A: Using awk:
function wprint() {
    print w[1], w[2], w[3];
}

function wshift(e) {
    w[1] = w[2]; w[2] = w[3]; w[3] = e;
}

BEGIN { FS = OFS = "," }

{
    wshift($1);
    wshift($2);
    wshift($3);
    wprint();

    for (i = 4; i <= NF; ++i) {
        wshift($i);
        wprint();
    }
}

Then:
$ awk -f script data.in
A,B,C
B,C,D
C,D,E
P,Q,R
G,D,V
D,V,K
L,Q,X
Q,X,I
X,I,U
I,U,G

The awk script uses a three element moving window, w.  For each input row, it populates the three elements of the window with the three first fields and prints these as a comma-separated list (followed by newline). It then iterates over the remaining fields on the line, shifting them into the window and printing the window for each element.
If any line in the input data contains less than two fields, you will get things like
A,,

or
A,B,

in the output.
If you are certain that every input line has at least three fields (or if you want to disregard any line that doesn't), then you may shorten the awk script slightly:
function wprint() {
    print w[1], w[2], w[3];
}

function wshift(e) {
    w[1] = w[2]; w[2] = w[3]; w[3] = e;
}

BEGIN { FS = OFS = "," }

{
    for (i = 1; i <= NF; ++i) {
        wshift($i);
        if (i >= 3) {
            wprint();
        }
    }
}

A generalization of the first variation of the script with a variable window size:
function wprint(i) {
    for (i = 1; i < n; ++i) {
        printf("%s%s", w[i], OFS);
    }
    print w[n]
}

function wshift(e,i) {
    for (i = 1; i < n; ++i) {
        w[i] = w[i + 1];
    }
    w[n] = e;
}

BEGIN { FS = OFS = "," }

{
    for (i = 1; i <= n; ++i) {
        wshift($i);
    }
    wprint();

    for (i = n + 1; i <= NF; ++i) {
        wshift($i);
        wprint();
    }
}

Using it:
$ awk -v n=4 -f script data.in
A,B,C,D
B,C,D,E
P,Q,R,
G,D,V,K
L,Q,X,I
Q,X,I,U
X,I,U,G

A: With perl:
perl -F, -le 'BEGIN { $, = "," } while(@F >= 3) { print @F[0..2]; shift @F }' file

With awk:
awk -F, -v OFS=, 'NF>=3 { for(i=1; i<=NF-2; i++) print $i, $(i+1), $(i+2) }' file

A: Using Perl we can tackle it as:
perl -lne '/(?:([^,]+)(?=((?:,[^,]+){2}))(?{ print $1,$2 }))*$/' yourfile
perl -F, -lne '$,=","; print shift @F, @F[0..1] while @F >= 3'
perl -F, -lne '$,=","; print splice @F, 0, 3, @F[1,2] while @F >= 3'

which can be written in an expanded manner as shown below:
perl -lne '
   m/
      (?:                       # set up a do-while loop
         ([^,]+)                # first field which shall be deleted after printing
         (?=((?:,[^,]+){2}))    # lookahead and remember the next 2 fields
         (?{ print $1,$2 })     # print the first field + next 2 fields
      )*                        # loop back for more
      $                         # till we hit the end of line
   /x;
' yourfile

And with sed we can do it with an assortment of it's commands:
sed -e '
   /,$/!s/$/,/     # add a dummy comma at the EOL

   s/,/\n&/3;ta    # while there still are 3 elements in the line jump to label "a"
   d               # else quit processing this line any further

   :a              # main action
   P               # print the leading portion, i.e., that which is left of the first newline in the pattern space
   s/\n//          # take away the marker

   s/,/\n/;tb      # get ready to delete the first field
   :b

   D               # delete the first field, and apply the sed code all over from the beginning to what remains in the pattern space
' yourfile

Dc can also do this :
sed -e 's/[^,]*/[&]/g;y/,/ /' gene_data.in |
dc -e '
[q]sq                            # macro for quitting
[SM z0<a]sa                      # macro to store stack -> register "M"
[LMd SS zlk>b c]sb               # macro to put register "M" -> register "S"
[LS zlk>c]sc                     # macro to put register "S" -> stack
[n44an dn44an rdn10anr z3!>d]sd  # macro to print 1st three stack elements
[zsk lax lbx lcx ldx c]se        # macro that initializes & calls all other macros
[?z3>q lex z0=?]s?               # while loop to read in file line by line and run macro "e" on each line
l?x                              # main()
'

Results
A,B,C
B,C,D
C,D,E
D,E,F
E,F,G
P,Q,R
G,D,V
D,V,K
L,Q,X
Q,X,I
X,I,U
I,U,G


text:
Q: How to Rotate QPixmap around center without cutting off parts of the image Let's say I have a QPixmap that has the dimensions of (20 x 100). How can I create a copy of this QPixmap that's rotated a specific amount and also has new dimensions to allocate the new dimensions of the rotated pixmap?
I've found multiple examples on how to rotate using QPainter and QTransform, but none seem to provide a proper manner to keep the QPixmap from cutting off.
The best example I've found so far is:
// original = Original QPixmap

QSize size = original.size();

QPixmap newPixmap(size);
newPixmap.fill(QColor::fromRgb(0, 0, 0, 0));

QPainter p(&newPixmap);
p.translate(size.height() / 2, size.height() / 2);
p.rotate(35); // Any rotation, for this example 35 degrees
p.translate(size.height() / -2, size.height() / -2);
p.drawPixmap(0, 0, original);
p.end();

This rotates a QPixmap, and places it on a new QPixmap of the same dimensions. However, I am at a loss on how to modify this to work with new dimensions.
I've even tried simply modifying the initial size of the new pixmap, but that just causes the image to be off center (and still cut off for some reason?)
Any support would be appreciated!

A: One way to do this would be to calculate the minimum bounding rect for your rotated image and to create a new pixmap with these dimensions onto which you can render your rotated image which is now guarenteed to fit. To do this you could take each corner point of your image rectangle and rotate them around the center. The resulting points can then be used to calculate your minimum bounding rectangle by looking at each point and finding both the minimum and maximum x and y values.
For example in the following hypothetical example we have a 100x100 rectangle. If we use a simple algorithm to rotate each corner point of the rectangle around the center by our angle (in this case 45 degrees) we get the four new corner points (50, -20), (-20, 50), (120, 120) and (50, 120). From these points we can see the minimum x value is -20, the minimum y value is -20, the maximum x value is 120 and the maximum y value is 120, so the minimum bounding rect can be described by topLeft:(-20, -20)  and bottomRight:(120, 120).

To help you with this here is a function taken from another stackoverflow post for rotating a point around another point:
QPointF getRotatedPoint( QPointF p, QPointF center, qreal angleRads )
{
    qreal x = p.x();
    qreal y = p.y();

    float s = qSin( angleRads );
    float c = qCos( angleRads );

    // translate point back to origin:
    x -= center.x();
    y -= center.y();

    // rotate point
    float xnew = x * c - y * s;
    float ynew = x * s + y * c;

    // translate point back:
    x = xnew + center.x();
    y = ynew + center.y();

    return QPointF( x, y );
}

And here is a function I wrote that uses it to calculate the minimum bounding rect for some rectangle rotated by some angle...
QRectF getMinimumBoundingRect( QRect r, qreal angleRads )
{
    QPointF topLeft     = getRotatedPoint( r.topLeft(),     r.center(), angleRads );
    QPointF bottomRight = getRotatedPoint( r.bottomRight(), r.center(), angleRads );
    QPointF topRight    = getRotatedPoint( r.topRight(),    r.center(), angleRads );
    QPointF bottomLeft  = getRotatedPoint( r.bottomLeft(),  r.center(), angleRads );

    // getMin and getMax just return the min / max of their arguments

    qreal minX = getMin( topLeft.x(), bottomRight.x(), topRight.x(), bottomLeft.x() );
    qreal minY = getMin( topLeft.y(), bottomRight.y(), topRight.y(), bottomLeft.y() );

    qreal maxX = getMax( topLeft.x(), bottomRight.x(), topRight.x(), bottomLeft.x() );
    qreal maxY = getMax( topLeft.y(), bottomRight.y(), topRight.y(), bottomLeft.y() );

    return QRectF( QPointF( minX, minY ), QPointF( maxX, maxY ) );
}

So now we have the minimum bounding rectangle for our rotated image we can create a new pixmap with its width and height and render our rotated image to it at the center. This is tricky because of the transformation involved which makes it a bit more confusing as to what your source and target rects might be. It's actually not as hard as it might seem. You perform your translation / rotation to rotate the paint device around the center, then you can simply render your source image onto your destination image exactly as you would if you were rendering the source to the center of the destination.
For example:
QPixmap originalPixmap; // Load this from somewhere
QRectF minimumBoundingRect = getMinimumBoundingRect( originalPixmap.rect(), angleRads);

QPixmap rotatedPixmap( minimumBoundingRect.width(), minimumBoundingRect.height() );
QPainter p( &rotatedPixmap );
p.save();

// Rotate the rotated pixmap paint device around the center...
p.translate( 0.5 * rotatedPixmap.width(), 0.5 * rotatedPixmap.height() );
p.rotate( angleDegrees );
p.translate( -0.5 * rotatedPixmap.width(), -0.5 * rotatedPixmap.height() );

// The render rectangle is simply the originalPixmap rectangle as it would be if placed at the center of the rotatedPixmap rectangle...
QRectF renderRect( 0.5 * rotatedRect.width() - 0.5 * originalPixmap.width(),
                   0.5 * rotatedRect.height() - 0.5 * originalPixmap.height(),
                   originalPixmap.width(),
                   originalPixmap.height() );
p.drawPixmap( renderRect, originalPixmap, originalPixmap.rect() );

p.restore();

And voila, a nicely rotated image with no corners chopped off.


text:
Q: Language translator using java I want to create a language translator using java. All translators are using the resources from google translate so they are not standalone. but i want to create a standalone application which doesnt use internet to translate the text. please guide me how to do this

A: If you want to translate just 1 word you need a database or file which have the translations. Just read in a word, search for it and put out the other value. If you want to translate complete texts - have fun, that's a whole other world.

A: It is not a simple argument.
You need to study the theory of machine translation.
Start reading some info about that on wikipedia
http://en.wikipedia.org/wiki/Machine_translation


text:
Q: Add characters between string I have a string like

A, B, C, D, E

Now I want to add single quotations to this like

'A', 'B', 'C', 'D', 'E'

How can I do this in C#.net?
Thanks.

A: Using string methods and LINQ combination, you can do it easily:
var str = "A, B, C, D, E";
var result = string.Join(", ",
                         str.Split(',').Select(x => string.Format("'{0}'", x.Trim())));

A: You can use Regex...
var newstr = Regex.Replace("A, B, C, D, E", @"\w", "'$0'");

A: You can use Replace:
string s = "A, B, C, D, E";
s = "'" + s.Replace(", ", "', '") + "'";

A:     string addQuotes(string val)
    {
        string[] ss = val.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        string res = "";
        foreach (string s in ss) res += (res == "" ? "" : ", ") + "'" + s + "'";
        return res;
    }

    void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = addQuotes(textBox1.Text);
    }


text:
Q: Threejs: Change color of only one child object i have a problem with changing the color of a element of my 3D Model (imported with the GLTFLoader). I added some pictures of the structure of the model.
I want to change the color of the marked children element in red. The path is: children[0].children[31].children[10].children[1]

If i change the color in the property material, the elements of the object with the same color (in this case white) change their color to red.
The object is exported with Siemens NX. I think the problem is the structure of the 3D Model. The children elements for example do not have a name (they have a name but it is like mesh_736). So for the future I have to add names to the object elements. Does anyone work with NX, too? How can I organize a object the right way to work easy with Threejs with it?

A:
If i change the color in the property material, the elements of the object with the same color (in this case white) change their color to red.

This probably happens because these objects share the same material. Try to  clone the material first and then change its color property. This approach should not affect other objects.
const material = object.material.clone();
material.color.set( 0xff0000 );
object.material = material;

A: Here is my take on the question and I am no expert but I struggled with this for a couple days so here is my response. All I set out to do was to change a color from a specific part from the resulting GTLF/GLB file
// this traverse's through the scene objects children and parents.
const SetColorTEXTURE = (c) => {
  console.log('BREAK1', c);
  Viewer.scene.traverse(function (child) {
    console.log('BREAK2C ', child)
    if (child.name.includes('XXXXXX-PCB-XXX-XXXX')) {
      for (const i of child.children) {
        console.log('BREAK2B ', i)
        if (i.isMesh) {
          console.log('BREAK2A ', i)
          i.material.color = new THREE.Color('rgb(212,175,55)');

        }

      }
    }
    if (child.isMesh) { ...

What I figured out is that the STEP file I had doesn't necessarily have the needed grouping and setup for 2 main things.

*

*The grouping of the children. From what I see all of the children hold their own styling that can also be tied to MaterialStandardMesh namespace. I will get to that more in the 2nd point. The reason why I was having an issuing styling a particular Mesh is because the parent was the top level namespace and like the original OP had a name of "". This is what was so confusing to me too. I could make the Mesh not visible but I couldn't add 1 color style or texture to that particular item.

Here is how the Mesh looks in the console for a specific item. Notice the 4 parts. 1. There is a parent: Group with a name of "" which has a parent: scene with a 2. name of xx-scene. That's the main scene.
You'll also notice the 3. the material: MeshStandardMaterial has a name of '' empty. Again, more on that in the second part.
In other words everything is going back from the parent: Group and Scene which is actually a tree, to the main parent/scene which is xxx-scene #2 in the image below.
Scene
  |
  -- Group
  |
  -- PerspectiveCamera

*From this information there would be 2 ways to isolate a specific item in the GTFL/GLB file. One, from the information I showed previously. I will show an example below.  And 2 would be to create and name specific material: MeshStandardMaterial properties.

This is items 3,4 in the diagram below. As you see, there is no name for that property either so as a result it is an empty namespace and everything with the main scene is going to be the same color/texture no matter what you do. There is no setting of a parent.child or material classification difference so you can't change the separately from what I see.
This is why the cloning doesn't work because you're just cloning the same problem without creating another scene, potentially. In any event, that didn't work for me in any easy way.

In the code snippet above I test my theory by isolating a child of the parent scene. In this case I was able to isolate all of the Mesh for that child and change only those properties.
In the console screenshot below it illustrates a child of a parent which was a child of Scene carries its own Object3D and Mesh. In this case even without the material specific properties of each Mesh I was still able to alter the specific item in this case.

In this picture below you can see the 3 different colors applied with code snippet above and the traversal mechanism of the Viewer.scene.Traverse method.


text:
Q: print unordered_map I have unordered_map. which has client and their associated users in std::list.
I can print my client, but don't know how to print its userslist.
mapType clientUserMap;

clientUserMap.insert (mapType::value_type("C1", std::list<std::string> (userlist)));

boost::unordered_map<std::string, std::list<std::string> >
         ::const_iterator it = clientUserMap.find("C1");

 std::cout << it->first << std::endl;

A: It's a list, so iterate through the list and print.. e.g.
for(std::list<std::string>::const_iterator l_it = begin(it->second); l_it != end(it->second); ++l_it)
  std::cout << *l_it << std::endl;

Of course there are many more fancy ways of doing this...

A: All you have to do is iterate over the list:
std::list<string> const &users = it->second;
std::for_each(users.begin(), users.end(), [](string const& user){std::cout << user << std::endl;}

A: as you already using boost, you could also use BOOST_FOREACH to iterate over the user list.
The code would then look like this:
#include <boost/foreach.hpp>
...

boost::unordered_map<std::string, std::list<std::string> >
  ::const_iterator it = clientUserMap.find("C1");

std::cout << it->first << std::endl;

BOOST_FOREACH( std::string user, it->second )
{
   std::cout << user << endl;
}


text:
Q: Using "valign-wrapper" & "right-align" together Materialize-CSS: Can valign-wrapper & right-align be used together in a single h5 tag ?
What I have observed untill now is, When they are used together, the text inside h5 is vertically aligned but not aligning to the right.
I want my text be both vertical & right aligned.
Please let me know if you know how to achieve this.
TIA
Jagan

A: valign wrapper use display flex. So just add justify-content: flex-end; to align right in your div class in which you are using v-align.
Here is the code in jsfiddle
There are many other approaches to do this. One of them is, use valign wrapper for verticle center and make them relative and h5 as absolute and right:0 to make it right align. Here is the jsfiddle code
another one is,you can use make parent div as display:table and h5 as display:table-cell. Below is the snippet:-

.heading{

display: table-cell;
  vertical-align: middle;
text-align:right;
}

Hi this is testing

A: Use Flexbox

.parent {
    height: 300px;
    width: 300px;
    background: red;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

Hi this is testing

A: Use the justify-content to .child too:
.child {
    justify-content: flex-end;
}

A: when using the valign-wrapper for a tag it makes that element:
.valign-wrapper{
display:flex;
align-items:center;
}

you can add the following is your css to make it center aligned:
.valign-wrapper{
justify-content:flex-end;
}


text:
Q: agregar datos desde la base de datos al combobox hola estoy tratando de seleccionar los datos de la tabla genero con la consulta select sexo from genero en un combobox, pero el combobox no me devuelve nada, este es el codigo que tengo el cual es el siguiente.
public void llenadocombobox() {
        Connection conn=null;
        ObservableList <String> listacombo= FXCollections.observableArrayList();

        String consulta = "select sexo from genero";
        try {

            conn = DriverManager.getConnection("jdbc:sqlserver://DESKTOP-4JA6SFR:1433;databaseName=prueba", "sa", "123");
            Statement ps =conn.createStatement();
             ResultSet rs =ps.executeQuery(consulta);

            while(rs.next()) {

                listacombo.add(rs.getString("sexo"));

            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        combo.getItems().addAll(listacombo);
    }

declaro un observablelist para guardar los datos y luego mostrarlos en el combobox. alguna ayuda seria genial. gracias.

A: Para este caso no es necesario esta variable:
ObservableList <String> listacombo= FXCollections.observableArrayList();

puedes hacer la actualizacion del combobox de manera simple y dinámica
// patrones es una instancia de ComboBox<String> patrones;
patrones.getItems().addAll("XML Clientes -> ",
                               "XML Proveedores ->",
                               "XML Complementos ->",
                               "XML SAT -> revisar"
                               );


text:
Q: How to get ajax value and store in PHP variable? custom.js file:
$(document).ready(function() {
    $("#company_name").keyup(function() {
        $.ajax({
            type: "POST",
            url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
            data: {
                keyword: $("#company_name").val()
            },
            dataType: "json",
            success: function(data) {
                //alert(data);
                if (data.length > 0) {
                    $('#DropdownCompany').empty();
                    $('#company_name').attr("data-toggle", "dropdown");
                    $('#DropdownCompany').dropdown('toggle');

                } else if (data.length == 0) {
                    $('#company_name').attr("data-toggle", "");
                }
                $.each(data, function(key, value) {
                    if (data.length >= 0)
                        $('#DropdownCompany').append('
' +
                            value['company_name'] + '
');
                });
            }
        });
    });
    $('ul.txtcountry').on('click', 'li a', function() {
        $('#company_name').val($(this).text());
        $('#company_id').val($(this).attr("id"));
        // $('#company_address1').val($(this).text());

        $('#tableCityID').html($(this).attr("id"));
        $('#tableCityName').html($(this).text());
        $('#Address1').html($(this).attr("Address1"));
        $('#Address2').html($(this).attr("Address2"));
        $('#city').html($(this).attr("city"));
        $('#state').html($(this).attr("state"));
        $('#pincode').html($(this).attr("pincode"));
    });
});

I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '';

and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";

I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15

If anybody faces this problem, please help me. Thanks in advance.

A: just use the
like this
$com = '';


text:
Q: JS: Qué diferencia hay entre parseFloat( variable, 10) vs (1 * variable)? He visto que en los ejemplos, no sólo aquí sino en la literatura y guías de javascript, cuando hay que castear un string compuesto de puros números, se usa:
var foo = '12345.10';

var numeric_foo = parseFloat(foo, 10);

He encontrado varias ocurrencias en mi código en donde simplemente hice
var numeric_foo = 1 * foo;

Y eso obviamente tiene cara de ser un atajo poco elegante. Pero no entiendo bien ¿En qué caso el segundo tipo de casteo me puede dar un valor  inconsistente?
Probé aplicar ambas maneras a strings que contenían números, pero ambos me dieron NaN.

A: La diferencia como tal es que el parseFloat, te corta el texto al momento de hacer el parseo si se encuentra con un caracter no deseado, ya que si tu primer caracter es numero, esta cadena sera interpretada como int ejemplo:
var foo = '1 Lore Ipsum';
var numeric_foo = parseFloat(foo, 10);
console.log(numeric_foo); //Imprime 1

var numeric_foo2 = 1 * foo;
console.log(numeric_foo2); //Imprime NaN

Otro ejemplo:
var foo = '123451%%%545454';
var numeric_foo = parseFloat(foo, 10);
console.log(numeric_foo); // IMprime 123451

var numeric_foo2 = 1 * foo;
console.log(numeric_foo2); //Imprime NaN

El unico caracter aceptado es el punto (.) ya que es separador de decimales:
var foo = '123451.545454';
var numeric_foo = parseFloat(foo, 10);
console.log(numeric_foo); //imprime 123451.545454

var numeric_foo2 = 1 * foo;
console.log(numeric_foo2); //imprime 123451.545454

Mientras que 1 * foo asegurara que foo sea un integer/float y tratara de hacer la operacion, por eso el NaN.
Adicionalmente se nota que el parseFloat trata de no reventar el codigo al momento de ver algo como esto var foo = '1 Lore Ipsum'; Cosa que en lo particular no esta del todo bien, ya que en lo particular en una ocasion pasada perdi mucho timpo por parsear un string en numero que no era valido y el parseFloat lo tomaba como que si lo era.


text:
Q: awk to cut portion of a field and still print entire line I have this line:
08:30:02.480507 IP 192.168.100.150.65119 > 192.168.100.151:53 59865 [1au] A? click.em.redbox.com. (48)

I need to cut out the ".480507" in the timestamp so the line looks like this:
08:30:02 IP 192.168.100.150.65119 > 192.168.100.151.53: 59865 [1au] A? click.em.redbox.com. (48)

I've fumbled around with several awk and cut statements but to no avail. I'd like to find an awk one liner but sed may be a better solution for this. I just don't know quite enough about either one when it comes to cutting in this fashion.
NOTE: This is an example, and the portion of the timestamp I need to cut out will not be the same, as I need to perform this action on a number of lines all with different timestamps.

A: I would use awk
awk --posix '{ gsub(/\.[[:digit:]]{6}/, "", $1); print }' filename
Will target the first field (space delimited) and search for a . followed by 6 numbers and empty it out.

A: With awk probably the simplest way is to do a regular expression substitution on the first whitespace-separated field, replacing everything from the period to the end of the field:
awk '{sub(/\..*/,"",$1)}1' somefile

A: with GNU sed
sed -r 's/^([^.]+)\.[0-9]+ /\1 /' filename

*

*^([^.]+) capture starting string upto first dot character

*\.[0-9]+ match dot character followed by more than 1 digit characters

and if number of characters is consistent as given in the example,
sed -r 's/^(.{8}).{7} /\1 /' filename


text:
Q: Model initialization I have custom module named Rkt_CustomBlock. I am trying to connect it to the database. My table name is socialcoupon. My path of the module is public_html/dev/app/code/local/Rkt/CustomBlock/Model. what I want to know is what should i put in  Rkt.php. The xml declaration is working.
     <?php
class Rkt_customblock_Model_Mysql4_Rkt extends Mage_Core_Model_Mysql4_Abstract
{
     public function _construct()
     {
         $this->_init('rkt/socialcoupon', 'scid');
     }
}

I am confused about $this->init. what should i put in it? is it rkt/rkt? or something else
my config file
<?xml version = "1.0"?>
<config>
    <modules>
        <Rkt_CustomBlock>
            <version>1.0.0</version>
        </Rkt_CustomBlock>
    </modules>
    <frontend>
        <routers>
            <rkt_customblock>
                <use>standard</use>
                <args>
                    <module>Rkt_CustomBlock</module>
                    <frontName>helloworld</frontName>
                </args>
            </rkt_customblock>
        </routers>
        <layout>
            <updates>
                <rkt_customblock>
                    <file>rkt_customblock.xml</file>
                </rkt_customblock>
            </updates>
        </layout>
    </frontend>
    <global>
        <blocks>
            <rkt_customblock>
                <class>Rkt_CustomBlock_Block</class>
            </rkt_customblock>
        </blocks>
        <models>
            <customblock>
                <class>rkt_customblock_Model</class>
                <resourceModel>customblock_mysql4</resourceModel>
            </customblock>
            <customblock_mysql4>
                <class>rkt_customblock_Model_Mysql4</class>
                <entities>
                    <socialcoupon>

socialcoupon

                    </socialcoupon>

                </entities>
            </customblock_mysql4>
        </models>
        <resources>
            <customblock_setup>
                <setup>
                    <module>rkt_customblock</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </customblock_setup>
            <customblock_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </customblock_write>
            <customblock_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </customblock_read>
        </resources>
    </global>
</config>

A: In Magento you can call your custom entity socialcoupon in this way.
Mage::getModel('rkt_customblock/socialcoupon')->load(5); //this will load
      //social coupon with id = 5;

This short code will load a socialcoupon item with an id = 5 from the database. Let us look how magento correctly "parse" your entity here.
General format : Mage::getModel('[model_group_name]/[entity_name]').
In our case model group name is rkt_customblock and entity name is socialcoupon. Using model group name, magento will identify which module responsible for the specified model group name and then locate the model location folder. We are setting up these values via config.xml.
Similarly socilacoupon entity should also set up via config.xml. So your module should hold following model configuration.
File : app/code/local/Rkt/CustomBlock/etc/config.xml
   <models>
        <rkt_customblock>
            <class>Rkt_CustomBlock_Model</class>
            <resourceModel>rkt_customblock_resource</resourceModel>
        </rkt_customblock>
        <crkt_customblock_resource>
            <class>Rkt_CustomBlock_Model_Resource</class>
            <entities>
                <socialcoupon>

socialcoupon

                </socialcoupon>
            </entities>
        </rkt_customblock_resource>
    </models>

Important points note to here are

*

*<rkt_customblock> : this is the model group name. Rule for model group name is, it should be unique. You have used customblock. There is no problem in that. But there is a huge chance to have that model group name is used by any other extension. So in order to avoid such conflicts, magento best practice says that, model group name should follow namespace_modulename format. So in your case it would become rkt_customblock.

*<class />: When magento called out by a particular model group name, then magento will look into this node in order to trace the model location for that module group name. Here we set this node with a value Rkt_CustomBlock_Model.Please note, those capitalizations in the value are very important here. This means magento now will look into app/code/local/Rkt/CustomBlock/Model/ directory for all of your module's model classes.

*<resourcemodel /> : Resource models are used to communicate with the database. They are making real communication with database. When you call Mage::getModel(), magento will internally call Mage::getResourceModel(). This method uses configurations provided inside this node and hence it is very important to configure this node correctly. Here we are set rkt_customblock_resource to this node. You have used customblock_mysql4. You can use that value too. But it is deprecated. From Magento 1.6, magento follows the practice [model_group_name]_resource. So in our case, it would become rkt_customblock_resource.

*<rkt_customblock_resource /> : this node configuring resource model configuration. The name of this node is came from <resourcemodel /> node. So when you call Mage::getModel(rkt_customblock/[entityname]), then magento will internally call the method Mage::getResourceModel('rkt_customblock/[entityname]'), which then eventually ends up in <class /> node which comes inside <rkt_customblock_resource /> node. This <class /> node specifies where is resource model classes are residing. We set a value Rkt_CustomBlock_Model_Resource here. Capitalization is again very important here. According to this value, magento will look for resource model classes inside app/code/local/Rkt/CustomBlock/Model/Resource/ directory.

*<entities />: this is used to setup an entity inside our model. Here we setup socialcoupon entity.
 node holds table name used by socialcoupon entity.
Now we studied model configuaration we needed. Now we need to setup socialcoupon entity and its resources inside module's mode section. Let us do that.
File Structure
rootdir
|________ app
        |________ code/local/Rkt/CustomBlock
                |________ etc
                |           - config.xml
                |________ Model
                        |   - Socialcoupon.php
                        |________ Resource
                                |   - Socialcoupon.php
                                |_________ Socialcoupon
                                                - Collection.php

First setup a folder structure like this (along with other files). Captitalizations are very important here.
Entity Definition
File : app\code\local\Rkt/CustomBlock/Model/Socialcoupon.php
<?php
class Rkt_CustomBlock_Model_Socialcoupon extends Mage_Core_Model_Abstract
{
    protected function _construct()
    {
        //follows the format [model_group_name]/[entity_name]
        $this->_init('rkt_customblock/socialcoupon');
    }
}

Calling to  _init() via _construct() method is very important. Every model entity should follow this format.
Resource Model Entity Definition
File : app\code\local\Rkt/CustomBlock/Model/Resource/Socialcoupon.php
<?php
class Rkt_CustomBlock_Model_Resource_Socialcoupon extends Mage_Core_Model_Resource_Db_Abstract
{
    protected function _construct()
    {
        //follows the format [model_group_name]/[entity_name]
        $this->_init('rkt_customblock/socialcoupon', 'sc_id');
    }
}

There are two types of models. Flat Models and EAV Models. They are distinguished by reosurce model setup. What is these two types models is out of topic here. Here I am going to assume you want to setup a Flat Model. For flat models, your resourece model class should extend from Mage_Core_Model_Resource_Db_Abstract. This class is also contain _construct() class and it agains calls _init() method within it. But this time, an additional parameter passing. sc_id stands for the primary column of your table. Replace this paramter with your primary column name of your table.
Resource Model Collection Entity Definition
Job is not over. By above your configuration, you can get a single item from your entity by calling
 Mage::getModel('rkt_customblock/socialcoupon)->load(1); //provided some data exist in table.

However if you want to get a collection of items, then you need to configure collection resource model for your entity. This is what we are going to do here.
File : app\code\local\Rkt/CustomBlock/Model/Resource/Socialcoupon/Collection.php
<?php
class Rkt_CustomBlock_Model_Resource_Socialcoupon_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    protected function _construct()
    {
        //follows the format [model_group_name]/[entity_name]
        $this->_init('rkt_customblock/socialcoupon');
    }
}

Main point note here is, this class extends from Mage_Core_Model_Resource_Db_Collection_Abstract and it also contains _construct() method as all other method does.
Now you are good to go clear your cache and tries to load your model with this call
 Mage::getModel('rkt_customblock/socialcoupon');

Hope that will help