text:
Q: How to open Wifi settings inside from a BroadcastReceiver I am working on an Android application that could recognize if the device is connected to a Network. If not, application display an AlertDialog and give the chance to the user to go to the device settings and open the wifi.
I have create a BroadcastReceiver for this job but i dont know how i can create an AlertDialog and give the option to the user to enable the the wifi.
Here is the code of BroadcastReceiver.
public class ExampleBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {
    if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
        boolean noConnectivity = intent.getBooleanExtra(
                ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
        );
        if (noConnectivity) {
            AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
            builder1.setMessage("You must have internet connection");
            builder1.setCancelable(true);

            builder1.setPositiveButton(
                    "Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    });

            builder1.setNegativeButton(
                    "No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            builder1.create();
            builder1.show();

        } else {
            Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
        }
    }
}

}

A: Please note, the below code is just for your reference. You could update/change this code based on your requirement.
public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mNetworkReceiver;

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

    }

private void registerNetworkBroadcastForNougat() {
    mNetworkReceiver = new NetworkChangeReceiver();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
}

protected void unregisterNetworkChanges() {
    try {
        unregisterReceiver(mNetworkReceiver);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterNetworkChanges();
}

class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent)
    {
        try
        {
            if (!isOnline(context)) {
                showDialog(context);
            }

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

    private void showDialog(final Context context) {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
        builder1.setMessage("You must have internet connection");
        builder1.setCancelable(true);

        builder1.setPositiveButton(
                "Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
                    }
                });

        builder1.setNegativeButton(
                "No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        builder1.create();
        builder1.show();
    }

    private boolean isOnline(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            //should check null because in airplane mode it will be null
            return (netInfo != null && netInfo.isConnected());
        } catch (NullPointerException e) {
            e.printStackTrace();
            return false;
        }
    }
}

}


text:
Q: C# Regex getting words that start with? How can I use a regular expression to get words that start with ! ? For example !Test.
I tried this but it doesn't give any matches:
@"\B\!\d+\b"

Although it did work when I replaced the ! with $.

A: I'd say that your regex was quite OK already, you just need to use \w (alphanumeric character) instead of \d (digit):
@"\B!\w+\b"

will match any word that is immediately preceded by a ! unless that ! itself is preceded by a word itself (that's what the \B asserts). Using a ^ instead will limit the matches to words that start at the beginning of a line which might not be what you want.
So this will match all the words including exactly one preceding ! in this line:
!hello !this ...!will !!!be !matched!

but none of the words in this line:
this! won't!be matched!!!

You could also drop the \B altogether if you don't mind matching !that in this!that.

A: This should work:    ^!\w+
 MatchCollection matches = Regex.Matches (inputText, @"^!\w+");

 foreach (Match  match in matches)
 {
      Console.WriteLine (match.Value);
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: int('10000000000000000000000000000001',2) does not return negative value >>>a='11111111111111111111111111110101'
>>>int(a,2)
4294967285

In the above code, I thought that 32'nd number is MSB(Most Significant Bit) and if MSB is 1, The value indicates negative.
but why does the int() function return positive number?

A: In Python that works a bit different, it is using two complements. I think the answer to the question here is what you are looking for and answers the 'why?'. You can test that yourself by using the bin()-function which returns you the bit equivalent  of a number.
a='11111111111111111111111111110101'
print(int(a,2))
#4294967285

# Postive Integer
# Same as above
b='0b11111111111111111111111111110101'
print(int(b,2))
#4294967285

# Negative Integer
=c'-0b11111111111111111111111111110101'
print(int(c,2))
#-4294967285


text:
Q: Where to know the URL for a community page When I created a community with a template.
There are already some out-of-box pages.
Each page should have a URL to access it.
Take the ForgotPassword for example,
I could see the URL here is ForgotPassword, however I could only access it under /login/ForgotPassword.
I didn't see where should we configure it. Any idea?

A: You cannot customize the "URL" in the standard "Forgot Password" page. If you hover around the "info" icon, you will get to see the details as below:

The URL of the page. Editable only in custom standard pages.

If at all you want to customize the URL, you will need to:

*

*Create a new custom page. While creating the page (or even after it has been created), you will be able to provide any custom URL that you want to use. Something as below:

*Utilize Identity Component "Forgot Password" to utilize the OOTB password reset functionality

However, remember you will also need to override your standard Login page for this to make sure you provide the link to your new custom page.
Additional note: If you don't see Identity Components in your Org, you will need to reach out to Salesforce Support to enable that. There is some permission that they enable from back-end, and only then those components start showing up in the list.


text:
Q: Whats the difference between Reference and Pointer return types in C++ If I were to create a simple object in C++, what is the difference between returning an address of the member vs. returning a pointer. As far as I'm aware, C++ doesn't have automatic garbage collection so it wouldn't be keeping a reference count. So why would someone do it this way:
class CRectangle {
public:
    string& getName( );
    int&    getWidth( );
    int&    getHeight( );
private:
    string  name;
    int     height;
    int     width;
};

rather than this way:
class CRectangle {
public:
    string* getName( );
    int*    getWidth( );
    int*    getHeight( );
private:
    string  name;
    int     height;
    int     width;
};

I realize these would allow you to access member data, but I'm not concerned about proper encapsulation in this simple example. So whats the difference? Speedup? Readability? Style?

A: The & (in this context) doesn't mean "address of".
A function declared as string& getName( ); returns a reference, not a pointer. A reference is essentially an alias for another object. So in this case, it doesn't return a copy of the object's name, or a pointer to the name, but a reference to the name itself. So any changes to the returned object are directly applied to the object's name.
You could achieve the same by returning a pointer, but there'd be two significant differences:

*

*a pointer requires special syntax to access (the * and -> operators), whereas a reference is used the exact same way you'd use the object itself.

*a pointer can be null, a reference cannot. So any time a pointer is used, you are signalling to the reader of the code that "this value may be null"

A: In this context, the & means reference - not address-of.

*

*A pointer can be 0 - A reference cannot, in a well-formed program.

*Ownership may be more unclear when you return a pointer.

*Readability is subjective - I'd say use a reference when you can.

*For efficiency, there's no real difference.

A: First off, the & form is called a "reference" in C++. The * form is called "pointer" or
"address of".
Speedup - no difference. Readability - probably a slight advantage for references, no derefencing in the upstack code.
Style - explicit breaking of encapsulation is bad enough style to obbscure anything else. If you want an object with naked data, an all-public struct would do just as well.

A: There's no benefit I can think of in returning a pointer to an integer from a property-type method such as getWidth(). It adds the burden of having to track memory ownership; but is actually likely to increase the bandwidth of the return type (both int and pointer sizes are platform specific, and can and do vary, but typical sizes are 32 and 64 bits respectively).


text:
Q: Google Bigtable - how to store data to be able then to query it by country, city and date? I'm looking for a best scheme for my Bigtable to fit the requirement of querying data by specifying a year (or full date), country and (or) city. I've thought about naming my row key as 2019.us.NYC and then query it by prefixes, but its a bad idea because its then will store all my data on one node only until 2020 year comes instead of sharing it to other nodes. Any ideas? Maybe someone already had such a case? The bottleneck here is that it will have about 50 000 000 new rows per second.
Edit: Maybe it's better to use BigQuery?

A: Below is a possible solution, based on your requirements :

*

*50'000'000 writes per second

*low latency for data access

*queries always contain year and country, optionally month, day and city
year + country
Since year and country are always present in your queries, those must figure in the beginning of the row key, like :

*

*2018#de

*2019#de

*2019#us
(I used # to delimit here, but it may be useless if year and country are always defined respectively on 4 and 2 characters. You can remove it to save a byte!).
month + day + city
Because month, day and city are optional, they can also appear on the row key, but rather to the end :

*

*2018#de#0610#frankfurt

*2019#de#0115#berlin

*2019#us#0813#nyc
I suggest you to reorder elements as you want (if queries with year, country and city are the most common, then the order should be year#country#city). Only you can know the most frequent queries. It's always necessary to design your row key with your queries in mind.
Avoid hotspotting
But, as you suggested in your question, this row key design can lead to Bigtable node hotspotting (all writes to a single node because the row keys are contiguous). To solve this and ensure a perfect distribution of the row keys between your nodes, I suggest you to use bucketing.
For each write, you can generate a random number (between 0 and 8, for example if you want 8 buckets), and prepend that bucket number to your rowkey. For example :

*

*3#2018#de#0610#frankfurt

*2#2019#de#0115#berlin

*7#2019#us#0813#nyc
You'll then be sure that your keys will be correctly distributed across your Bigtable nodes when writing.
You can check this link on how to do this on HBase (Bigtable equivalent) : https://hbase.apache.org/book.html#schema.casestudies.log_timeseries.tslead.
Querying data
But because of this bucketing (or salting), you'll need to change the way you query your table. If you want all data for 2019 in US, you'll then need to perform 8 scans (one per bucket) :

*

*start key : 0#2019#us#, end key : 0#2019#us~

*start key : 1#2019#us#, end key : 1#2019#us~

*start key : 2#2019#us#, end key : 2#2019#us~

*start key : 3#2019#us#, end key : 3#2019#us~

*start key : 4#2019#us#, end key : 4#2019#us~

*start key : 5#2019#us#, end key : 5#2019#us~

*start key : 6#2019#us#, end key : 6#2019#us~

*start key : 7#2019#us#, end key : 7#2019#us~
(I used ~ at the end of the end key because ~ in the ASCII table is after all possible characters after the #. For the first scan, for example, this ensures that all row keys beginning by 0#2019#us# are retrieved)
These scans can be performed in parallel for maximum performance.
Scanning is the most performant way to query data in Bigtable. You could also use some filters (like FuzzyRowFilter to query on a row key with a particular regex), but scanning will give definitively give you a better latency. You can also perform scans and use a filter after scanning (for example, to retrieve all data for 2019 in us in nyc, a filter is necessary to get only lines with city = nyc).
Conclusion
So, based on these elements, I'll design my key like :
<bucket_number>#<year>#<country>#<month><day>#<city>

to query my table using scans. Separators (# here) are useless if all fields have fixed length.
You could also have some variants without bucketing if you have a sufficient number of <country> values to distribute the keys to the different nodes :
<year>#<country>#<month><day>#<city>

or :
<country>#<year>#<month><day>#<city>

In conclusion, it's always a tradeoff when designing Bigtable row keys. By using bucketing, you always avoid hotspotting but the way you query the data is more complex. But, based on your requirements (many writes), this is what I'll do.
You can change the number of buckets depending on your number of nodes in your Bigtable cluster also. If you have more than 8 nodes, I recommend you to create more buckets. Ideally, 1 bucket = 1 node but a node can easily contain multiple buckets.
I suggest though to test this key design with others and benchmark them in real conditions (PoC). You could use the Bigtable Key Visualizer to check the distribution of your keys across your cluster.


text:
Q: How to reset netscape.security.PrivilegeManager.enablePrivilege? At same point, I believe I've clicked the "Deny" button when the message box appeared in FireFox asking me if I wanted to allow a site a privilege using the
netscape.security.PrivilegeManager.enablePrivilege()

method. Now, I cannot find how to reset this so that the message box will start appearing again at this specific site. I've checked Tools -> Options and about:config, but nothing. Does anyone know how to reset this? Or is there any other reason that the message box simply will not show and automatically throw an exception?

A: Firefox saves the allow/deny permissions for websites using PrivilegeManager in the prefs.js file in your profile directory. A permanent DENY setting for the sample page (jar:http://www.mozilla.org/projects/security/components/signed-script-demo.jar!/signed-script-demo.html) added these user preferences:
user_pref("capability.principal.certificate.p0.denied", "UniversalPreferencesRead");
user_pref("capability.principal.certificate.p0.id", "C3:B3:11:2F:F2:CB:3B:86:A3:66:11:DD:C2:42:0F:7F:98:C8:21:02");
user_pref("capability.principal.certificate.p0.subjectName", "CN=Netscape Communications Corp.,OU=For internal testing only,O=Netscape Communications Corp.,L=Mountain View,ST=California,C=US");

You'll have to find the ones for the website that you accidentally denied, and delete the three settings for that site.  Exit Firefox before you change them, or it will get overwritten.

A: Go to Tools -> Clear Recent History -> press the details button, check Site Preferences/Settings(I dont know how it is in english, but you will find the right checkbox easy) and then click Erase Now(or Ok, whatever).


text:
Q: Slider compatible issue with IE7 and IE8 I bought a bootstrap template appster online. The slider is not compatible with my IE7 and IE8 as show in the following image:

Does anybody know how to fix this problem? Thanks in advance!

A: Here is the solution.
add this css :
.right-side img{background-color: none !important;}


text:
Q: Spring Data 'Left Join Fetch' query returning null My query looks like this:
@Query("SELECT p FROM Pilot p LEFT JOIN FETCH p.playerShips WHERE p.nickname = (:nickname)")

So far so good. I'm getting Pilot instance even when playerShips is empty.
Now, I want to fetch only inactive ships so I modified my query to look like this:
@Query("SELECT p FROM Pilot p LEFT JOIN FETCH p.playerShips s WHERE p.nickname = (:nickname) AND s.active = false")

and I'm getting null as a pilot so it clearly doesn't work. I'd be glad if someone could explain me how to create a JOIN FETCH query with WHERE clause that applies to the child elements. Thanks in advance.

A: Just move it to the join condition:
@Query("SELECT p FROM Pilot p LEFT JOIN FETCH p.playerShips s ON s.active = false WHERE p.nickname = (:nickname)")

The ON clause is defined in the JPA 2.1

A: After a lot of research, I decided to implement a custom repository so that I can use Hibernate Filters and now it works.
PilotRepository:
@Repository
public interface PilotRepository extends JpaRepository<Pilot, Long>, PilotRepositoryCustom{
/*spring data methods here*/
}

PilotRepositoryCustom:
public interface PilotRepositoryCustom {
    public Pilot findByNicknameFetchInactiveShips(String nickname);
}

PilotRepositoryImpl:
public class PilotRepositoryImpl implements PilotRepositoryCustom{

    @PersistenceContext
    EntityManager entityManager;

    @Override
    public Pilot findByNicknameFetchInactiveShips(String nickname) {
        Session session = entityManager.unwrap(Session.class);
        session.enableFilter("active").setParameter("active", false);
        Query query = entityManager.createQuery(
                "SELECT p FROM Pilot p " +
                "LEFT JOIN FETCH p.playerShips ps " +
                "LEFT JOIN FETCH ps.ship s " +
                "WHERE p.nickname = (:nickname)");
        query.setParameter("nickname", nickname);
        return (Pilot)query.getSingleResult();
    }
}

That's it about spring data. Now the Filters configuration:
Pilot Entity:
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pilot")
    @Filter(name="active", condition = "active = :active")
    private List<PlayerShip> playerShips;

PlayerShip Entity:
@Entity
@Table(name="player_ship")
@FilterDef(name="active", parameters=@ParamDef(name="active",type="java.lang.Boolean"))
public class PlayerShip {
    /*...*/
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "pilot_id")
    private Pilot pilot;
    /*...*/
}

IMPORTANT :
If you use Boolean in @ParamDef, make sure to type java.lang.Boolean instead of just Boolean. I've spent more than one hour wondering why I keep getting parameter not found/not defined error.


text:
Q: (Dis)prove: $\left\lceil\frac{\left\lceil\frac{x}2\right\rceil}2\right\rceil=\left\lceil\frac{x}4\right\rceil\ \forall x\in\Bbb R$ I don't how to prove if $\frac{x}2\in\Bbb Z$.
Let  $\frac{x}2=n\in\Bbb Z$.
$\begin{aligned}\left\lceil\frac{\left\lceil\frac{x}2\right\rceil}2\right\rceil&=\left\lceil\frac{x}4\right\rceil\\\left\lceil\frac{n}2\right\rceil&=\left\lceil\frac{x}2\cdot\frac12\right\rceil\\\left\lceil\frac{n}2\right\rceil&=\left\lceil\frac{n}2\right\rceil\end{aligned}$
Let $\frac{x}2, b\in\Bbb R,\ 0<b<1,\ a\in\Bbb Z$.
$m=a+b$
case 1:  $0<b<0.5$
$0<b/2<0.25$
$\left\lceil\frac{\lceil a+b\rceil}2\right\rceil=\left\lceil\frac{a+b}2\right\rceil$
What should $\frac{a}2$ be?

A: Write $x=4m-a$ with $m\in\Bbb Z$ and $a\in[0,4)$.
Then $$\left\lceil\frac x4\right\rceil =\left\lceil m-\frac a4\right\rceil =m,$$
$$\left\lceil\frac x2\right\rceil =\left\lceil 2m-\frac a2\right\rceil =\begin{cases}2m&0\le a<2\\2m-1&2\le a<4\,\end{cases}$$
and so
$$ \left\lceil\frac{ \left\lceil\frac x2\right\rceil}2\right\rceil=\left\lceil m\quad\textit{or}\quad m-\frac12\right\rceil=m$$


text:
Q: Select Month in Oracle Query I tried the below query in oracle
select cast(TO_DATE (cal.MONTH,'MM') AS varchar2(30)) as result
FROM  JOBCONTROL_USER.ods_calendar_weeks cal
WHERE cal.YEAR NOT IN (0, 9999)

it gives result in dd-mon-yy format. Now I want only mon from the result, how can I achieve this without using to_char()?

A: If you're avoiding Oracle functions and the month number is stored on its own as a varchar2 field, then you could brute-force it:
select case cast(month as number)
    when 1 then 'Jan'
    when 2 then 'Feb'
    when 3 then 'Mar'
    when 4 then 'Apr'
    when 5 then 'May'
    when 6 then 'Jun'
    when 7 then 'Jul'
    when 8 then 'Aug'
    when 9 then 'Sep'
    when 10 then 'Oct'
    when 11 then 'Nov'
    when 12 then 'Dec'
  end as mon
from ods_calendar_weeks cal
where cal.year not in (0, 9999);

But you're having to specify the language; you don't get Oracle's conversion of the month to the NLS date language. Which might be a bonus or a problem depending on your context.
I'd be tempted to put the conversions into a look-up table instead and join to that; or to add the month name as a separate column on the table, as a virtual column in 11g.

A: select to_char(cal.Month,'month')
              ) AS result
FROM  JOBCONTROL_USER.ods_calendar_weeks cal
WHERE cal.YEAR NOT IN (0, 9999);

This will gives month. the to_char() is a function which has two arguments 1. Column name ans 2. Month. Column name is of date data type so we have to convert the date into character data type and we required only the month so the second column will describes what will be extracted from the date. Finally the result is displayed as a character datatype. This query will returns the months name if year neither 0 nor 9999.

A: You can try somthing like this:-
SELECT EXTRACT(MONTH FROM CAST(TO_DATE (cal.MONTH,'MM') AS varchar2(30))) as RESULT
FROM  JOBCONTROL_USER.ods_calendar_weeks cal
WHERE cal.YEAR NOT IN (0, 9999)

Hope this will help you.


text:
Q: how to close a softinputkeyboard I have created a customauto EditText field. My problem with the text field is that when i click on the EditText the keyboard rises but when i click elsewhere the keyboard still remains open. Please help me in this issue
The name of the custom auto EditText is auto_list. I have attached the onFocusChangeListener
auto_list.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if (hasFocus) {
                    getActivity()
                            .getWindow()
                            .setSoftInputMode(
                                    WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                }
                else{
                    InputMethodManager im = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        });

A: Try below code
public static void hideKeyboard(Activity activity) {
     InputMethodManager inputManager = (InputMethodManager) activity
       .getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputManager != null && activity.getCurrentFocus() != null) {
      inputManager.hideSoftInputFromWindow(activity.getCurrentFocus()
     .getWindowToken(), 0);
    }
}

A: You are only checking hasFocus, this seems to be causing you problem. you should check something like this
    if(v.getId() == R.id.your_edit_text && hasFocus)

A: try this :
try
    {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
     }
    catch (Exception e)
    {
        // Ignore exceptions if any
            Log.e("KeyBoardUtil", e.toString(), e);
    }

A: Do this in event on which you want to hide soft keyboard...
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(xxx.getWindowToken(), 0);

where xxx is the edit text in which you want to hide keyboard. do same if you have more than one edit texts on which you want to apply same functionality.


text:
Q: Group string values I have this code
var myBuilder = new StringBuilder();

foreach (var item in myList)
{
  myBuilder.Append(item.Number).Append(" - ").Append(item.SecondNumber).Append(", ");
}

var text = myBuilder;

and using that I'm getting this text

AAA08 - BB08, AAA09 - BB09, AAA09 - BB10,

myList returns this:

{ Number = "AAA08", SecondNumber = "BB08" }
{ Number = "AAA09", SecondNumber = "BB09" }
{ Number = "AAA09", SecondNumber = "BB10" }

How can I concatenate it to string to display this:

AAA08 - BB08; AAA09 - BB09, BB10

I can do replace , to ; but can't get how to group these Numberto display only one and each SecondNumber right to him

A: You can do this with Linq and string.Join
var grouped = myList
    .GroupBy(x => x.Number)
    .Select(g => g.Key + " - " + string.Join(", ", g.Select(x => x.SecondNumber)))
var text = string.Join("; ", grouped);

A: You can use GroupBy and String.Join:
var groupedNumbers= myList
    .GroupBy(x => x.Number)
    .Select(g => $"{g.Key} - {String.Join(", ", g.Select(x => x.SecondNumber))}");
string result = String.Join("; ", groupedNumbers);

I'm using string interpolation which is a C#6 feature, if you aren't using it replace $"{g.Key}..." with  String.Format("{0}...", g.Key, ..).

A: When you get Number, iterate through myList to find all instances of Number, then get each corresponding SecondNumber and append it to your string.

A: Before building final string you probably would need to group your array first with this code:
var groupedList = myList.GroupBy(x => x.Number)
and later use that grouped list to get proper string:
foreach (var item in groupedList)
{
    myBuilder.Append(item.Number).Append(" - ").Append(item.Select(x => x.SecondNumber).Join(", ")).Append("; ");
}


text:
Q: Datatable.js make table from object Suppose I have a set of objects that each contain data I want to store into a data table.  Per the documentation, I would normally do something like:
var dataSet = [
    ['Trident', 'Internet Explorer 4.0', 'Win 95+', '4', 'X'],
    ['Trident', 'Internet Explorer 5.0', 'Win 95+', '5', 'C'],
    ['Trident', 'Internet Explorer 5.5', 'Win 95+', '5.5', 'A'],
    ['Gecko', 'Camino 1.0', 'OSX.2+', '1.8', 'A'],
    ['Gecko', 'Camino 1.5', 'OSX.3+', '1.8', 'A'],
    ['Gecko', 'Netscape 7.2', 'Win 95+ / Mac OS 8.6-9.2', '1.7', 'A'],
    ['Gecko', 'Netscape Browser 8', 'Win 98SE+', '1.7', 'A'],
    ['Gecko', 'Netscape Navigator 9', 'Win 98+ / OSX.2+', '1.8', 'A'],
    ['Misc', 'PSP browser', 'PSP', '-', 'C'],
    ['Other browsers', 'All others', '-', '-', 'U']
];

But my data is presented as an array of objects. Can I iterate through them in a for loop and get each piece of data? For example, if I have  an object, obj, that contains a title and a some data, the following does not work:
var finalObj = "["
for (var i = 0; i < obj.length; i++) {
    finalObj = finalObj + "['" + obj[i].title + "','" + obj[i].data + "']";
}
finalobj = finalObj + "]";

This results in my datatable only containing one letter per column. What is the proper way to create a string (or other object) that will be formatted like the example above?

A: This is achieved using the data option in the initialization object, passing in an array of data to be used (like all other DataTables handled data, this can be arrays or objects using the columns.data option)
See the example below for code and demonstration.

$(document).ready( function () {

  var obj = [
        {
            "title": "Tiger Nixon",
            "data": "System Architect"
        },
        {
            "title": "Garrett Winters",
            "data": "Accountant"
        },
        {
            "title": "Ashton Cox",
            "data": "Junior Technical Author"
        }
  ];

  $('#example').DataTable({
    "data": obj,
    "columns": [
       { "data": "title" },
       { "data": "data" }
    ]
  });

});
<!DOCTYPE html>

    <link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>

            Title
            Data

            Title
            Data

A: I think you need the example about the javascript sourced data
As you can see for yourself it uses the following code to create the table
 $('#example').dataTable( {
        "data": dataSet,
        "columns": [
            { "title": "Engine" },
            { "title": "Browser" },
            { "title": "Platform" },
            { "title": "Version", "class": "center" },
            { "title": "Grade", "class": "center" }
        ]
    } );


text:
Q: How to iterate elements list and map in Terraform I want to create a folder structure in S3 with Terraform so that it defaults to all environments. The idea is to have structures similar to these:
locals {
  folder = [
  {
    provider = "provider-1",
    process = "batch-process",
    final = ["people","cart"]
  },
  {
    provider = "provider-1",
    process = "online-process",
    final = ["log","order"]
  }]}

Bucket-1

*

*provider-1

*

*batch-process

*

*people

*cart

*online-process

*

*log

*order

I managed to create a list with all the S3 directories I would like to have, but I know this is not the most efficient way.
I tried to follow some examples found here but they returned an error. What is the correct way to do this iteration without having to write the entire directory?


text:
Q: Caching with redux-toolkit's createApi I am caching product data coming from /products/name API using the Products tag and I want to re-fetch only when the product list has been updated.
But I am concerned that I could still get cached data if someone else (another user) has updated the products and I didn't call /add-product API.
Then what's the use case of caching data using tags in using createApi?
    ...
    endpoints: (builder) => ({
      getProducts: builder.query({
        query: () => `/products`,
        provideTags: 'Products',
      }),
      addProduct: builder.mutation({
        query: ({ product }) => ({
          url: `/add-product`,
          method: 'put',
          body: product,
        }),
        invalidateTags: 'Products'
    }),
    ...

A: RTK Query's main purpose is to help keep data on the client in sync with what's on the server.
As part of that, the philosophy of RTK is that it's best to re-fetch data from the server any time something may have changed, so that the client always has the most current data.
"Tags" are used to manage relationships between mutations and queries.  When you run a mutation, you're telling the server "go update this data".  That means the data on the server is now newer than what's on the client, so we should re-fetch the related data and keep the client up to date.  By attaching the same tag from a query's providesTags into a mutation in invalidatesTags, RTKQ knows that any time the mutation runs it should re-fetch the related queries.
If you think there's cases when someone else other than this user may have updated the data on the server, you can also configure RTKQ to automatically poll and re-fetch the data on a timer.
More details:

*

*https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#cache-data-subscription-lifetimes

*https://redux-toolkit.js.org/rtk-query/usage/automated-refetching

*https://redux-toolkit.js.org/rtk-query/usage/polling


text:
Q: Provision to allocate multiple Roles to single User Just want to know, is there any work around to allocate multiple Roles to a user. The user with multiple roles should able to handle all assigned role's responsibilities.

A: There is no functionality to allow assignments of multiple Roles in the way that a Permission Set allows extension of the Profile's system permissions.
To allow access to records in other parts of a Role Hierarchy you can use Sharing Rules or Apex sharing based on either the user's current Role or another part of their profile.
Another option is to use Public Groups for the users to allow access to records without being part of the same Role hierarchy.


text:
Q: Eclipse tree bullets are invisible
I would like to know if there is any way to change the color of the bulleted item in tree view in Eclipse while using a dark theme, they are almost invisible.
Try to use eclipse dark background, DevStyle dark theme, eclipse preferences, DPI settings, changing my Windows theme, and it seems like nothing can change the color of these bullets.


text:
Q: Should I always use the perfect present, when the sentence uses "never"? In my English classes, I was taught that never should not be used with past forms, only with present perfect forms; this is also what I read in a grammar book I bought some years ago. (I bought the book in the USA; I guess the book is about American English grammar, but I don't have any reason to believe there is any difference between American, and British English in this case.)
Is it correct to use never with the past tense?

I never said that.

I have never said that.

A: This is the sort of 'rule' that teachers employ during early studies to prevent beginning students from making certain likely errors. In this case what the rule is fighting is things like:

*

*I never visited Italy, when what the student means is that she has not yet visited Italy

*I never saw Citizen Kane, when what the student means is that she is unfamiliar with the movie

This is the sort of proposition a beginning student is likely to encounter or use. But once the student masters the notion that past events (or non-events) with effects in the present are discussed in the present perfect form, the rule can be qualified: when you are speaking only of the past effects, the past form is appropriate:

*

*I lived in Europe in the 90s, but the entire time I never visited Italy.

*I never saw Citizen Kane until our school's Welles Festival last year.

*I never said I would give you my car. I said I would lend you my car.

ADDED:
To distinguish between use of the present perfect and use of the past:

I have never said I like hats means "Right up to the present moment I have avoided saying I like hats"; it suggests that you continue to avoid saying you like hats.
I never said I like hats means only that "During some [past] period [defined by the context] I avoided saying I liked hats"; it does not say anything about whether at some subsequent time you did say you liked hats, or whether you now deny or assert a liking for hats. It is silent on the topic.

A: Never implies a time period, then if your statement can expand to now (or future) you may use present perfect

I have never visited Italy
I have never liked to play football

But if your statement was true in a period in the past you may use a past tense

I never liked to play football until I watched a match between Brazil and Germany.


text:
Q: Compiling the file with a main function to a specific file name instead of "a.out" I have multiple files that main.cpp depends on. My main.cpp file contains int main() {...} in it. Currently, my command to compile main.cpp looks like so:
g++ main.cpp src_file1.cpp src_file1.cpp header.h ...
This generates a.out. I do not want this file to be named a.out. I want to control the main executable's file name. I tried using this command to do so:
g++ main.cpp src_file1.cpp src_file1.cpp header.h ... -o main.out
However, when I run this, I get the error:
error: cannot specify -o when generating multiple output files
I understand why this is happening, but I do not know how to fix it. Of course I still want g++ to compile my headers and other c++ files, but I would like the main file, main.cpp to be compiled as main.out instead of a.out. How can I do this?
Relevant makefile code (if you want):
SRC = block.cpp list.cpp blocker.cpp hasher.cpp header.h
CFLAGS = -g -Wall
CC = g++
STD = -std=c++11
ARGON = argon2/libargon2.a
TARGET = main.out

main: main.cpp $(SRC) argon2/argon2.h
  $(CC) main.cpp $(SRC) $(ARGON) $(CFLAGS) $(STD) $(TARGET)

A: Don't pass header files to the compiler as if they were source files. Try this:
SRC = block.cpp list.cpp blocker.cpp hasher.cpp
ARGON = argon2/libargon2.a
TARGET = main.out

main: main.cpp $(SRC) argon2/argon2.h header.h
    $(CC) main.cpp $(SRC) $(ARGON) $(CFLAGS) $(STD) -o $(TARGET)


text:
Q: Reducing services to commands Could spring services be reduced to commands (according to the Command design pattern)? I see this as a more flexible approach, and certainly one which increases the cross-cutting of concerns, than putting all functionality into one service class.
Good? Bad? I know that this will undoubtedly increase the number of classes the app will be dealing with, but I don't mind.

A: You're still making a distinction where none needs to be made. Anything can be injected--you can call the entity whatever you want. A controller, a service, a command could all be injected with entities that implement a known interface, like a command interface implementing a run method, or whatever.
There are a myriad ways to do this in Spring. You could layer AOP advice. You could inject lists of "commands". Intercept calls and/or web requests, composite collections of services, ...
Until you provide an example of what you are actually trying to do, it'll be tough to provide anything beyond generalities. Web searches turn up resources like this, which is just one way of doing it.


text:
Q: Python pandas column get rows with highest five numbers I have a dataframe 'df1' with three columns: 'Name', 'Age', and 'Number' and more than hundreds of rows. I would like to create two new dataframes: 'df2' presenting 'Name' rows with the highest five 'Age' values and 'df3' presenting 'Name' rows with the highest five 'Number' values. I'm thinking doing some .sort() or .max() function but I'm not very sure. Can anyone help me with this please? Thanks in advance!

A: You can use the pandas nlargest function like follows:
df2 = df.nlargest(5, 'Age')
df3 = df.nlargest(5, 'Number')

Just make sure the columns are numeric type.


text:
Q: JS For loop with conditionals I've got a function with a For loop that will count from 0 to the value of n, but, will include a string instead of an integer when it reaches numbers that are either multiples of 5 or 7. The problem is it only shows 1 output and I want it to list the append the outputs on each iteration. ( 1 , 2 , 3 , 4 , etc.).
HTML:
<button onclick="callit()">Call OneTwo</button>

Test

JS:
            function callit() {
                x = 0;
                n = 100;
                z = "The number is " + x + "
";
                one = "One";
                two = "Two";
                ot = one + " " + two;
                obj = document.getElementById('OneTwo');

                for (x; x <= n; x++) {
                    if ((x % 5) === 0) {
                        z = one;
                    }
                    if ((x % 7) === 0) {
                        z = two;
                    }
                    if (((x % 3) === 0) && ((x % 5) === 0)) {
                        z = ot;
                    }
                    obj.innerHTML = z;
                }
            }

A: Here you go, this should do what you are looking for:
obj.innerHTML = obj.innerHTML + "
" + z;

You need to maintain the value of innerHTML instead of replacing it.

A: Well you are replacing whole html of div with current value. You need to append it. Try following:
obj.innerHTML = obj.innerHTML + '
' + z;

jsfiddle

A: You need to get the previous value and append with the new one. You had just append on existing one, which makes the problem.
<!DOCTYPE html>

<button onclick="callit()">Call OneTwo</button>

Test


text:
Q: Charset of http response in Java Using a standard Java HTTP Client, I load a page at this address:
https://www.youtube.com/watch?v=ELArlE7gSmw
Title of this youtube video in Bulgarian. It is listed in the meta tags of the page like this:
<meta name="title" content="here is title">

I am using the following code to load this page. Pay attention to the encoding (Windows-1251):
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;

public class Application {
    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI("https://www.youtube.com/watch?v=ELArlE7gSmw"))
                .GET()
                .build();
        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString(Charset.forName("Windows-1251")));
        System.out.println(response.body());
    }
}

If you look at this tag in the response (with Windows-1251 encoding), then it will look like this:
<meta name="title" content="ЗАХАРОСАН�? ЧЕРВЕН�? ЯБЪЛК�?!!">

If you use UTF-8 instead of Windows-1251, it will be like this:
<meta name="title" content="���������� ������� ������!!">

I have also tried other http clients, such as the client in jsoup library. The result is similar, although the demo version of this library displays all tags with Bulgarian content correctly:

How to decode http response without errors?

A: There are multiple items that can (and do not have to) define the response format:

*

*When the client sends a request, there is a header called Accept-Encoding.
This should be a hint for the server what the client wants to have.

*When the server sends the response, the server should mark up the encoding used in the header Content-Encoding.

*The response body may contain meta tags as you mention. The disadvantage here is that the client already needs to assume some encoding to access this data so it is less reliable.

*Still then, it seems you apply the BodyHandler for Windows-1251 regardless of what the really used encoding is.

With that your setup looks quite fragile, and you better check if the headers Accept-Encoding and Content-Encoding are present and meaningful.
Edit: When testing the code from the question I was able to reproduce the reported problems. But they vanished when I simply leveraged the default behaviour of the client like so:
public static void main(String[] args) throws Exception {
    HttpRequest request = HttpRequest.newBuilder()
            .uri(new URI("https://www.youtube.com/watch?v=ELArlE7gSmw"))
            .GET()
            .build();
    HttpClient client = HttpClient.newHttpClient();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.body());
}

A: Solved the problem.
For Intellij IDEA:
File > Settings > Editor > File Encodings.
Set fields "Global Encoding" and "Project Encoding" to "System Default" (not UTF-8 or Windows-1251, but default!). The whole output is fixed


text:
Q: Does $ \lim_{n \to 0} \frac{f(n)-f(-n)}{n} $ exist for smooth functions? Suppose $f:\mathbb{R} \to \mathbb{R}$ is a (sufficiently) smooth function. I want to know if
$$
\lim_{n \to 0} \frac{f(n)-f(-n)}{n}
$$
always exists and is computable. I was think that one could use the definition of a derivative somehow or perhaps the mean value theorem? If the answer is no, what other assumptions do we need? Boundedness for instance?


text:
Q: How do you create acceptance tests for webgl applications? I don't think selenium/webdriver is going to work out here (for obvious reasons). Are there any techniques for acceptance testing webgl (even opengl) style applications beyond unit testing?
This application functions more like photoshop and less like a game.

A: Why won't selenium work? We used it on O3D to test graphics. You can take screenshots from selenium and use perceptual diff. There are something things to be aware of. You probably want to test with anti-aliasing off because how each GPU anti-aliases is different. Similarly interpolation is GPU dependent so you need to test solid colors, simple textures, turn off filtering if you can for your tests. Or else check individual pixels in known "safe" areas meaning areas where you know it should render the same regardless of GPU.
You can also take a look at the WebGL Conformance Tests. They run in the browser both Chrome, Firefox, and Safari all have them running in their builds as just another example of testing WebGL.
Also see how to run Chrome using osmesa (for running tests on machines without GPUs). Note it will be sssssllllloooowwww so need to design your tests well.


text:
Q: How to include scope variables options array with values in angulajs? I am very new to AngularJS.
I have query on how to to have a drop down that have scope variable options which contains Low Price to High and High Price to Low values in it.
Also sort the product list based on the price (higher to lower / lower to higher).

A: I created demo for you with what you are looking.
Demo
You can see that angularJs give you option OrderBy: 'key' you can choose how to tell angular sorted current repeat.
For now its sort by higher to lower but if you want the oposite you can remove  the true from the orderBy filter


text:
Q: How can I take log of particular columns? I have this data
structure(list(DATE = 19620101:19620106, PRECIP = c(10.54, 6.39,
0.01, 0, 0.02, 20.94), OBS_Q = c(2.39, 2.38, 2.22, 2.24, 2.26,
5.13), swb = c(4.11, 3.92, 3.8, 3.8, 3.77, 7.16), gr4j = c(3.7,
4.24, 3.73, 3.24, 2.98, 4.93), isba = c(4.82, 3.44, 4.18, 3.01,
2.88, 6.35), noah = c(3.11, 2.84, 2.57, 2.59, 2.84, 4.83), sac = c(2.83,
2.84, 2.73, 2.87, 2.94, 6), swap = c(2.16, 2.56, 2.08, 2.19,
3.65, 4.43), vic.mm.day. = c(3.44, 3.14, 3.37, 3.15, 2.88, 4.52
)), .Names = c("DATE", "PRECIP", "OBS_Q", "swb", "gr4j", "isba",
"noah", "sac", "swap", "vic.mm.day."), row.names = c(NA, 6L), class = "data.frame")

And a function that does three things

*

*Subsets based on what 'model' is mentioned(one of the column names of df)

*Outputs dfcal with 3 columns

*Outputs dfcallog with the log of those values

The function
dataprep.allcal<-function(df,model){
      dfcal<<-subset(df, select=c("DATE",model, "OBS_Q"))
      dfcallog<-subset(df, select=c("DATE",model, "OBS_Q"))
      cols<-colnames(dfcallog)
      dfcallog[cols] <<- log(dfcallog[cols])
    }

dataprep.allcal(df=df,model='sac')

The problem with this, it converts the date to log as well.
Can you tell me how I can apply the log only on model and OBS_Q column?

A: This is a way to do it by excluding DATE from the cols variable:
dataprep.allcal<-function(df,model){
  dfcal<<-subset(df, select=c("DATE",model, "OBS_Q"))
  #need to use the <<- operator below
  dfcallog<<-subset(df, select=c("DATE",model, "OBS_Q"))
  cols<-colnames(dfcallog)
  cols<-cols[!cols %in% 'DATE']
  dfcallog[cols] <<- log(dfcallog[cols])
}

dataprep.allcal(df=df,model='sac')

Output:
> dfcal
      DATE  sac OBS_Q
1 19620101 2.83  2.39
2 19620102 2.84  2.38
3 19620103 2.73  2.22
4 19620104 2.87  2.24
5 19620105 2.94  2.26
6 19620106 6.00  5.13

> dfcallog
      DATE      sac     OBS_Q
1 19620101 1.040277 0.8712934
2 19620102 1.043804 0.8671005
3 19620103 1.004302 0.7975072
4 19620104 1.054312 0.8064759
5 19620105 1.078410 0.8153648
6 19620106 1.791759 1.6351057

Note:
I don't know if this is a typo but you should have dfcallog<-subset(df, select=c("DATE",model, "OBS_Q")) with a <<- operator because using a <- operator at the beginning and then a <<- operator at the last command in the function will produce an error because <<- looks at the parent.environment to find a variable and thus you would get an object not found error.


text:
Q: Identifying candidate distributions with a desired set of qualitative characteristics Is there a good way of finding candidate distributions based on a set of qualitative characteristics?  For instance, at the moment I am looking for a continuous univariate two-parameter distribution, bounded by zero on the left (i.e. with a scale and a shape parameter), with a single internal mode, for which the second moment fails to exist due to a fat tail for some but not all values of the parameters. (This is intended as a model of trading volume for certain securities).)
I could go through Johnson, Kotz and Balakrishnan in all of its 1500+ page glory, but it seems like there should be a less tedious way of finding a distribution with specified characteristics.
Identifying candidate distributions with a desired set of qualitative characteristics

A: There's no general way to identify distributions that satisfy some arbitrary list of characteristics. If you restrict the possible characteristics to a small set then you could perhaps set up a database of commonly used distributions for which those characteristics are known, but outside something like that, no.
As for your specific request, perhaps the scale-location family of the Fréchet with the location parameter set to 0. That is, with density
$$f(x) = {\frac  {\alpha }{\sigma}}\;\left({\frac  {x}{\sigma}}\right)^{{-1-\alpha }}\;e^{{-({\frac  {x}{\sigma}})^{{-\alpha }}}}\, x>0,\,\alpha>0,\,\sigma>0$$
The variance is finite for $\alpha>2$. The mode is $\sigma\left({\frac  {\alpha }{\alpha +1}}\right)^{{\frac  {1}{\alpha }}}$


text:
Q: Find multiple partial strings in each row and create a variable with the column the string is in I have found similar questions but nothing that has solved my problem yet.
I have a huge dataframe and I'm trying to find where there are occurrences of a range of strings.
Here is my sample data:
var1 <- c("Goats","Sheep","Pigs","Dog","Zebu","Donkeys","Water buffaloes","Dromedary camel","Dog","Pig")
var2 <- c("cats","Dog","birds","rabbits","Plant","fish","guinea pigs","cat","Mouse","dog")
var3 <- c("cats","Dog","birds","rabbits","horses","Sheep","Pigs","Tree","Zebu","Donkeys")
var4 <- c("Plant","Ant","Bee","Tree","Water buffaloes","Donkeys","Water buffaloes","Dromedary camel","Dog","Pig")

df <- data.frame(var1, var2, var3, var4)

head(df)
    var1    var2    var3            var4
1   Goats    cats    cats           Plant
2   Sheep     Dog     Dog             Ant
3    Pigs   birds   birds             Bee
4     Dog rabbits rabbits            Tree
5    Zebu   Plant  horses Water buffaloes
6 Donkeys    fish   Sheep         Donkeys
>

I can find the row and column of each occurrence of Tree and plant:
strings = c( "Tree","Plant")

which(apply(df, 1, function(x) any(grepl(paste(strings, collapse = "|"), x))))# ROW
[1] 1 4 5 8

which(apply(df, 2, function(x) any(grepl(paste(strings, collapse = "|"), x)))) # COLUMN
var2 var3 var4
   2    3    4

But can't figure out how to put the column name (or indice) in a new variable for each row. This is what I would like:
> head(df)
     var1    var2    var3            var4     x1
1   Goats    cats    cats           Plant     var4
2   Sheep     Dog     Dog             Ant     NA
3    Pigs   birds   birds             Bee     NA
4     Dog rabbits rabbits            Tree     var4
5    Zebu   Plant  horses Water buffaloes     var2
6 Donkeys    fish   Sheep         Donkeys     NA

I thought something with str_detect or str_which would would, but not sure how to do it across all columns.
Something like:
df <- df %>%
  mutate(words = ifelse(any_vars(str_detect(strings))))

Appreciate your time and help.

A: We can achieve this with rowwise -
library(dplyr)

cols <- names(df)

df %>%
  rowwise() %>%
  mutate(x1 = toString(cols[c_across() %in% strings])) %>%
  ungroup

#   var1            var2        var3    var4            x1
#   <chr>           <chr>       <chr>   <chr>           <chr>
# 1 Goats           cats        cats    Plant           "var4"
# 2 Sheep           Dog         Dog     Ant             ""
# 3 Pigs            birds       birds   Bee             ""
# 4 Dog             rabbits     rabbits Tree            "var4"
# 5 Zebu            Plant       horses  Water buffaloes "var2"
# 6 Donkeys         fish        Sheep   Donkeys         ""
# 7 Water buffaloes guinea pigs Pigs    Water buffaloes ""
# 8 Dromedary camel cat         Tree    Dromedary camel "var3"
# 9 Dog             Mouse       Zebu    Dog             ""
#10 Pig             dog         Donkeys Pig             ""

In base R, with apply -
df$x1 <- apply(df, 1, function(x) toString(cols[x %in% strings]))


text:
Q: OS X Terminal using default ANSI colours for every theme For some reason, every theme I palette I've had installed for the OS X Terminal.app has reverted to using the default ANSI colours. The themes have been working fine up until this point and I can't seem to determine what could have caused them to revert in this way. For reference, my standard Solarized Dark colour scheme should look like this …

… but it currently looks like this:

A quick look in the preferences panel shows that all the colours are correct save for the ANSI colours which have reverted to their defaults.
I don't know what other information would be helpful but if you need any other info to help me troubleshoot just ask and I'll update as quickly as I can.

A: Bizzarely enough, the problem seems to have resolved itself without any need for restarts or anything, so I'm closing this thread.


text:
Q: Как при помощи регулярных выражений найти строку, при этом чтобы она была без опознавательных слов(см. описание) Я хочу найти слово, которое идет после слова Vovin. Для этого я пишу "Vovin \w+". При исходном предложении "Vovin velosiped ykrali" я получу "Vovin velosiped". А я хочу получить лишь velosiped. Как это можно сделать, пользуясь лишь регулярными выражениями из библиотеки C#?

A: https://regex101.com/r/ybl9g3/1
Вам нужно разбить регекс на группы с помощью скобок (), а чтобы не возвращались результаты для ненужной группы, её лучше заигнорить с помощью ?:
(?:Vovin )(\w+)

A: Используйте позитивный просмотр назад:
(?<=Vovin )\w+

Пример: regex101.com


text:
Q: Hide  I have used  in my xhtml page to display command buttons. Now I want an implementation such that there is a commandButton which calls a javascript and if my condition matches then I'll call another command Button which is hidden. Is there any way I can make my second commandButton hidden.
My only issue is to make commandButton hidden.


text:
Q: Fatal error: Class 'Abraham\TwitterOAuth\TwitterOAuth' not found I am trying to tweet posts to my twitter account. I am download the required library files from https://github.com/abraham/twitteroauth
I am geting the error

Fatal error: Uncaught Error: Class 'Abraham\TwitterOAuth\TwitterOAuth'
  not found in
  D:\xamp\htdocs\Shasta_Tools\trunk\CEP\Twitter\SampleCode\connect\index.php:12
  Stack trace: #0 {main} thrown in
  D:\xamp\htdocs\Shasta_Tools\trunk\CEP\Twitter\SampleCode\connect\index.php
  on line 12

Folder structure:

Sample Code:
<?php
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

// Set keys
$consumerKey = 'MyConsumerKey';
$consumerSecret = 'MyConsumerSecret';
$accessToken = 'MyAccessToken';
$accessTokenSecret = 'MyAccessTokenSecret';

// Create object
$connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

// Post Update
$content = $connection->post('statuses/update', array('status' => 'Test Tweet'));
?>

I already refered
Fatal error: Class 'Abraham\TwitterOAuth\TwitterOAuth' not found in.. in the sub folder
Class not found PHP
How to resolve this issue.
Please advise!


text:
Q: How to use Drupal 8 logger within the .theme file I need to debug a preprocess function in a theme's .theme file. I don't have the project on my local computer, so I can't use dump-like functions on production.
I thought about using logs, but \Drupal::logger() requires a module name as its first parameter, and I'm not within a module, I'm at the .theme file.
How can I use this or a similar function?

A: Drupal::logger() does not require a module name as its first parameter, the general practice is to use the name of the module calling it, but you can use any string you want actually.
This string is used as a channel (or category or type) to which the message belongs, it principally aim easing the idendification of messages when looking through logs (ie. by filtering them by their category/type/channel).
Here on the Reports page of the admin UI, it is referred to as Type :


text:
Q: Agregar checkbox a celda DataTables Estoy actualizando una tabla DataTable, en una de las columnas necesito agregar un checkbox de acuerdo a uno de los valores que recibo, una vez dibujada la tabla en la columna recibo el valor [object Object], de esta forma actualizo la tabla:
function OnlyNotApproved(checkbox) {
    var table = $('#table_datable_CoorSf').DataTable();
    if (checkbox.checked)
    {
        $.ajax({
            method: "GET",
            url: "../AManager/GetOnlyNotApproval",
            contentType: "aplication/json; Charset=utf-8",
            async: true,
            success: function (records) {
                table.clear();//Limpia tabla
                records.forEach(e => {
                    table.rows.add([{
                        0: e.idscrap,
                        1: e.fecha.substring(0, 10),
                        2: e.parte,
                        3: e.numparte,
                        4: e.causa,
                        5: e.defecto,
                        6: e.descripcion,
                        7: e.causa,
                        8: e.cantidad,
                        9: new Test(e.idteam),
                        10: ''
                    }]);
                });
                table.draw();//Dibuja tabla
            }
        });
    }
}

Al llenar el valor de la columna 9 uso la función Test() que es como sigue:
function Test(idteam) {
    var item;
    if (idteam == 6) {
        item =  '<input class="form-check-input" type="checkbox">';
    }
    else { item = ''; }
    return item;
}

La intención es que solo en ciertos registros dibuje un checkbox, la documentación de DataTables menciona que si puede recibir una función para añadir un valor, pero no me funciona. Anexo una imagen como sigue:

A: efectivamente datatables tiene una funcion para renderizar contenido dentro de sus celdas (Aca la documentacion de render), lo que sucede en tu caso es que estas creando el datatable y luego netamente le envias datos para llenar sus filas, yo lo haria de la siguiente forma renderizando los checkbox al crear la tabla, Pero debes tener presente como le envias tus datos al DataTable, porque hay distintas formas de llenar un datatable pasandole la informacion como arreglo o como objeto, aca lo importante es la funcion (lo que responderia tu pregunta)render del datatable.
function OnlyNotApproved(checkbox) {
  let dataset = []
  if (checkbox.checked)
  {
    $.ajax({
        method: "GET",
        url: "../AManager/GetOnlyNotApproval",
        contentType: "aplication/json; Charset=utf-8",
        async: true,
        success: function (records) {
           $('#table_datable_CoorSf').DataTable({
              destroy: true,
              data: records,
              columns: [
                // {title: "parte", data: "Parte"} si pasas los datos como objeto
                {title: "N°"},
                {title: "Fecha"},
                {title: "Parte"},
                {title: "parte"},
                {title: "Analisis"},
                {title: "Defecto"},
                {title: "defecto"},
                {title: "causa"},
                {title: "cantidad"},
                {title: ""}//Nueva columna para dibujar checkbox
                {title: "icono de borrar"},
               ],
               columnDefs:[
               {
               targets:-2,
               render: function (data, type, row, meta) {
               //Aca depende mucho de como le pasas la data a la tabla, si como arreglo o como objeto.
               //supongamos que lo pasas con un arreglo bidimensional
               //indice de la fila
               let indiceFila = meta.row
               //record[indiceFila][8] a modo de ejemplo
               if (records[indiceFila][8])
                 item =  '<input class="form-check-input" type="checkbox">';

               else
                 item = '';
               return item;
               }//Fin de la funcion render
              }]
          });
        }
    });
  }
}

Lo que hace render es tomar la data que le envias, ya sea desde el arreglo original, o desde la informacion de la fila y ahi puedes gestionar lo que quieres renderizar, html en este caso

con target:-2 seleccionas la columna a renderizar, en este caso es -2 porque la tomo de derecha a izquierda, pero si fuese numeros positivos seria usar su indice por ejemplo target:0, primera columna, target:1 segunda y asi..
Te recomiendo que le hagas un console.log() a los atributos que le pasas a la funcion render.
Espero te sirva y aca te dejo documentacion sobre los datatables.
Esta respuesta tiene mas detalles tal vez te sirva
Documentacion render datatable
Documentacion colum defs


text:
Q: Find sufficient and necessary conditions on $a$ and $b$ such that the equation have solutions of the form $(x,y)=(0,y)$ Let us consider the following equation
$$ax+by=0$$
where $x$ and $y$ are the unknown variables and $a$ and $b$ are constants.
My question is: Find sufficient and necessary conditions on $a$ and $b$ such that the set of solutions of the system is precisely $\{\,(x,y)\mid x=0\,\}$.

A: Let $y=t$ then $x=-\frac{b}{a}t$ and hence the solution set is of the form $(x,y)=(-\frac{b}{a}t,t)$ so the condition is $b=0,a\ne 0$

A: Since $(x,y)=(0,1)$ must be in the solution set, one gets
If $a\times 0+b\times 1=0$ leading to $b=0$, and since $(x,y)=(1,0)$ must not be in the solution set one gets $a\times 1+b\times 0\neq0$ leading to $a\neq 0$;
these are therfore necessary conditions. Conversely, if $a\neq0$ and $b=0$ then you equation is $ax=0$ and after the allowed division by $a$ this gives $x=0$ as equivalent form, and the solution set is $\{\,(x,y)\mid x=0\,\}$ as required.
The necessary condition found above is therfore also sufficient; your answer is "$a\neq0$ and $b=0$".


text:
Q: Critique of complex analysis proof I'm working on the following complex analysis problem and am wondering if someone could critique my proof:

Suppose that $f$ is an analytic function on some domain $D$ and that
  there exists a degree two polynomial $p$ such that $p \circ f$ is
  real-valued. Show that $f \equiv C$ on $D$.

My solution: First we'll show that $f(z) \in \mathbb{R}$ for any $z \in D$ and then we'll deduce that $f$ must be constant.
Let $p(z) = a_0 + a_1z + a_2z^2$ and suppose that $f(z)$ is complex for some $z$. Observe that $(p \circ f)(z) = a_0 + a_1f(z) + a_2f^2(z)$. If $f(z)$ is complex, then $a_1f(z)$ is also complex, contradicting the problem statement. Thus, $f$ is real-valued.
Now we show that $f \equiv C$ on $D$. Write $f$ in the form $f(x,y) = u(x,y) + iv(x,y)$. Since $f$ is real-valued, $v_x = v_y = 0$. Thus, to satisfy the Cauchy-Riemann equations, we must have $u_x = u_v = 0$. Thus, $f \equiv C$ on $D$.


text:
Q: how to autoincrement different department in one table in textbox This is my code for autoincrementing but when i save it in database the number of autoincrement is starting to 1 again. I need something that is stable where in there are different incremeting in each department and also when the year change it starts from 1 again.
An example output should be :
10-ppmn-16-0001
10-fcrsm-16-0001

 Static cnt As Integer
        cnt = cnt + 1

prnotxt.Text = ""10""-"" & deptcmb.Text & "-" & Now.Date.ToString("yy") & "-" & Format(cnt, "0000") & ""

A: Irrespective of what you want to save, and whether your application is attached to any database or not, there is a facility in VB.NET to save values into permanent storage.

*

*Right click on your Project, and click on Properties. This will open the Project Properties.

*Goto Settings tab and add a setting with appropriate Name, Type, Scope and default value. For the sake of example, say our setting is Name=DeptCount, Type=Integer, Scope=User, Value=0

*Now you can easily save and get the saved value across application restarts. Sample code provided below:
'-- to save the value in settings.
My.Settings.DeptCount = 100
My.Settings.Save()

'-- to get back the saved value
Dim count As Integer = My.Settings.DeptCount


text:
Q: Call static method on null object I'm curious to know how would you explain this task I found in this quiz?
Even when the getFoo method returns null, the output is still Getting Object JavaQuiz . I think it should be NullPointerException.
   public class Foo {

        static String name = " JavaQuiz";

        static Foo getFoo() {
            System.out.print("Getting Object");
            return null;
        }

        public static void main(String[] args) {
            System.out.println(getFoo().name);
        }

   }

A: static members of a class are class level Members its means there is no need of Object to access these static Members.`
It automatically loaded when classloader of jvm loads the class. So here in this case
static String name = " JavaQuiz"; //load when class get loaded by JVM class loader.

This static variable will exists in memory just after class Foo is getting loaded into the jvm.
static Foo getFoo() {  //method is also a static Member automatically loaded at Class Loading.
            System.out.print("Getting Object");
            return null;
        }

And same will be applied with this static method getFoo().
So Here   System.out.println(getFoo().name);.
Here is a example to abbriviate my Answer
class StaticExample
{
    static String abc ="India";
    public static void main (String[] args) throws java.lang.Exception
    {
        StaticExample obj = null;
        System.out.println("Value is ==>" + obj.abc + StaticExample.abc + abc);
    }
}

Output:-
 Value is ==>IndiaIndiaIndia

here this line of code will also produce the output.
     System.out.println(((Ideone)null).abc); // this will also print India.

Output:-
 Value is ==>India

Note:- I think there  is confusion about getFoo() method but if .name makes a ambiguity. name is a  static member so it can access using either className or any null reference . So, Here you may assume this scenario such that this name variable is accessed with any null reference .

Hope you Got the point.

A: Accessing a static method or variable can be done via a null reference for the class that contains that static method/variable.
Since name is static, getFoo().name has the same result as Foo.name or just name, regardless of whether or not getFoo() returns null.
However, it is always better to use the class name when accessing a static method/variable, since it makes it clear that you intended to access a static member.

A: Disassembling (javap -c Foo) the byte code of Foo.java file reveals the under the hood information as to why you don't see a NullPointerException when the name is static.
With the above code, when disassembled it produces the following output.

If we look at the yellow box, we see that the compiler identifies that we are trying to access a static field and so it places the getstatic instruction to get the field name. So this effectively doesn't use the instance returned from getFoo method to get the value of name field and so no NPE is raised.

If we remove the static keyword before the String name = " JavaQuiz";, it results in below disassembled code.

Here we can see that java compiler instructs to use getfield instruction and this would invoked on the instance i.e., returned from getFoo method. So, this would raise a NPE if the getFoo method returns null.
So effectively, in this case, the java compiler does the magic during the compilation, i.e., if it the code is calling static field it places getstatic instruction that doesn't result in using the object reference.
We can find more information on instruction set here.


text:
Q: Can dragons use Unihorns to heal themselves? My character has a couple of dragons, each has a unihorn. I'm almost ready to polypile, and 2 more magic tools wouldn't hurt.  I have a bullwhip, so taking them shouldn't be a problem.  But, if the dragons actually use them, I'd prefer they keep them. So, can dragons use unihorns to heal themselves?

A: Any monster with hands that is in possession of a non-cursed unicorn horn (or one with an unknown BUC status) will use it to cure blindness, stunning, or confusion.  Your pet dragons don't have hands, so they won't use the unicorn horns.


text:
Q: Nested Query Nested Query This query
SELECT name
FROM sysobjects
WHERE id IN (SELECT id FROM syscolumns WHERE name LIKE 'TICKER')

produces the list of tables that contain a column called TICKER.
Now I want to see all the data from each table.
Select *
from (the result from the above query)

Example
Select * from POS
Select * from SEC
Select * from BROKER

Any ideas?

A: Set based\no cursors.
Final edit - a combo of both solutions
Declare @Sql NVarchar(Max) = N'';

Select @Sql += N'Select * From ' + QuoteName(Schema_Name(Schema_id)), '[') + N'.' + QuoteName(Tables.Name, '[') + N';'
From sys.tables
Join sys.Columns
On tables.object_id = Columns.object_id
Where columns.Name = 'Ticker';

Exec (@Sql);

A: You should use an INNER JOIN on the two tables, and you should also use the sys.objects and sys.columns system views instead of the deprecated sysobjects and syscolumns.  Also, if you don't have a wild-card, you should use equals instead of 'like'.
The result is something like this:
SELECT *
  FROM sys.objects o
       INNER JOIN sys.columns c ON o.object_id = c.object_id
 WHERE c.name = 'TICKER'

Okay, you changed the question on me while I was answering it... so with your new requirements (and this is horribly dangerous... think about what would happen if it returned a thousand tables with a given column name), you can use dynamic SQL like this:
DECLARE @sql varchar(MAX);
DECLARE @tableName sysname;
DECLARE theCursor CURSOR FAST_FORWARD FOR
    SELECT o.name AS TableName
      FROM sys.objects o
           INNER JOIN sys.columns c ON o.object_id = c.object_id
     WHERE c.name = 'TICKER';

OPEN theCursor;
FETCH NEXT FROM theCursor INTO @tableName;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = 'SELECT * FROM ' + QUOTENAME(@tableName);
    EXEC (@sql);
    FETCH NEXT FROM theCursor INTO @tableName;
END

CLOSE theCursor;
DEALLOCATE theCursor;

Or, if you want to avoid the cursor, do it like this, no temp tables required:
DECLARE @sql varchar(MAX);
SET @sql = '';
SELECT @sql += 'SELECT * FROM ' + QUOTENAME(o.name) + '; '
  FROM sys.objects o
       INNER JOIN sys.columns c ON o.object_id = c.object_id
 WHERE c.name = 'TICKER';
EXEC (@sql);


text:
Q: Probability of getting exactly 4 heads when a coin is tossed 6 times I understand that this problem may be elementary, but I'm unable to come up with anything other than this.

*

*$n(S)=2^6$
2)number of favorable events $\binom{6}{4}$
thus the probability of desired events is $$\frac{\binom{6}{4}}{2^6}$$
Which is $\frac{15}{64}$
which feels wrong
could someone help, please

A: When in doubt about an exercise, a reasonable mathematical approach is to simplify the exercise data if possible; here, let's look for the probability of getting exactly $2$ heads when a coin is tossed $a=3$ times.
Let's describe this random experience with the sample space $S=\{HHH,HHT,HTH,HTT,THH,THT,TTH,TTT\}$.
By the way, we make sure that $Card(S)=2^a=2^3=8$. The event $A':$"getting exactly $2$ heads" is $A'=\{HHT,HTH,THH\}$. We have$Card(A')=\mathrm{C}_{3}^{2}=\mathrm{C}_{3}^{1}=3$. Suppose that the outcomes in the sample space are equally likely to occur. Then $p(A')=\frac{\mathrm{C}_{3}^{2}}{2^3}=\frac{\mathrm{C}_{3}^{1}}{2^3}$.
So back to our original exercise, and based on what we have learned in our simple case, $p(A)=\frac{\mathrm{C}_{6}^{4}}{2^6}=\frac{\mathrm{C}_{6}^{2}}{2^6}=\frac{\frac{6\times5}{2!}}{2^6}$.


text:
Q: UNIX command which displays lines which contains specified string I have file which contains something like :
Hi how are you
how are you
you are genius
hi i'am fine
this is test session
I need UNIX command which displays lines which contains "are" word.

A: hmm, this is really the most basic use of grep.
grep -w "are" myfile.txt


text:
Q: Read file names in a local folder in an HTML page I am creating a HTML page where I need to display the names of the files present in the specific local folder, example - C:\Users\User1\Documents\folder1 . I tried to write the code in java script but have not succeeded yet. Most of the question threads mention about "ActiveXObject" to be used but that itself does not work for me.
Reference: JavaScript: Read files in folder
Can anyone help me in achieving this?

A: In general, you can't do that. Web pages do not have access to the local filesystem.
Chrome can access the contents of a directory that is selected using a file input field. However, other browsers, such as Internet Explorer and Firefox, have not implemented this feature at this time, nor is there currently any way to access a directory that was not selected by the user.
In theory, it is possible to read arbitrary files using a signed Java (not Javascript) applet. However, this requires the user to approve a series of extremely scary warning dialogs — and requires Java! — so it's really not a viable solution.

A: I'm afraid I may be the bearer of bad news for your design: The action you are requesting expressly violates the security model as specified in the File API spec. The client implementation of FileReader() must make sure that "all files that are being read by FileReader objects have first been selected by the user." (W3C File API , 13. Security Considerations: http://www.w3.org/TR/FileAPI/#security-discussion).
It would be a huge security risk of browser scripts could just arbitrarily open and read any file from a path without any user interaction. No browser manufacturer would allow unfettered access to the entire file system like that.
Thinking about it however, if it is all being run locally, you could use ajax to query a server side script that could return the directory you request.


text:
Q: Getting Status 504 using Rest Routing API Since today other people and me are getting 504 Response / Timeout while using the Rest Routing API.
Yesterday everything worked fine. When I try to call the API via Browser I also get 504 Gateway Timeout.
Other APIs are working as expected. It's only the Routing API which fails with 504.
Requests are sent from Germany.
The status page shows that everything is up and running, but the Routing API is unreachable.

A: It started to work again as it should 3 minutes ago..
So I think the problem was solved by here.com ..


text:
Q: How to mask password with MaterialTable I am using MaterialTable and want to mask a column values but I,m not able to do so.
Can you please help?
I am using MaterialTable to show users for an app.
import MaterialTable from "material-table";

function UserProfile() {
  const [state, setState] = React.useState({
    columns: [
      { title: "Logging Name", field: "name" },
      {
        title: "password",
        field: "password",
      }
],

data: [
      {
        name: "Dan",
        password: "TopseCrets@1"
}]

return (

      <MaterialTable
        title="User List"
        columns={state.columns}
        data={state.data}
.
.
.
);

I want to see ***** instead of password for the corresponding field, password string should be displayed only when I try to edit the row.

A: At this time, material-table doesn't have support for a custom password field.
I was able to salvage the solution on https://gitter.im/material-table/Lobby?at=5ebbf9c82cf0da0ad9fda27c (the chat lobby of material-table)
In short for your password column, you want to add additional properties (render, and editComponent):
        {
        title: 'Password', field: 'password',
        render: rowData =>
{rowData.password.split('').map(() => '*')}
,
        editComponent: props => (
            <TextField
                type="password"
                value={props.value}
                onChange={e => props.onChange(e.target.value)}
            />)
        },

render property will replace characters when displaying the field.
editComponent will use your own TextField component, with type "password" to hide the value when editing the row.


text:
Q: Flow: resolving modules in a monorepo that uses Yarn workspaces We have a monorepo that uses Yarn's 'workspaces' feature, meaning that whenever possible, Yarn will hoist dependencies to the monorepo's root node_modules directory rather than keep them in the individual package's node_modules dir. This relies on Node's module resolving algorithm, which continues to search for modules in node_modules directories up the dir tree until it finds the required module.
When using Flow types in a file that imports another package (internal or external to the monorepo), running Flow inside the package that contains that file causes a Cannot resolve <package-name> error to be thrown. It seems like Flow uses a different module resolving algorithm, and fails since the installed modules are hoisted to the root dir and Flow does not continue to search up the dir tree.
Is there a way around this other than running Flow from the root? Running from the root is less than optimal because it does not allow different settings for different packages in the monorepo.
Node version: 10.8.0
flow-bin version: 0.78.0

A: I also ran into this problem
To fix it need update .flowconfig:
[include]
../../node_modules/

FS struct:
/project_root
--/node_modules
--/packages
----/module1
------.flowconfig

A: Pick the components to be hoisted by hand with a directive like:
"nohoist": ["**/npm-package", "**/npm-package/**"]

or select them with an exclude glob:
"nohoist": [
  "**/!(my-site|my-cms|someones-components)"
 ]

See my answer to another question for more information.


text:
Q: HTML5 form validation before click event I have the following form and input button:
 <form class="form-horizontal" role="form" id="category_markups_form" data-toggle="validator">
    {{#each context.category_0}}

        {{category_name}}

            <input type="number" min="1.0" class="form-control" name="{{category_name}}" data-error="Please enter a number." required>

      {{/each}}
      <input id="to_subcategory_markups" type="submit" class="btn btn-success" value="Next: Subcategory Markups">
  </form>

My input button validates all of the inputs to make sure they are valid. My button also calls a script to show another form if it is clicked:
$("#to_subcategory_markups").click(function(e) {
    e.preventDefault();
    $("#subcategory_markups").show();
});

My problem is, as written, my other form will show if I click the input submit button WITHOUT validating all the inputs. The only way to make sure the form validates is by removing my input's id attribute. But this means my click event would not fire. Is there a way I can make my form validate before firing off the click event?
Thanks in advance!!

A: You should listen for the submit event on the form. Then the HTML5 validators will stop the submit if there are validation errors.
$(".form-horizontal").submit(function(e) {
    e.preventDefault();
    $("#subcategory_markups").show();
});

A: please use this syntax to validate your form
$("#f").validate({
            rules: {
                field01: {
                    required: true
                },
                field02:{
                    required: true,
                },
                field03: {
                    required: true
                },
                field04: {
                    required: true,
                },
                field05: {
                    required: true
                }
            },
            submitHandler: function(form) {
                 form.submit(); //  or your action
             }
  });

here is f is your form id and field0* will be the name of your input fields that you want to be required.


text:
Q: Jquery slideUp() slideDown() jump glitch, WordPress I'm using jquery (v2.2.4) slideUp() and slideDown() to show/hide a  tag. Inside  are 3 divs with different content: one shows recent posts, another recent comments, and the third shows a search field. There's an  tag for each button, which also checks if the sub content divs are active or not and to add or remove classes accordingly.
While the jquery works as far as revealing and hiding the , and adding and removing the classes, the slide animation only seems to work for about 5 pixels and then it "jumps" open. Since the content in the divs is dynamic, I can't set a specific height on anything.
I don't think this has anything to do with WordPress specifically, as I've used this in other templates without problem, though I didn't have multiple content areas showing and hiding inside a primary content area.
I'm not sure if this is related to the CSS or the jquery or both—guessing it's some CSS conflict. I checked other topics on here about slide glitches but couldn't see a relation to my problem as far as margin and padding. I thought it might be a float issue but I do have a clearfix on
 tags using pseudo elements and display:table for display issues with floated
.
Advice welcome.
HTML/PHP:

post

comment

search

recent posts

                <?php
                    $args = array(
                        'numberposts' => '5',
                        'post_type' => 'tips',
                        'offset' => '0',
                        'orderby' => 'post_date',
                        'order' => 'DESC',
                        'post_status' => 'publish'
                    );
                    $recent_posts = wp_get_recent_posts( $args );
                    foreach( $recent_posts as $recent ){
                        echo '

' . get_the_post_thumbnail($recent["ID"], 'tip-nav-thumb') . '

' . get_the_title($recent["ID"]) . '

' . get_the_time('l, F j, Y', $recent["ID"]) .'
' . '
';
                    }
                ?>

            close

recent comments

                <?php recent_comments(); ?>

            close

search for stuff

                <form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">

<input type="text" name="s" id="s" value="Find some crap" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
                    <input type="submit" id="searchsubmit" value="g" class="btn" />

                </form>

            close

jquery:
$('#post-link-a').click(function () {
    if($('#tip-nav-content').is(':hidden')){
        if($('#post-content').hasClass('show-the-content')){
            $('#tip-nav-content').slideDown();
        }
        else {
            $('#search-content').removeClass('show-the-content');
            $('#comment-content').removeClass('show-the-content');
            $('#post-content').addClass('show-the-content');
            $('#tip-nav-content').slideDown();
        }
    }
    else if($('#tip-nav-content').is(':visible')){
        if($('#post-content').hasClass('show-the-content')){
            $('#tip-nav-content').slideUp();
        }
        else {
            $('#search-content').removeClass('show-the-content');
            $('#comment-content').removeClass('show-the-content');
            $('#post-content').addClass('show-the-content');
        }
    }
    else {
        // nada
    }
});
$('#comment-link-a').click(function () {
    if($('#tip-nav-content').is(':hidden')){
        if($('#comment-content').hasClass('show-the-content')){
            $('#tip-nav-content').slideDown();
        }
        else {
            $('#search-content').removeClass('show-the-content');
            $('#post-content').removeClass('show-the-content');
            $('#comment-content').addClass('show-the-content');
            $('#tip-nav-content').slideDown();
        }
    }
    else if($('#tip-nav-content').is(':visible')){
        if($('#comment-content').hasClass('show-the-content')){
            $('#tip-nav-content').slideUp();
        }
        else {
            $('#search-content').removeClass('show-the-content');
            $('#post-content').removeClass('show-the-content');
            $('#comment-content').addClass('show-the-content');
        }
    }
    else {
        // nada
    }
});
$('#search-link-a').click(function () {
    if($('#tip-nav-content').is(':hidden')){
        if($('#search-content').hasClass('show-the-content')){
            $('#tip-nav-content').slideDown();
        }
        else {
            $('#post-content').removeClass('show-the-content');
            $('#comment-content').removeClass('show-the-content');
            $('#search-content').addClass('show-the-content');
            $('#tip-nav-content').slideDown();
        }
    }
    else if($('#tip-nav-content').is(':visible')){
        if($('#search-content').hasClass('show-the-content')){
            $('#tip-nav-content').slideUp();
        }
        else {
            $('#post-content').removeClass('show-the-content');
            $('#comment-content').removeClass('show-the-content');
            $('#search-content').addClass('show-the-content');
        }
    }
    else {
        // nada
    }
});
$('.kill-tn-content').click(function () {
    $('#tip-nav-content').slideUp();
});

CSS:
#tips-nav { position:relative; margin:0; padding:0; background:#E3DECB; }
#tip-nav-content { position:relative; display:none; overflow: hidden; margin:0; padding:0; }
#tip-nav-content:before { content:''; position:absolute; top: -10px; left: -10px; width:105%; height:10px; box-shadow: 0 0 15px rgba(26, 40, 53,.8); }

.tips-navigation { position:relative; height:50px; overflow:hidden; }
.tips-navigation ul { position:relative; height:50px; margin:0; padding:0; }
.tips-navigation li { display:block; float:left; text-align: center; background:#1A2835; }
.tips-navigation li:hover { background:#DB5D3B; }
.tips-navigation a { display:block; line-height: 49px; padding:0 0 1px; }
.tips-navigation a:before { font-family:dd_icons !important; font-size:.9em; margin-right:4px; }

#post-content { display:none; }
#comment-content { display:none; }
#search-content { display:none; }

.show-the-content { display:block !important; }

#tip-nav-content header { background:#CEC7B3; padding:15px 0; }
#tip-nav-content h4 { padding:0 20px; margin:0; }
#post-content h4:before, #comment-content h4:before { content:'T'; font-family: dd_icons; margin-right:7px; display:inline-block; font-size:1.2em; vertical-align: -2px; }
#search-content h4:before { content:'g'; font-family: dd_icons; margin-right:7px; display:inline-block; font-size:1.2em; vertical-align: -2px; }

.tip-nav-ul { margin:0; }
.tip-nav-ul li { position:relative; display:block; }
.tip-nav-ul li:hover { background:#DB5D3B; }
.tip-nav-ul li:hover a:before { color:#2A3F51; }
.tip-nav-ul li a { display:inline-block; margin:4px 0 0 0; padding:13px 13px !important; }
#pc-comment-ul li a { display:block; margin:0; padding:10px 0; font-size:.9em; }
#pc-comment-ul li:last-of-type { border:none; }
#pc-comment-ul li { height:initial; border-bottom:1px dashed #AAA48F; }
.rc-link:before { content:'b'; font-family: dd_icons; color:#898472; display:inline-block; margin-right:4px; }
#pc-post-ul li { overflow:hidden; padding:7px; border-bottom:1px dashed #AAA48F; }
#pc-post-ul li:last-of-type { border:none; }
#pc-comment-ul li:hover, #pc-post-ul li:hover { border-color:#DB5D3B; }
.tip-nav-ul li p { font-size:.9em; margin:0; color:#DB5D3B; }
.tip-nav-ul li:hover p { color:#fff; }
.tip-nav-ul li:hover p + p { color:#ddd; }
.tip-nav-ul li p + p { font-size:.8em; margin:0; color:initial; }
.tip-nav-thumb { display:block; float:left; width:52px; height:52px; background:#0F171E; margin-right:10px; }

.cf:before, .cf:after { content: ""; display: table; }
.cf:after { clear: both; }

A: I found the problem so figured I'd post it if anyone else runs into this.
The content divs had some old CSS from a test I did swapping classes qith Jquery and using CSS transitions. That doesn't work right so I went to using slideUp() and slideDown(). I forgot to remove those transitions once I added the jquery which seems to have caused the glitch. Once I removed the CSS transitions there was no more jumping and everything animates smoothly now.


text:
Q: heavy customized routing constraint slowing site down? It doesn't happen all the time, but after some heavy use it seems my site slows down a lot, the only code I have changed has been changing the redirects.
The routing finds old categories (that aren't in use anymore) and replaces them with their new category. so someone how goes to example.com/scary-shows/buffy will be redirected to example.com/television/buffy
I am trying to figure out the performance loss (if it's even happening here), and where I can improve it.
Global.asax:
...
// custom constraint
    routes.MapRoute("ArticlesCategories", "{category}/{page}",
       new { controller = "Custom", action = "CategoryRedirect" },
       new { isCategory = new CategoryRouteConstraint() });

    //Article routes
    routes.MapRoute("ArticlesRedirect", "Articles/Redirect",
       new { controller = "_Articles", action = "Redirect" });
             routes.MapRoute("ArticlesSubcategories", "articles/categories/{filter}/{section}",
                    new { controller = "_Articles", action = "Filter", filterBy = "categories", section = UrlParameter.Optional });
          routes.MapRoute("ArticlesTags", "articles/tags/{filter}",
    new { controller = "_Articles", action = "Filter", filterBy = "tags" });
...

Constraint:
   public class CategoryRouteConstraint:IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
                          RouteDirection routeDirection)
        {
            string page = string.Format("{0}", values["page"]);
            string urlCategory = string.Format("{0}", values["category"]);

            if (GetCategoryDictionary().ContainsKey(urlCategory))
            {
                string topCategory = GetCategoryDictionary()[urlCategory];
                values.Add("topCategory",topCategory);
                return true;
            }
            return false;
        }

        private static List<Category> _categoryList = null;
        private static object _lockObj = new object();
        private static Dictionary<string, string> _dictionary = null;

        private static Dictionary<string, string> GetCategoryDictionary()
        {
            if (_dictionary != null) return _dictionary;

            lock (_lockObj)
            {
                //check again...
                if (_dictionary != null) return _dictionary;
                var dictionary = new Dictionary<string, string>
                    {
                        {"my-old-example-category", "example"},
                        {"blogs", "Blog"},
                        {"doctor-notes", "Blog"},
                        {"action-movies", "movies"},
                        {"reality-tv", "television"},
                        {"scary-shows", "televsion"},
                        ... this goes on for about 100 more categories ...
                    };

                _dictionary = dictionary;
                return dictionary;
            }
        }
    }

Controller:
[OutputCache(Duration = 10800)]
public class CustomController : Controller
{
    public ActionResult CategoryRedirect()
    {
        string topCategory = string.Format("{0}", RouteData.Values["topCategory"]);
        string page = string.Format("{0}",RouteData.Values["page"]);

        return RedirectPermanent(string.Format("/{0}/{1}", topCategory, page));
    }
}

A: You could optimise your code a bit:

*

*Use .ToString() instead of string.Format (string.format uses expensive regex)

*Use TryGetValue() instead of your 2 operations

*Init the dictionary on app start or even consider dropping the dictionary at all, an large switch statement with a returned string is faster than the dictionary


text:
Q: SyntaxError: Cannot use import statement outside a module -> pupa package The package that has the issues is pupa
I am importing it as
import pupa from 'pupa'

I am running the tests using jest and I have changed my jest.config file
transformIgnorePatterns: [
    `node_modules/(?!(@pupa)/)`,
  ],

On my test file as well I am importing this on the top of my file
/**
 * @jest-environment jsdom
 */