text:
Q: Where are additional / stored in VisualStudio I've added an additional project dependency like this: Project>Right Click>Build Dependencies>Project Dependencies

I know that visual studio saves some information about project settings in the user-project file (.csproj.user). But I wanted to make sure all my colleagues also have this dependency added. So I started looking for changes in git (none), then changes in the .user-file, also none. I'm wondering, where is this information stored?
Any Ideas?


text:
Q: Kubespray etcdctl: "Error: client: etcd cluster is unavailable or misconfigured; error #0: no route to host Configuring Kubespray on 4 nodes, with 2(node1, node2) master nodes and installing etcd on node1 node2 node3, and node3-4 are worker nodes.
I get this following error,
fatal: [node1]: FAILED! => {"attempts": 8, "changed": false, "cmd": "/usr/local/bin/etcdctl --no-sync --endpoints=https://x.x.x.x:2379,https://x.x.x.x:2379,https://x.x.x.x:2379 cluster-health | grep -q 'cluster is healthy'", "delta": "0:00:00.023138", "end": "2020-06-05 17:07:03.033707", "msg": "non-zero return code", "rc": 1, "start": "2020-06-05 17:07:03.010569", "stderr": "Error:  client: etcd cluster is unavailable or misconfigured; error #0: dial tcp x.x.x.x:2379: connect: no route to host\n; error #1: EOF\n; error #2: dial tcp x.x.x.x:2379: connect: no route to host\n\nerror #0: dial tcp x.x.x.x:2379:

Could someone please explain me what I am doing wrong here while configuring these nodes?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What 's a good way to align layout across activities when one uses weight in linear layout while the rest does not? I utilized weight in the LinearLayout in the main screen of my app, but didn't do so in the other activity of my app. My goal is to align the circles and the start stop buttons in both activities, what's the best way to accomplish this? Below are my code for both activities' xml files.
Main activity that utilizes weight in LinearLayout:

    <View
        android:id="@+id/leftTopOfApp"
        android:layout_alignParentTop="true"
        android:layout_width="5dp"
        android:layout_height="1dp"
        android:background="@android:color/transparent" />

    <View
        android:id="@+id/topOfApp"
        android:layout_toRightOf="@id/leftTopOfApp"
        android:layout_width="1dp"
        android:layout_height="5dp"
        android:background="@android:color/transparent" />

    <TextView
        android:id="@+id/totalTimeView"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:layout_width="104dp"
        android:layout_height="40dp"
        android:gravity="right"
        android:textAlignment="gravity"
        android:layout_below="@id/topOfApp"
        android:layout_toRightOf="@+id/leftTopOfApp"
        android:textSize="17sp"

        android:background="@android:color/white"
        android:textColor="@color/started_black"
        />

    <ImageButton
        android:id="@+id/settings"
        android:layout_width="60dp"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_settings_black_24dp"
        android:scaleType="fitXY"
        />

    <View
        android:id="@+id/settingsToLinear"
        android:layout_below="@id/settings"
        android:layout_width="1dp"
        android:layout_height="30dp"
        android:background="@android:color/transparent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/settingsToLinear"
        android:gravity="center_horizontal"
        android:weightSum="3"
        android:orientation="vertical"
        >

    <TextView
        android:id="@+id/countDownView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1.8"
        android:background="@drawable/white_circle"
        android:textColor="@color/started_black"
        android:gravity="center"
        android:textSize="65sp" />

    <View
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_weight="0.15"
        android:background="@android:color/transparent" />

    <ToggleButton
        android:id="@+id/toggleSwitch"
        android:background="@drawable/toggle_selector"
        android:layout_width="250dp"
        android:layout_height="0dp"
        android:layout_weight="0.3"
        android:text=""
        android:textOn=""
        android:textOff=""
        />

    <View
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_weight="0.17"
        android:background="@android:color/transparent" />

    <ImageButton
        android:id="@+id/startButton"
        android:background="@drawable/button_selector"
        android:layout_width="275dp"
        android:layout_height="0dp"
        android:layout_weight="0.35"
        />

    </LinearLayout>
</RelativeLayout>

Started activity that doesn't not utilize weight at all.
<?xml version="1.0" encoding="utf-8"?>
<!--layout for when timer is started-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/green_go"
    android:paddingBottom="60dp"
    android:paddingLeft="35dp"
    android:paddingRight="35dp"
    tools:context=".MainActivity">

    <Chronometer
        android:id="@+id/currentElapsed"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/white_circle"
        android:gravity="center"
        android:textColor="@color/green_go"
        android:textSize="65sp" />

    <ImageButton
        android:id="@+id/stopButton"
        android:background="@drawable/stop_button"
        android:layout_centerHorizontal="true"
        android:layout_width="150dp"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

Any advice is appreciated, thank you!

A: You need to calculate ratio of layout_weight/weight_sum for your most bottom layout ("@id/settingsToLinear").Assuming that your first activity's weight_sum 3.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/green_go"
    android:paddingBottom="60dp"
    android:paddingLeft="35dp"
    android:paddingRight="35dp"
    tools:context=".MainActivity">

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        //NEEDS ID
        android:weightSum="10"
        android:orientation="vertical"
        >
    <Chronometer
        android:id="@+id/currentElapsed"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/white_circle"
        android:gravity="center"
        android:textColor="@color/green_go"
        android:textSize="65sp"
        android:layout_weight="7" />

    <ImageButton
        android:id="@+id/stopButton"
        android:background="@drawable/stop_button"
        android:layout_centerHorizontal="true"
        android:layout_width="150dp"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:layout_alignParentBottom="true" />
</LinearLayout>
</RelativeLayout>

Now both are covering 30 percent of screen.


text:
Q: How to convert a long to a Date with "dd/MM/yyyy" format I have a variable of type Long.
Long longDate = 20180201110400
It represents this: 2018/02/01 11:04:00
I want to convert the format and variable type like below:
Format should be "dd/MM/yyyy" and type should be Date. How can I do that?

A: You can covert the long to a Date object first then you can further convert it to your desired format. Below is the code sample.
Long longDate = 20180201110400L;

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

Date date  = dateFormat.parse(longDate.toString());

System.out.println("Date : "+date);

SimpleDateFormat dateFormatNew = new SimpleDateFormat("dd/MM/yyyy");

String formattedDate = dateFormatNew.format(date);

System.out.println("Formatted date : "+formattedDate);

A: cast Long to Date:
Long longDate = 20180201110400L;
String dateAsString = String.valueOf(longDate);
Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateAsString);

cast Date to String with "dd/MM/yyyy" format:
String formattedDate = new SimpleDateFormat("dd/MM/yyyy").format(date);

A: To convert in any standard date format, we can use SimpleDateFormat class. See the below snippet
Long longDate = new Date().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String formatedDate = dateFormat.format(longDate);

System.out.println(formatedDate);

Output : 01/02/2018


text:
Q: PyQt window focus events not called I have a PyQt4 program where I'm trying to get notified when a window gets focus, following the advice in the QUndoGroup docs:

It is the programmer's responsibility to specify which stack is active by calling QUndoStack::setActive(), usually when the associated document window receives focus.

But I have a weird problem where only one window actually gets the focusIn and focusOut events, while the others either receive only one at their creation, or else never receive them at all. Here is an example program:

    #!/usr/bin/env python

    from PyQt4.QtCore import *
    from PyQt4.QtGui import *

    import sys

    class MyWindow(QMainWindow):
        def __init__(self):
            super(MyWindow, self).__init__()
            self.label = QLabel('Window')
            self.setCentralWidget(self.label)
            self.setFocusPolicy(Qt.StrongFocus)

        def focusInEvent(self, event):
            self.label.setText('Got focus')

        def focusOutEvent(self, event):
            self.label.setText('Lost focus')

    def main():
        app = QApplication(sys.argv)
        win1 = MyWindow()
        win2 = MyWindow()
        win1.show()
        win2.show()
        sys.exit(app.exec_())

    if __name__ == '__main__':
        main()

A: I'm actually not quite sure why it doesn't work, might be an issue in how qt handles focus transition between windows. Anyways, below is how you might fix this, I've changed your code a bit
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import sys

class MyWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__()
        self.label = QLabel('Window')
        self.setCentralWidget(self.label)
        self.setFocusPolicy(Qt.StrongFocus)

    def focusInEvent(self, event):
        self.label.setText('Got focus')

    def focusOutEvent(self, event):
        self.label.setText('Lost focus')

def changedFocusSlot(old, now):
    if (now==None and QApplication.activeWindow()!=None):
        print "set focus to the active window"
        QApplication.activeWindow().setFocus()

def main():
    app = QApplication(sys.argv)
    QObject.connect(app, SIGNAL("focusChanged(QWidget *, QWidget *)"), changedFocusSlot)

    win1 = MyWindow()
    win2 = MyWindow()
    win1.show()
    win2.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

hope this helps, regards


text:
Q: Vue / Buefy Datetimpciker: How can I submit the results of an vue compontent to a form? For my new website project I wanted to use a datetime picker in a html form. As i use Bulma as CSS framework, I want to use the buefy datetimepicker https://buefy.org/documentation/datetimepicker, which is using vue.
For now, the datetimepicker is displayed nicely on my website, however, I am not able to receiving results when submitting the html form by a POST request.
What do I need to change to make the selected datetime available as a variable in php $_POST variable?
Code on codepen
<form action="submit.php" method="POST">

      <button class="button is-primary">Submit</button>

</form>

A: You should bind datetimepicker to a variable normally with v-model, then assign that variable to a hidden input field.
In HTML file
<input type="hidden" name="mydate" value="{{ mydate }}" />

In JS file
data() {
    ...,
    mydate: null
}


text:
Q: Android Java Fragment Data/Layout Transfer Keep getting no view found when calling dialog fragment from another fragment. I am trying to send image location to the dialog fragment to display.
Originating Fragment
mLEFTBUTTON.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Log.d("gogo", "left photo");

                DialogFragment fm = new DialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("stringUri",stringUri);
                //contains the location to be sent and re opened.
                fm.setArguments(bundle);
                fm.show(getChildFragmentManager(), stringUri);

            }
        });

Ending Fragment
public class PhotoLeft extends DialogFragment {
    public static final String TAG = "PhotoLeft";
    public static ImageView FragImageView;
    private TextView mActionOK, mActionCancel;
    private File mPhotoFile;
    public static Bitmap bmLarger;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){
        AlertDialog.Builder builder =
                new AlertDialog.Builder(getActivity());
        Log.d("gogo","inphoto1");
        Bundle bundle = getArguments();
        String stringUri = bundle.getString("stringUri");

        Bitmap bitmap = BitmapFactory.decodeFile(stringUri);
        FragImageView.setImageBitmap(bitmap);

        // Inflate the layout for this fragment
        Log.d("gogo","inphoto");

        return builder.create();
    }
}

A: I cannot see you have define you xml or view in dialog fragment.Please add it to render view of your dialog
public class PhotoLeft extends DialogFragment{

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState)
        {
            View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_my_dialog, new LinearLayout(getActivity()), false);

            // Retrieve layout elements
            ImageView FragImageView = (ImageView) view.findViewById(R.id.imaageview);

            Bundle bundle = getArguments();
            String stringUri = bundle.getString("stringUri");

            Bitmap bitmap = BitmapFactory.decodeFile(stringUri);
            FragImageView.setImageBitmap(bitmap);

            // Build dialog
            Dialog builder = new Dialog(getActivity());
            builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
            builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            builder.setContentView(view);
            return builder;
        }
    }


text:
Q: I am facing some issues related to expo ejection When I run expo eject on an empty project created by create-react-native-app or my complete project created in the same way, I get the following error:

Error: Group by name c:/Users/#folder-path#/ios/#projectname# not found!

The folder above does exist after the attempt. Here

A: I have never faced such type issue.but one way to solve this problem
1.Create new Project using react-native init firstapp
2.copy your code one by one into new react-native project from your expo project
3.every time run your project after paste first screen code.
Do not paste full code one by one..


text:
Q: python ctypes how to map PTSTR There is WINAPI call definition:
DWORD MapFileAndCheckSum(
  _In_   PTSTR Filename,
  _Out_  PDWORD HeaderSum,
  _Out_  PDWORD CheckSum
);

How to pass PTSTR param for the call?

A: Is it just:
filename = ctypes.c_char_p('something')
filename = ctypes.c_wchar_p('something') # for unicode

Edit: answer was based on the definition of PWSTR, PSTR, and PTSTR on this page and the ctypes docs.
And as suggested in the comments you should use restype/argtypes, especially if you are trying to be explicit, something like:
# define func
dll = ctypes.WinDLL(imagehlp)
mapfileandchecksuma = dll.MapFileAndCheckSumA
mapfileandchecksuma.restype = ctypes.wintypes.DWORD
mapfileandchecksuma.argtypes = [c_char_p,
                                POINTER(ctypes.wintypes.DWORD),
                                POINTER(ctypes.wintypes.DWORD)]

# call func
filename = 'ntkr128g.exe'
headersum  = ctypes.wintypes.DWORD()
checksum = ctypes.wintypes.DWORD()
if mapfileandchecksuma(filename,
                       byref(headersum),
                       byref(checksum)) == 0:
    print headersum.value, checksum.value

A: Just for the reference, the whole call to get checksum of PE binary turned up to be this:
filename = "ntkr128g.exe"
PTSTR = ctypes.c_char_p
headersum  = ctypes.wintypes.DWORD()
checksum = ctypes.wintypes.DWORD()
ctypes.windll.imagehlp.MapFileAndCheckSumA(
    PTSTR(filename), ctypes.byref(headersum), ctypes.byref(checksum))
print('head: 0x%08X, real: 0x%08X' % (headersum.value, checksum.value))


text:
Q: Help on solving integral equation Hello Stack Exchange Users,
I was working on an integration problem, and I "simplified" the integral to the following:
$$\int \limits_0^{2\pi} (7.625+.275 \cos(4x))^{1.5} \cdot (A \cos(Nx) + B \sin(Nx)) \cdot (Z-v \cos(x)) dx$$
This integral may seem impossible (I have almost lost all hope on doing this analytically.)  If anyone can suggest a approach on attacking this monster, please suggest (It doesn't matter how ugly the solution will turn up to be.  I will churn it out.)
Note: Assume all values to be constants EXCEPT $x$
Edit: It may be that the function doesn't have a "simple" antiderivative.  If so, please post the more complicated antiderivative.
Edit 2: I like the approach converting the trig functions to exponentials, but I am struggling in expanding the first part of the integral ($(7.625+.275 \cos(4x))^{1.5}$) using the exponential notation.  Can someone help me on that?  Additionally, N IS an integer.


text:
Q: Error MSG 213 Column name or number of supplied values does not match table definition Hi I'm trying to append the result of my query to another table, but i get the an error,  here is my code for the project
--create new table
create table tempweblogs
(
  date1 datetime
  users nvarchar(50)
  utotal int
  date2 datetime
  hostname nvarchar(50)
  htotal int
  date3 datetime
  srcip nvarchar(50)
  stotal int
)
--insert query result to tempweblogs table

insert into tempweblogs
SELECT distinct top 10
       Xdate as date1, Xuser as users, count (Xuser) as utotal
from   weblogs
where Xdate='2/16/2016'  and Xuser is not null
group by Xuser, Xdate order by utotal  DESC

SELECT distinct top 10
       Xdate as date2, Xhostname as hostname, count(Xhostname) as htotal
from weblogs
where Xdate='2/16/2016'  and xhostname is not null
group by Xhostname, Xdate order by htotal DESC

SELECT distinct top 10
       Xdate as date3, Xsrcip as srcip, count (Xsrcip) as stotal
from weblogs
where Xdate='2/16/2016'  and Xuser is not null
group by Xsrcip, Xdate order by stotal  DESC

A: You should need to specify the column list in the INSERT statement
insert into tempweblogs ( date1 , users , utotal )
select ....

also you need the INSERT clause for all 3 query


text:
Q: VB.NET tutorial for username/password check using database Where is a good VB.NET tutorial where I can have a username box and a password box and it checks in the database if it's there and if it is then another form will show?

A: Look here:
Introduction to Membership
There are a couple things you should know before you get started:

*

*Never, NEVER, NEVER store a plain-text password anywhere in your database. For that matter, don't even store an encrypted password in your database. Instead, you store a hashed password, using a cryptographic hashing algorithm (md5 isn't good enough). When someone wants to log in, you hash the attempted password and compare the hashes. Even this is the simplified version.

*You never want to implement security-related code yourself. Always rely as much as possible on the tools provided to you by your platform. The reason for this is that it's just so easy to write something seems to work — maybe even passes a whole slew of unit tests — but is still subtly flawed such that a year after going live with it you'll find out you were hacked six months ago. You don't want to be in that situation.


text:
Q: BLToolkit alternative object mapper that supports stored procedures I'm not too big of a fan of direct entity mappers, because I still think that SQL queries are fastest and most optimized when written by hand directly on and for the database (using correct joins, groupings, indexes etc).
On my current project I decided to give BLToolkit a try and I'm very pleased with its wrapper around Ado.net and speed so I query database and get strong type C# objects back. I've also written a T4 that generates stored procedure helpers so I don't have to use magic strings when calling stored procedures so all my calls use strong types for parameters.
Basically all my CRUD calls are done via stored procedures, because many of my queries are not simple select statements and especially my creates and updates also return results which is easily done using a stored procedure making just a single call. Anyway...
Downside
The biggest drawback of BLToolkit (I'd like everyone evaluating BLToolkit to know this) aren't its capabilities or speed but its very scarce documentation as well as support or lack thereof. So the biggest problem with this library is doing trial and error to get it working. That's why I also don't want to use too many different parts of it, because the more I use the more problems I have to solve on my own.
Question
What alternatives do I have to BLToolkit that:

*

*support use of stored procedures that return whatever entities I provide that are not necessarily the same as DB tables

*provide a nice object mapper from data reader to objects

*supports relations (all of them)

*optional (but desirable) support for multiple result-set results

*doesn't need any special configuration (I only use data connection string and nothing else)

Basically it should be very lightweight, should basically just have a simple Ado.net wrapper and object mapper.
And the most important requirement: is easy to use, well supported and community uses it.

A: Alternatives (May 2011)
I can see that big guns have converted their access strategies to micro ORM tools. I was playing with the same idea when I evaluated BLToolkit, because it felt bulky (1.5MB) for the functionality I'd use. In the end I decided to write the aforementioned T4 (link in question) to make my life easier when calling stored procedures. But there are still many possibilities inside BLToolkit that I don't use at all or even understand (reasons also pointed out in the question).
Best alternative are micro ORM tools. Maybe it would be better to call them micro object mappers. They all have the same goals: simplicity and extreme speed. They are not following the NoSQL paradigm of their big fellow ORMs, so most of the time we have to write (almost) everyday TSQL to power their requests. They fetch data and map them to objects (and sometimes provide something more - check below).
I would like to point out 3 of them. They're all provided in a single code file and not as a compiled DLL:

*

*Dapper - used by Stackoverflow itself; all it actually does it provides generic extension methods over IDbConnection which means it supports any backing data store as long there's a connection class that implements IDbConnection interface;

*

*uses parametrised SQL

*maps to static types as well as dynamic (.net 4+)

*supports mapping to multiple objects per result record (as in 1-1 relationships ie. Person+Address)

*supports multi-resultset object mapping

*supports stored procedures

*mappings are generated, compiled (MSIL) and cached - this can as well be downside if you use huge number of types)

*Massive - written by Rob Connery;

*

*only supports dynamic type mapping (no support in .net 3.5 or older baby)

*is extremely small (few hundreds of lines of code)

*provides a DynamicModel class that your entities inherit from and provides CRUD functionaly or maps from arbitrary baremetal TSQL

*implicit paging support

*supports column name mapping (but you have to do it every time you access data as opposed to declarative attributes)

*supports stored procedures by writing direct parametrised TSQL

*PetaPoco - inspired my Massive but with a requirement to support older framework versions

*

*supports strong types as well as dynamic

*provides T4 template to generate your POCOs - you'll end up with similar classes as big fellow ORMs (which means that code-first is not supported)  but you don't have to use these you can still write your own POCO classes of course to keep your model lightweight and not include DB only information (ie. timestamps etc.)

*similar to Dapper it also compiles mappings for speed and reuse

*supports CRUD operations + IsNew

*implicit paging support that returns a special type with page-full of data + all metadata (current page, number of all pages/records)

*has extensibility point for various scenarios (logging, type converters etc)

*supports declarative metadata (column/table mappings etc)

*supports multi object mapping per result record with some automatic relation setting (unlike Dapper where you have to manually connect related objects)

*supports stored procedures

*has a helper SqlBuilder class for easier building TSQL statements

Of all three PetaPoco seems to be the liveliest in terms of development and support most of the things by taking the best of the other two (and some others).
Of all three Dapper has the best real-world usage reference because it's used by one of the highest traffic sites on the world: Stackoverflow.
They all suffer from magic string problem because you write SQL queries directly into them most of the time. But some of this can be mitigated by T4, so you can have strong typed calls that provide intellisense, compile-time checking and re-generation on the fly within Visual Studio.
Downside of dynamic type
I think the biggest downside of dynamic types is maintenance. Imagine your application using dynamic types. Looking at your own code after a while will become rather problematic, because you don't have any concrete classes to observe or hang on to. As much as dynamic types are a blessing they're as well a curse on the long run.


text:
Q: Making your own wildcard and recognize patterns to zip your list I have an algorithm trouble, I don't know how to do it and how to call it (Does it have any specific name?)
For example, if I have this sequence:
000 CASE_01
001 CASE_02
010 CASE_03
011 CASE_02
100 CASE_02
101 CASE_01
110 CASE_01
111 CASE_01

I want to convert it in something like this:
000 CASE_01
0-1 CASE_02
010 CASE_03
100 CASE_02
1-1 CASE_01
11- CASE_01

I have called it wildcard because I think is the most correct way...
They not necessarily have 3 bits, you must do it with n bits
If only I had the psudo-code I could write it to any language (Python in my way)

A: The code below generates all possible wildcard strings for the number of bits encountered in the input (e.g. --, -0, -1, 0-, 00, 01, 1-, 10 and 11 for 2 bits), and also creates patterns where numbers are inverted and wildcards become 1 (so wildcard 0-1 has pattern 110), and masks where numbers become 1 and wildcards become 0 (so wildcard 0-1 has mask 101).
The binary numbers in the input are then XOR-ed with the patterns and AND-ed with the masks to check whether they fit a certain wildcard. If a wildcard has the required number of matching numbers (2 ^ number_of_wildcards), it is added to the output and the matching numbers are removed from the input.
Run the code snippet to see the algorithm in action with your example input, to which I added a fourth case with larger binary numbers.

function wildcard(input) {
    var output = [], cases = [], wilds = [], patts = [], masks = [];

    var bits = groupCases(cases);
    for (var i = 0; i <= bits; i++) wilds[i] = [];
    wildStrings(bits);
    convertStrings(wilds, patts, "-01", "110");
    convertStrings(wilds, masks, "-01", "011");

    for (var c = 0; c < cases.length; c++) {
        for (var i = 0, j = Math.pow(2, bits); i <= bits; i++, j /= 2) {
            for (var k = 0; k < patts[i].length; k++) {
                var patt = patts[i][k];
                var mask = masks[i][k];
                var matches = [];
                for (var d = 0; d < cases[c].nums.length; d++) {
                    var num = cases[c].nums[d];
                    if (((num ^ patt) & mask) == mask) matches.push(d);
                }
                if (matches.length == j) {
                    output.push(wilds[i][k] + " " + cases[c].id);
                    for (var l = j - 1; l >= 0; l--) cases[c].nums.splice(matches[l], 1);
                }
            }
        }
    }
    return output;

    function groupCases(cases) {
        var max = 0;
        for (var i = 0; i < input.length; i++) {
            var num = parseInt(input[i], 2);
            if (num > max) max = num;
            var id = input[i].slice(input[i].indexOf(" ") + 1);
            var pos = 0;
            while (cases[pos] != undefined && cases[pos].id != id) ++pos;
            if (cases[pos] == undefined) cases[pos] = {id: id, nums: []};
            cases[pos].nums.push(num);
        }
        return Math.ceil(Math.log(max) / Math.log(2));
    }

    function wildStrings(len, wild, str) {
        wild = wild || 0;
        str = str || "";
        for (var i = 0; i < 3; i++) {
            var w = (i == 0) ? 1 : 0;
            var s = str + ["-","0","1"][i];
            if (len > 1) wildStrings(len - 1, wild + w, s)
            else wilds[bits - wild - w].push(s);
        }
    }

    function convertStrings(input, output, from, to) {
        for (var i = 0; i < input.length; i++) {
            output[i] = [];
            for (var j = 0; j < input[i].length; j++) {
                var str = input[i][j], s = "";
                for (var k = 0; k < str.length; k++) {
                    s += to.charAt(from.indexOf(str.charAt(k)));
                }
                output[i].push(parseInt(s, 2));
            }
        }
    }
}

var a = ["000 CASE_01", "001 CASE_02", "010 CASE_03", "1010 CASE_04",
         "011 CASE_02", "100 CASE_02", "1110 CASE_04", "101 CASE_01",
         "110 CASE_01", "1100 CASE_04", "1000 CASE_04", "111 CASE_01"];
var w = wildcard(a);
document.write(w.length + " wildcards:

");
for (var i in w) document.write(w[i] + "
");


text:
Q: Value passing combobox to textarea of same page Today I got one interesting problem. I am working on SMS management so I have one dropdown to select template , after selecting template the same text should be apear on message body which is a text area and it is in the same jsp page. Some of my friends suggest me to do in Ajax but I dont know Ajax can any help me to solve this . Here is my select and textare elements.
<select class="selectpicker form-control"name="grade" data-style="btn-primary">
    <option></option>
    <c:forEach var="grade" items="${gradeInfo}">
        <option value="${grade.getDropDownName()}">
            ${grade.getDropDownName()}
        </option>
    </c:forEach>
</select>

       Message
    <textarea class="form-control " rows="6" placeholder="Message"
        style="height: auto;" id="MessageBox">
    </textarea>

Here dorpdown values come from database . If I select one value the same text should apear on textarea. Please Help me in this.

A: Try this one using jquery
use can use JQuery

CODE

Working Demo
If you want to load any template on the select within a div Try this

A: Here is a workaround :
If you put the ID/name of the template or something (the url) to identify the template in your database in the value of the select options.
HTML
 <select class="selectpicker form-control"name="grade" data-style="btn-primary">
 <option></option>
 <c:forEach var="grade" items="${gradeInfo}">
     <option value="${grade.getDropDownName()}">
         ${grade.getDropDownName()}
     </option>
 </c:forEach>
 </select>

       Message
    <textarea class="form-control " rows="6" placeholder="Message"
        style="height: auto;" id="MessageBox">
    </textarea>

Javascript
function updateTemplate(this) {
    $.ajax({
        url: "/template?name="+this.value
    }).done(function(data) {
        $( "#MessageBox").html(data);
    });
}

This probably need some work to fill your need but you can start here and check the doc of JQuery about ajax : Here


text:
Q: Getting Particleground in background? I'm trying to make an html and css page, and i'm actually trying to get a Particleground in background, but now, it's still in the bottom of the page, like this :
Particleground problem
My code is actually :

#particles {
    width: 100%;
    height: 100%;
    position: fixed;
}
<!DOCTYPE html>

 <meta charset="UTF-8">

 <link rel="stylesheet" href="css/style.css">
 <title>Contact form</title>

 <?php include 'includes/header.html'; ?>

Formulaire de contact

   <form action="contact.php" method="post">
    Nom d'utilisateur
    <input class="userForm" type="text" placeholder="Nom (30 caractères max.)" name="username">
    Email
    <input class="emailForm" type="email" placeholder="E-mail (100 caractères max.)" name="email">
    Message

    <textarea class="messageForm" rows="4" cols="50" placeholder="Message (2000 caractères max.)" name="message"></textarea>

    <input type="submit" placeholder="Envoyer" name="submit">
   </form>

Can someone help me solving my problem please ? :(
Thanks !

A: I finally found :
Just put the div containing #particles to z-index: -100; in your CSS file

#particles {
    z-index: -100;
    position: absolute;
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 50% 50%;
}
<!DOCTYPE html>

 <meta charset="UTF-8">

 <link rel="stylesheet" href="css/style.css">
 <title>Contact form</title>

Formulaire de contact

   <form action="contact.php" method="post">
    Nom d'utilisateur
    <input class="userForm" type="text" placeholder="Nom (30 caractères max.)" name="username">

    Email
    <input class="emailForm" type="email" placeholder="E-mail (100 caractères max.)" name="email">

    Message

    <textarea class="messageForm" rows="4" cols="50" placeholder="Message (de 20 à 2000 caractères)" name="message"></textarea>

                <input type="submit" placeholder='Envoyer' name="submit">

   </form>

Done!

Thanks to your answers nevertheless!  :)

A: Maybe you can set background size, for example:
#particles {
    position: absolute;
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 50% 50%;
}

Or your particles div should be above the contact form.


text:
Q: how to access new created partition in container I want to access new created partition in container with below actions but fail.
use --device= to mount a disk
docker run --privileged -d --device=/dev/vde:/dev/vde centos

use parted to create a new data partition
[root@cdba144bc679 ~]# lsblk
lsblk: dm-0: failed to get device path
lsblk: dm-1: failed to get device path
lsblk: dm-0: failed to get device path
lsblk: dm-1: failed to get device path
lsblk: dm-2: failed to get device path
lsblk: dm-3: failed to get device path
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
vda    253:0    0  116G  0 disk
├─vda1 253:1    0   52G  0 part /etc/hosts
└─vda2 253:2    0   64G  0 part
vdb    253:16   0  400G  0 disk
vdc    253:32   0  100G  0 disk
vdd    253:48   0   10G  0 disk
vde    253:64   0   10G  0 disk
vdf    253:80   0   10G  0 disk
vdg    253:96   0   10G  0 disk
[root@cdba144bc679 ~]# parted -s /dev/vdg  mklabel gpt mkpart 1 ext4 1 2M

With lsblk can view:
[root@cdba144bc679 ~]# lsblk
lsblk: dm-0: failed to get device path
lsblk: dm-1: failed to get device path
lsblk: dm-0: failed to get device path
lsblk: dm-1: failed to get device path
lsblk: dm-2: failed to get device path
lsblk: dm-3: failed to get device path
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
vda    253:0    0  116G  0 disk
├─vda1 253:1    0   52G  0 part /etc/hosts
└─vda2 253:2    0   64G  0 part
vdb    253:16   0  400G  0 disk
vdc    253:32   0  100G  0 disk
vdd    253:48   0   10G  0 disk
vde    253:64   0   10G  0 disk
vdf    253:80   0   10G  0 disk
vdg    253:96   0   10G  0 disk
└─vdg1 253:97   0    1M  0 part  <===

With ls can not access which means i can not use it:
[root@cdba144bc679 ~]# ll /dev/vdg*
brw-rw---- 1 root disk 253, 96 Nov  9 02:31 /dev/vdg

How can i access it?

A: The current method that Docker uses to pass devices into a container won't allow you to dynamically pass a device after a container is created.
There have been a few discussions around this: moby/moby #22563 is a merged PR, but has discussion about further enhancements after the merge was done. Also moby/moby #35359 is an open issue/feature request asking for device-related capabilities that would likely also serve your usecase.
The current workaround for right now would be to run fdisk in one container, and then run a new container that passes through all the block devices that are now available/created:
docker run --privileged -it --rm --device=/dev/vde:/dev/vde fdisk /dev/vde

Followed by:
docker run --privileged [...]\
    --device=/dev/vde:/dev/vde \
    --device=/dev/vde1:/dev/vde1 \
    --device=/dev/vde2:/dev/vde2 \
    centos


text:
Q: Javascript tabs widget with drag and drop reordering Do you know of a tab widget that has built-in drag+drop reordering? I'm building an editor-like interface and want to allow the user to reorder their tabs.
So far I've been using ExtJS with a community plugin, but it's buggy and usually needs updating with every new ExtJS release.

A: Is something like this what you're looking for?
I'd definitely use jQuery and jQuery UI as a base if I was trying to do what you are. The solid support structure and wealth of tutorials around jQuery is unbeatable!
Of course this is if you don't mind the weight of another javascript framework or having to recode some of your interface.
On a slight tangent, if you want your interface to remember a user's preferences you'll need a server-side language. Alternatively, use the jQuery cookie plugin to store preferences between page loads.

A: There's a draggable tab widget based on YUI lib just for that.
If you're not concerned about adding another javascript lib to your application, I think it's an interesting alternative. You can even drag and drop tabs from other containers (I didn't see this feature on your ExtJS plugin by the way).

A: There are attempts to make jquery tabs drag and drop able. While it is not drag and dropable out of the box you could make them yourself in jquery-ui.
Here are some resources that tried it:
Resource 1
Resource 2


text:
Q: I want my thread to handle interruption, but I can't catch InterruptedException because it is a checked exception I have a thread in Java which calls
t.interrupt();

making t (a different thread) be interrupted. I want the "t" thread to then catch an InterruptedException but Eclipse won't let me put an InterruptedException in saying it's not thrown in the try body. How can I get the InterruptedException to be called? Am I using t.interrupt() wrong?

A: While the other answers are correct, a fuller explanation is appropriate.
A thread can be safely interrupted (in the general sense of the word) only at specific points in its execution.  In particular, it can be interrupted safely when it has issued a wait() call, or has invoked a service that can issue wait().  This is why InterruptedException is a checked exception and not a runtime (unchecked) exception.  Allowing a thread to be arbitrarily interrupted at any point would make execution non-deterministic (at least that's the way the JVM was specified).  There is a Thread#stop() method which is strongly deprecated because it causes more problems than it solves.  From the Javadoc

This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

If you need to interrupt a running thread, then you must periodically poll the interrupted status with Thread.interrupted() or .isInterrupted() or poll a shared variable, and take appropriate action yourself.
Note: The term "interrupted" above (except as part of a method name) is intended in the general sense, not the specific meaning of calling Thread#interrupt().

A: Rather than catching InterruptedException you can call Thread.interrupted() or Thread.getCurrentThread().isInterrupted() (the former will clear the interrupted flag, the latter will not), which will return true if the interrupted flag is set.  You can only catch InterruptedException if you've called a method that throws it, like sleep

A: InterruptedException is only thrown from specific method calls - mostly any method calls that wait, sleep or do I/O, so it wont be thrown out of anywhere.
if the Thread youre trying to interrupt is doing something CPU-internsive and not I/O, you will need to sprinkle Thread.getCurrentThread().isInterrupted() calls in there otherwise the target thread might never notice.

A:
I want the "t" thread to then catch an InterruptedException but Eclipse won't let me put an InterruptedException in saying it's not thrown in the try body. How can I get the InterruptedException to be called? Am I using t.interrupt() wrong?

It is important to realize that t.interrupt() only sets the interrupted bit in a thread -- it doesn't actually interrupt the thread's processing per se.  A thread can be interrupted at any time safely.
To quote from the Thread.interrupt() javadocs:

*

*If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

*If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.

*If this thread is blocked in a java.nio.channels.Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

*If none of the previous conditions hold then this thread's interrupt status will be set.

It is important to add that if the thread's interrupt bit has been set and then wait() (and others) is called, then the wait() will throw InterruptedException immediately.
So you can't catch InterruptedExeption everywhere since only certain methods throw it.  If you want to see if a thread has been interrupted (again has the interrupt bit set) then the right thing to do is to test for it directly with the Thread.getCurrentThread().isInterrupted().  Typically we do something like the following:
while (!Thread.getCurrentThread().isInterrupted()) {
     // process stuff
     ...
     try {
         // here's an example of a method that throws InterruptedException
         Thread.sleep(100);
     } catch (InterruptedException e) {
         // throwing InterruptedException actually clears the interrupt bit
         // so it is a good pattern to re-interrupt the thread immediately
         Thread.currentThread().interrupt();
         // now we decide what to do since we are interrupted
         // you most likely shouldn't just continue processing
         break;
     }
}

There are a number of good questions and answers on this topic:

*

*What does java.lang.Thread.interrupt() do?

*How exactly does Thread.interrupt() and Thread.interrupted() work?

*How to stop uninterruptible threads in Java


text:
Q: SwiftUI UIImagePickerController adds Black Bars in Landscape I have a SwiftUI app with SwiftUI App lifecycle where the user can take photos of items
and store those images in the app persistent store. With one exception, the app
performs as expected. Both iPhone and iPad are supported. The exception is with photos
taken on an iPad in landscape mode. Those photos have a black band at the top and bottom
of the photo. I think that Apple only supports the portrait type capture, which would
be fine if I could crop the image to remove those bands. I've seen some older posts with this same issue, but none of the suggestions seems to apply now. I have not found any way to
eliminate the blackened area. I think my capture code is pretty standard.
In this image the green is what I get. The red is what I want.

struct CaptureImageView: View {
    @Binding var isShown: Bool
    @Binding var newUIImage: UIImage?

    func makeCoordinator() -> Coordinator {
        return Coordinator(isShown: $isShown, image: $newUIImage)
    }
}

extension CaptureImageView: UIViewControllerRepresentable {

    func makeUIViewController(context: UIViewControllerRepresentableContext<CaptureImageView>) -> UIImagePickerController {

        let vc = UIImagePickerController()

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
            vc.sourceType = .camera
            vc.allowsEditing = true
            vc.cameraCaptureMode = .photo
            vc.delegate = context.coordinator

            return vc
        }
        return UIImagePickerController()
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<CaptureImageView>) {
    }

}//extension

class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @Binding var isCoordinatorShown: Bool
    @Binding var imageInCoordinator: UIImage?

    init(isShown: Binding<Bool>, image: Binding<UIImage?>) {
        _isCoordinatorShown = isShown
        _imageInCoordinator = image
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        guard let unwrapImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else { return }

        imageInCoordinator = unwrapImage
        isCoordinatorShown = false

    }//image picker controller

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        isCoordinatorShown = false
    }

}//class

Any guidance would be appreciated. Xcode 14.3, iOS 14.3


text:
Q: Interpolação de Lagrange - ERRO no [do while] Estou criando um método para pegar n valores, adicionando-os em um array, e desses valores aplicar o método de interpolação de Lagrange para encontrar um polinômio. Logo após, encontrar um valor estimado de x para o intervalo definido pelo maior e o menor valor do conjunto de dados inputados.
Só que está dando um erro no do while, pois ele até pega o primeiro valor, mas ao passar pela primeira instrução de input ele dá o seguinte:

*

*ERRO:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at lagrange.calculate(lagrange.java:13)
at Main.main(Main.java:6)
exit status 1
import java.util.Scanner;

public class lagrange{
   public void calculate(){
      Scanner sc = new Scanner(System.in);
      double n[];
      int cont = 0;

      do {
        n = new double[cont];
        System.out.println("Digite o valor de numero " + cont + 1);
        n[cont] = sc.nextDouble(); //INPUT DE DADO NO ARRAY
        cont = cont + 1;
      } while(n[cont - 1] != 0); //continuar o processo até o array for igual a zero

   System.out.println(n[cont-1]);
   }
}

A: Na linha
int cont = 0;

troque para
System.out.println("Digite o grau do polinômio");
int cont = sc.nextInt() + 1;
int indice = 0;

Na linha
System.out.println("Digite o valor de numero " + cont + 1);

troque para
System.out.println("Digite o valor do coeficiente " + indice);

Na linha
n[cont] = sc.nextDouble();

troque para
n[indice] = sc.nextDouble();

Retire a linha
cont = cont + 1;

Na linha
} while (n[cont - 1] != 0);

troque para
} while (n[indice++] != 0 && indice < cont);


text:
Q: A singular $2×2$ matrix We assume a singular $2×2$ matrix $A=\begin{pmatrix}
a & b \\
c & d \\
\end{pmatrix}.$ Then $ad=bc$ and $A^2=(a+d)A$ and $A^n=(a+d)^{n-1}A.$ So
$$B=\sum_{n = 0}^{+\infty} \frac {A^{2n}}{(2n)!} = I+ \sum_{n = 1}^{+\infty} \frac {(a+d)^{2n-1}}{(2n)!}A$$
By the ratio test, the series $\sum_{n = 1}^{+\infty} \frac {(a+d)^{2n-1}}{(2n)!}$ converges and we have:
$$\sum_{n = 1}^{+\infty} \frac {(a+d)^{2n-1}}{(2n)!} = \frac{\cosh (a+d) -1}{a+d}$$
Could $B$ be a zero matrix?

A: $B=0\implies 0=\det A=(\frac {a+d}{1-\cosh (a+d)})^2\implies a+d=0$, a contradiction.


text:
Q: Dependency between defining constants in C? I used the #define command for following code and constants. I defined in the first WORKLOAD_MAX with 4 and second line TASK_COUNT_MAX with 10 and used multiplication of them in the third line.
after a long time debugging, I realized that the correct value does not apply while executing the code, and I have to manually set the value that I do not like it. (like 40 on the fourth commented line)
Someone can help.
Thank you
#define WORKLOAD_MAX 4
#define TASK_COUNT_MAX 10
#define READY_LOOP_DEEP TASK_COUNT_MAX*WORKLOAD_MAX
//#define READY_LOOP_DEEP 40

struct workItem                         // It is a STRUCT to keep the status of task in different stages
{
    int task_ID;                            // Task ID
    int workload_ID;                    // Workload ID
};

// Read from the beginning of the readyQueue
struct workItem readFromReadyQueue()
{
    struct workItem witem;
    // Picking up from queue head
    witem = readyQueue[readyQueueHead];
    // Move forward the queue head index in rotation
    readyQueueHead = (readyQueueHead + 1) % READY_LOOP_DEEP;
    // Reduce the number of queue elements
    readyQueueSize--;
    #ifdef PRINT_ReadReadyQueue
        printf("Task_ID #%d (Workload_ID #%d) read from readyQueue.\n", witem.task_ID , witem.workload_ID);
    #endif
    return witem;
}

A: Macros are textual replacements the semantics of which are context dependent.  In this case any occurrence of READY_LOOP_DEEP will be replaced with 4*10 which in context may not behave as you might expect due to operator precedence and evaluation order.  It is an example of a dangerous macro, and should be written thus:
#define READY_LOOP_DEEP (TASK_COUNT_MAX * WORKLOAD_MAX)

with parentheses to ensure the evaluation order is as expected.
In your case the expression:
readyQueueHead = (readyQueueHead + 1) % READY_LOOP_DEEP;

expands to:
readyQueueHead = (readyQueueHead + 1) % 4 * 10 ;

with left-to-right evaluation, so (readyQueueHead + 1) % 4 is multiplied by 10, rather than (readyQueueHead + 1) % 40 as you intended.
The parentheses change the expression to:
readyQueueHead = (readyQueueHead + 1) % (4 * 10) ;

which will evaluate as you intended.


text:
Q: why is my Unity photon Pun2 import not working? I'm trying to import unity Pun2 free assets but when i try to access any of the method i get an error. also all the imported scripts are showing errors. i have checked supported unity version for pun2. it says 2017.4.7+ and i'm using 2019.4.11f
Please someone help me i'm stuck here from last 2 days

A: Are you getting that error only in vscode or in Unity as well?
I had a similar error where VSCode could not find anything related with Photon. In order to solve it, I installed the latest version of mono and then set in VSCode preferences "omnisharp.useGlobalMono": "always.

A: Figured it out. i installed unity 2019.4.17 and now it's working. thank you for your help guys.


text:
Q: Java: Sorting specific Strings first, then sort by alpha numeric I try to sort according to:
MyPOJO:
String city;
String tokenA;
String tokenB;

city is a name of a City.
tokenA can only be either "ALARM" or "ALERT"
tokenB can only be either "ALARM" or "ALERT"

*

*MyPOJO with "ALARM" in either tokenA or tokenB or both must come first

*MyPOJO with "ALERT" in either tokenA or tokenB or both must come second

*last all the cities should come, sorted alphanumeric

If several MyPOJO's has "ALARM" in both tokenA and tokenB, sort according to city within.
If several MyPOJO's has "ALERT" in both tokenA and tokenB, sort according to city within.
A MyPOJO with ALARM in any field or both fields must always come before ALERT.
I have the first tokenA but Im not sure how to best bring in tokenB.
Code I have:
@Override
public int compareTo(Object other) {
    if (other == null) {
        throw new NullPointerException();
    }

    MyPOJO that = (MyPOJO) other;

    int token = tokenA.compareTo(that.tokenA);
    if (token != 0) {
        return token;
    }

    return city.compareTo(that.city);
}

A: Here is the method you want.
In the compareTo method do this:
if tokenA == ALARM and other.tokenA != ALARM return -1
if tokenA != ALARM and other.tokenA == ALARM return 1
if tokenB == ALARM and other.tokenB != ALARM return -1
if tokenB != ALARM and other.tokenB == ALARM return 1
if tokenB == ALARM and other.tokenB == ALARM
  return city.compareTo(other.city)
if tokenA == ALERT and other.tokenA != ALERT return -1
if tokenA != ALERT and other.tokenA == ALERT return 1
if tokenB == ALERT and other.tokenB != ALERT return -1
if tokenB != ALERT and other.tokenB == ALERT return 1
if tokenB == ALERT and other.tokenB == ALERT
  return city.compareTo(other.city)
return city.compareTo(other.city)


text:
Q: adding data to xml is giving error I am using a plsql block which has below code and is giving a error to me at  in if condition.
error:- ORA-31020: The operation is not allowed, Reason: Invalid pl/sql DOM handle
PROCEDURE add_to_xml(
    p_doc         IN OUT dbms_xmldom.domdocument ,
    p_node_parent IN dbms_xmldom.domnode ,
    p_table       IN xml_tabtype )
IS
  k_routine CONSTANT VARCHAR2(255) := gk_package||'add_to_xml';
  l_stmt    VARCHAR2(512);
  l_node_child dbms_xmldom.domnode;
  l_txt_node dbms_xmldom.domnode;
  l_elem dbms_xmldom.domelement;
BEGIN
  FOR i IN p_table.first..p_table.last
  LOOP
    l_elem              := dbms_xmldom.createelement( doc => p_doc , tagname => p_table( i ).tagname );
    l_node_child        := dbms_XMLDom.appendChild( p_node_parent , dbms_XMLDom.makeNode( l_elem ));
    IF p_table( i ).val IS NOT NULL THEN
      l_txt_node        := dbms_xmldom.appendchild( l_node_child , dbms_xmldom.makenode( dbms_xmldom.createtextnode( p_doc , p_table( i ).val )));
    END IF;
  END LOOP;
EXCEPTION
WHEN OTHERS THEN
  dbms_output.put_line('error in add_to_xml'||SQLCODE||sqlerrm);
END add_to_xml;

can you please why this error pop ups ?
I have debug this and before if condition I have all the relevent data comming through this procedure.My database version is 11.
THe calling code is
declare
t_xml_tab                      xxcu_hr_interface.xml_tabtype;
l_doc                          dbms_xmldom.domdocument;
      l_top_node                     dbms_xmldom.domnode;
      l_node_top_detail              dbms_xmldom.domnode;
      l_node_assignment_change       dbms_xmldom.domnode;
      l_node_hdr_assignment_hdr      dbms_xmldom.domnode;

begin
t_xml_tab.delete;
           t_xml_tab(t_xml_tab.count + 1).tagname := 'OperasjonsID';
           t_xml_tab(t_xml_tab.count).val := 'U'; --Defect 1047
           t_xml_tab(t_xml_tab.count + 1).tagname := 'BusinessGroupID';
           t_xml_tab(t_xml_tab.count).val := 101;
           t_xml_tab(t_xml_tab.count + 1).tagname := 'FirmaID';
           t_xml_tab(t_xml_tab.count).val := 984661185;
           t_xml_tab(t_xml_tab.count + 1).tagname := 'AnsattNr';
           t_xml_tab(t_xml_tab.count).val := 52022;
           t_xml_tab(t_xml_tab.count + 1).tagname := 'StartDato';
           t_xml_tab(t_xml_tab.count).val := xxcu_hr_common.conv_date('18-AUG-75');
           t_xml_tab(t_xml_tab.count + 1).tagname := 'SluttDato';
           t_xml_tab(t_xml_tab.count).val := xxcu_hr_common.conv_date('31-DEC-12');
           t_xml_tab(t_xml_tab.count + 1).tagname := 'Primaer';
           t_xml_tab(t_xml_tab.count).val := 'J';
           t_xml_tab(t_xml_tab.count + 1).tagname := 'IntegrationKey1';
           t_xml_tab(t_xml_tab.count).val := 11933;
           t_xml_tab(t_xml_tab.count + 1).tagname := 'IntegrationKey2';
           t_xml_tab(t_xml_tab.count).val := 123;
           t_xml_tab(t_xml_tab.count + 1).tagname := 'PersonKategori';
           t_xml_tab(t_xml_tab.count).val := 1;

           dbms_output.put_line('3.7');

           ---dbms_output.put_line('3.7.1 t_xml_tab'||t_xml_tab(t_xml_tab.count + 1).tagname );

           xxcu_hr_interface.add_to_xml(p_doc         => l_doc,
                                        p_node_parent => l_node_hdr_assignment_hdr,
                                        p_table       => t_xml_tab);

 --dbms_output.put_line(l_doc);
exception
when others then
dbms_output.put_line('The error is :'||sqlcode||sqlerrm);
end;

A: You need to create your document via the createdocument function before passing it into your procedure.
DBMS_XMLDOM Documentation


text:
Q: How to improve Trac's performance I have noticed that my particular instance of Trac is not running quickly and has big lags.  This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN).
Setup Info: This is via a SELinux system hosted by WebFaction.  It is behind Apache, and connections are over SSL.  Currently the .htpasswd file is what I use to control access.
Are there any recommend ways to improve the performance of Trac?

A: It's hard to say without knowing more about your setup, but one easy win is to make sure that Trac is running in something like mod_python, which keeps the Python runtime in memory. Otherwise, every HTTP request will cause Python to run, import all the modules, and then finally handle the request. Using mod_python (or FastCGI, whichever you prefer) will eliminate that loading and skip straight to the good stuff.
Also, as your Trac database grows and you get more people using the site, you'll probably outgrow the default SQLite database. At that point, you should think about migrating the database to PostgreSQL or MySQL, because they'll be able to handle concurrent requests much faster.

A: We've had the best luck with FastCGI.  Another critical factor was to only use https for authentication but use http for all other traffic -- I was really surprised how much that made a difference.

A: I have noticed that if
select disctinct name from wiki

takes more than 5 seconds (for example due to a million rows in this table - this is a true story (We had a script that filled it)), browsing wiki pages becomes very slow and takes over 2*t*n, where t is time of execution of the quoted query (>5s of course), and n is a number of tracwiki links present on the viewed page.
This is due to trac having a (hardcoded) 5s cache expire for this query. It is used by trac to tell what the colour should the link be. We re-hardcoded the value to 30s (We need that many pages, so every 30s someone has to wait 6-7s).
It may not be what caused Your problem, but it may be. Good luck on speeding up Your Trac instance.

A: Serving the chrome files statically with and expires-header could help too. See the end of this page.


text:
Q: TypeORM Insert Returning - Getting Correct ID Back But As 3 Different Names For Same Value I'm inserting into a MS SQL table with an identity column, and need the newly inserted ID returned.
This code does the correct insert, and correctly returns the newly created ID.  I can't figure out why I get three different names for the same returned value.
This isn't blocking anything - just curious if there's a cleaner way to only get one returned reference:
import "reflect-metadata";
import {createConnection} from "typeorm";
import {getConnection} from "typeorm";
import {Organizations} from "./entity/Organizations"

createConnection().then(async connection => {

    //insert new organization - return organizationId
    const newOrganizationId = await getConnection()
        .createQueryBuilder()
        .insert()
        .into(Organizations)
        .values([
            { organizationName: "Test Organization", organizationId: 2, orgShortName: "TestOrg"}
        ])
        .returning(["organizationId"])
        .execute();
    //  .getSql();
    console.log("Organization Created: ", newOrganizationId);
}).catch(error => console.log(error));

Here's what's getting returned:
Organization Created:  InsertResult {
  identifiers: [ { organizationId: 8 } ],
  generatedMaps: [ { organizationId: 8 } ],
  raw: [ { organizationId: 8 } ]
}

Why all three references for the same organizationID value?

A: Figured it out:
console.log(newOrganizationId.raw);


text:
Q: Match escaped html in regex c# How can I escape html codes in Regex?
I need to find the string
&

in a string like
this is my string & this is another string

I can not use HtmlEncode/Decode for this purpose cause i need work with tags. That i want i just find the common string.
I use this, and work for example with "another" or "my" but doesn't work with "&".
            Regex regularextest = new Regex("\b&\b", options);
            string RSTest = "char $& morechar";
            string lalala = regularextest.Replace("foo & bar", RSTest);

It's very frustrating because google replaces the string with an & or "AND" word.
Thanks in advance

A: This \b&\b will not match because & and ; are not word characters.
You could try this :
Regex regularextest = new Regex("(?<=^|\s+)&(?=\s+|$)", options);

A: If you need to identify/convert valid entities (non-unicode), you could use this regex
(?:&(?:[A-Za-z_:][\w:.-]*|\#(?:[0-9]+|x[0-9a-fA-F]+));)
to identify a possible value to replace, pass it to a callback function that further process the entity you wish to replace. This way it could all be done in a single regex global replace (with callback logic).


text:
Q: VS Code: Configure keyboard shortcuts to move cursors when !textInputFocus I'd like to use Ctrl+B/Ctrl+F for VSCode Neovim when editing code, which I assume textInputFocus is about, and use them to move the cursor left/right when not editing code, for example in:

*

*Command Palette

*Search Files

*Code Search

*Settings UI

VSCode Neovim doesn't interact with those text fields, so you can't use h/l to move your cursor left/right, which is why I want Ctrl+B/Ctrl+F there.
I tried the following keybindings.json, but it didn't work:
[
    {
        "key": "ctrl+b",
        "command": "cursorLeft",
        "when": "!textInputFocus"
    },
    {
        "key": "ctrl+f",
        "command": "cursorRight",
        "when": "!textInputFocus"
    }
]

Note: The same thing seems to work on macOS without any configuration. I'd like to have the same behavior on Linux. A key remapper is not useful for it because it can't be aware of VSCode NeoVim's current mode.


text:
Q: Random for any database Rails PostgreSQL requires random() and MySQL requires rand() is there any way to write query for both databases in Rails way?
On localhost I'm using PostgreSQL, on development MySQL, the query is:
@texts = Text.where('status is true and id != ?', @text.id).limit(3).order("RANDOM()")

A: Try as below,
 case ActiveRecord::Base.connection.adapter_name
  when 'PostgreSQL'
     @texts = Text.where('status is true and id != ?', @text.id).limit(3).order("RANDOM()")
  else
     @texts = Text.where('status is true and id != ?', @text.id).limit(3).order("rand()")
  end

A: You can use offset to your advantage to find a random record independently from your database.
Text.offset(rand(Text.count)).first


text:
Q: Password hashing for php 5.3.3 So I read alot of topics here on stackoverflow.
Most of them say that password_hash is the best, but Its only for php 5.5.5.
So what is the best hashing for php 5.3.3? And shall I hash it?
Thank you


text:
Q: SQLite DB is Duplicating a last record in Table how to prevent a SQLite DB to duplicate my record its actually duplicating a last record of my Table i have primary key don't want to make it UNIQUE Key.
public void AddCity(String cityname)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues _values = new ContentValues();

    try {

        _values.put("City_name", Cityname);
        db.insert(TABLE_City,null,_values);
        // Log.d("Record inserted",Cityname);
        db.close();
    }
    catch (SQLException e)
    {
        e.printStackTrace();
        Log.d("Exception", e.toString());

    }
}


text:
Q: How do I translate VB.NET's CType() to C#? I have this code segment in VB.NET:
CType(pbImageHolder.Image, Bitmap).SetPixel(curPoint.X, curPoint.Y, Color.Purple)

What is appropriate code in C#?

A: In VB.Net CType(object, type) casts an object to a specific type.
There are two ways to accomplish this in C#:
Bitmap image = pbImageHolder.Image as Bitmap;
image.SetPixel(curPoint.X, curPoint.Y, Color.Purple);

or
Bitmap image = (Bitmap)(pbImageHolder.Image);
image.SetPixel(curPoint.X, curPoint.Y, Color.Purple);

A: Hi this is the code after conversion VB to C# code:
((Bitmap)pbImageHolder.Image).SetPixel(curPoint.X, curPoint.Y, Color.Purple);

And if you want code conversion from VB to C# and vice verse go through the following link: http://www.developerfusion.com/tools/convert/vb-to-csharp/

A: ((Bitmap)pbImageHolder.Image).SetPixel(curPoint.X, curPoint.Y, Color.Purple)

A: I'm surprised that none of the answers on this subject are correct so I decided to post here. You can verify what is going on by decompiling a VB.NET program. The answer depends on the type being converted to.
For reference types:
Dim value = CType(x, ReferenceType)
var value = (ReferenceType)x;
For structs:
Dim value = CType(x, StructType)
var value = (x != null) ? ((StructType)x) : default(StructType);
For predefined casts:
Dim value = CDbl(x)
var value = Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(x)
Which looks like this:
internal static double ToDouble(object Value, NumberFormatInfo NumberFormat)
{
    if (Value == null)
    {
        return 0.0;
    }
    IConvertible convertible = Value as IConvertible;
    if (convertible != null)
    {
        switch (convertible.GetTypeCode())
        {
        case TypeCode.Boolean:
            if (Value is bool)
            {
                return 0 - (((bool)Value) ? 1 : 0);
            }
            return 0 - (convertible.ToBoolean(null) ? 1 : 0);
        case TypeCode.SByte:
            if (Value is sbyte)
            {
                return (sbyte)Value;
            }
            return convertible.ToSByte(null);
        case TypeCode.Byte:
            if (Value is byte)
            {
                return (int)(byte)Value;
            }
            return (int)convertible.ToByte(null);
        case TypeCode.Int16:
            if (Value is short)
            {
                return (short)Value;
            }
            return convertible.ToInt16(null);
        case TypeCode.UInt16:
            if (Value is ushort)
            {
                return (int)(ushort)Value;
            }
            return (int)convertible.ToUInt16(null);
        case TypeCode.Int32:
            if (Value is int)
            {
                return (int)Value;
            }
            return convertible.ToInt32(null);
        case TypeCode.UInt32:
            if (!(Value is uint))
            {
                return convertible.ToUInt32(null);
            }
            return (uint)Value;
        case TypeCode.Int64:
            if (Value is long)
            {
                return (long)Value;
            }
            return convertible.ToInt64(null);
        case TypeCode.UInt64:
            if (!(Value is ulong))
            {
                return convertible.ToUInt64(null);
            }
            return (ulong)Value;
        case TypeCode.Decimal:
            if (Value is decimal)
            {
                return convertible.ToDouble(null);
            }
            return Convert.ToDouble(convertible.ToDecimal(null));
        case TypeCode.Single:
            if (Value is float)
            {
                return (float)Value;
            }
            return convertible.ToSingle(null);
        case TypeCode.Double:
            if (Value is double)
            {
                return (double)Value;
            }
            return convertible.ToDouble(null);
        case TypeCode.String:
            return ToDouble(convertible.ToString(null), NumberFormat);
        }
    }
    throw new InvalidCastException(Utils.GetResourceString("InvalidCast_FromTo", Utils.VBFriendlyName(Value), "Double"));
}


text:
Q: Regex: matches to new line or end of line or space in JS I wanted to extract :privacy and :date from the example string below.
I wanted to have a regex constraint that describes that a :[^:\s]+ block (e.g. :privacy or :date) can only be ended
by a space \s or a newline \n or a end of string $ (so I will be able to have a rule to logically split these blocks in the later steps).
So I simply put (?:$|\n|\s) at the end of the regex, but I doesn't work for me (the 3rd regex below). I double checked that it does work when
I separately put \s or $ (the 1st and 2nd regex below), now I have no idea how I can implement the thing. Thanks for your help.
'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+\s/g)
(1) [' :privacy ']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+$/g)
(1) [' :date']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+(?:$|\n|\s)/g)
(1) [' :privacy ']

A: You can use below regex pattern to match a block pattern :[^:\s+]+ ended by a space \s or a newline \n or a end of string $
/((:[^:\s+]+)(?:[\s\n]))|(:[^:\s+]+)(?:[\s\n])?$/gm

(?:[\s\n]) - will check if the block is being followed by a space or a new line
(:[^:\s+]+)(?:[\s\n])?$ - will check if the block is at the end of string or not.

you can also use lookforward technique to achieve the same result
(:[^:\s+]+)(?=\s|\n|$)

A: In your pattern \s:[^:\s]+\s you are matching the leading and the trailing whitespace chars.
What you might do is assert a whitespace boundary using (?!\S) to the right.
To get the value without the leading whitespace char, you can use a capture group.
\s(:[^:\s]+)(?!\S)

Regex demo

const s = "note::tmp hogehoge. :privacy :date";
const regex = /\s(:[^:\s]+)(?!\S)/g;
const result = Array.from(s.matchAll(regex), m => m[1]);
console.log(result);


text:
Q: Hide several divs and only after all are hidden, then run a callback function I am needing to hide all of the divs of class .panel in a container div.  Then after all are hidden, selectively unhide a few of the .panel divs.  I tried using a callback on hide() but the callback runs for every single element that is hidden.  In some cases I end up in a nearly infinite or long running loop as the same divs are hidden and shown over and over.
This does not work as the second elements are being shown before the hide is complete:
$("#detailsPanel").children(".panel").hide();
$("#membershipPanel").slideDown();
$("#specializationsPanel").slideDown();

And if I nest those steps after the hide in a callback, the call back runs for every .panel div that is hidden.

FULL CODE
Here is my full function if that helps to find the flaw in my logic.
function goWizard(step) {
    switch (step) {
        case 0:
            $("#formPanel").hide();
            $("#beginPanel").slideDown();
            $("#instructionsPanel").slideDown().children().slideDown();
            $("#loginPanel").slideDown().children().slideDown();
            break;
        case 1:
            $("#beginPanel").hide().children().hide();
            $("#stepTitle").text("Membership Category/Specialist Category :: Step 1 of 8");
            $("html, body").animate({ scrollTop: 0 }, "slow");
            $("#summaryPanel").slideDown().children().show();
            $("#formPanel").slideDown();

            var i = 0;
            var $panels = $("#detailsPanel").children(".panel");
            $panels.hide(function () {
                i++;
                if (i == $panels.length) {
                    $("#membershipPanel").show();
                    $("#specializationsPanel").show();
                }
            });

            $("#startOverButton").show();
            $("#prevStepButton").hide();
            $("#nextStepButton").show();
            $("#startOverButton").click(function () { goWizard(0); });
            $("#nextStepButton").click(function () { goWizard(2); });
            break;
        case 2:
            $("#beginPanel").hide().children().hide();
            $("#stepTitle").text("Section Membership :: Step 2 of 8");
            $("html, body").animate({ scrollTop: 0 }, "slow");
            $("#summaryPanel").slideDown().children().show();
            $("#formPanel").slideDown();

            var i = 0;
            var $panels = $("#detailsPanel").children(".panel");
            $panels.hide(function () {
                i++;
                if (i == $panels.length) {
                    $("#sectionsPanel").show();
                }
            });

            $("#startOverButton").hide();
            $("#prevStepButton").show();
            $("#nextStepButton").show();
            $("#prevStepButton").click(function () { goWizard(1); });
            $("#nextStepButton").click(function () { goWizard(3); });
            break;
        case 3:
            $("#beginPanel").hide().children().hide();
            $("#stepTitle").text("Insurance Compliance :: Step 3 of 8");
            $("html, body").animate({ scrollTop: 0 }, "slow");
            $("#summaryPanel").slideDown().children().show();
            $("#formPanel").slideDown();

            var i = 0;
            var $panels = $("#detailsPanel").children(".panel");
            $panels.hide(function () {
                i++;
                if (i == $panels.length) {
                    $("#insurancePanel").show();
                }
            });

            $("#startOverButton").hide();
            $("#prevStepButton").show();
            $("#nextStepButton").show();
            $("#prevStepButton").click(function () { goWizard(2); });
            $("#nextStepButton").click(function () { goWizard(4); });
            break;
        default:
            $("#beginPanel").slideDown();
            $("#formPanel").hide();
            break;
    }
}

A: I would use promises:
$.when(
    $("#detailsPanel").children(".panel").hide().promise(),
    $("#membershipPanel").slideDown().promise(),
    $("#specializationsPanel").slideDown().promise()
).done(function() {
    console.log('all done');
});

Example: https://jsfiddle.net/jjh65h2y/

A: You could modify your hide callback to check if the element being hidden is the last one, and then do the callback in that portion, like so...
var i = 0;
var $panels = $("#detailsPanel").children(".panel");
$panels.hide(function() {

    i++;
    if(i == $panels.length) {
        $("#membershipPanel").slideDown();
        $("#specializationsPanel").slideDown();
    }

});

A: Given a DOM structure like (example):

text

text

text

text

text

You can hide and then unhide the elements in 2 ways with jQuery.
Either:
$.when($('.panel').animate({opacity: 0}, 500)).then(function () {
  $('.unhide').animate({opacity: 1}, 500);
});

Or:
$('.panel').animate({opacity: 0}, 500).promise().done(function () {
  $('.unhide').animate({opacity: 1}, 500);
});

https://jsfiddle.net/q2mctsz6/


text:
Q: Executing XML to Copybook COBOL and vice versa transformation in JAVA application I am new to COBOL Copybook/ XML mapping. So please forgive me for any silly question I ask here.
Basically I'm required to perform XML to COBOL Copybook and vice versa transformation in a Java Application. I know it can be done in WebShpere Transformation eXtender (WTX) but my requirement is to do it in Java application where WTX runtime will not be available (I guess).
Is there any jars available which I can use in Java to perform these requirements? Any help in this regard would be much appreciated!

A: Have look at CobolToXml project. It can convert Xml to a Mainframe Binary File using a Cobol Copybook. The Xml tags must match the Cobol field names though.
See CobolToXml  description wiki
To Convert  Xml to a Cobol binary file in java:
JRecordConstantVars constants = Cobol2Xml.JR_CONSTANTS;
Cobol2Xml.newCobol2Xml("G:/Users/Bruce01/RecordEditor_HSQL/CopyBook/Cobol/DTAR020.cbl")

                                 // Cobol Options
                 .setFileOrganization(constants.IO_FIXED_LENGTH)
                 .setDialect(constants.FMT_MAINFRAME)
                 .setSplitCopybook(constants.SPLIT_NONE)
                 .setFont("cp037")

      .xml2Cobol("G:/Users/Bruce01/RecordEditor_HSQL/SampleFiles/DTAR020.bin.xml",
                 "G:/Users/Bruce01/RecordEditor_HSQL/SampleFiles/DTAR020byJava.bin");

Disclaimer I wrote CobolToXml

A: Check out the cb2xml project at https://sourceforge.net/projects/cb2xml/

*

*Click Download, unzip the downloaded .zip file.

*Navigate to the lib folder. You can add the cb2xml*.jar files to your project and use them in your Java development.


text:
Q: Using Google Auth in Development I recently submitted a verification request to have a public Google OAuth Client and with that I had to remove my localhost URIs and callbacks. I've tried to figure out what the best way for using Google Auth in development is but couldn't find a definite solution.
Does anybody have insights by any chance?

A: The best option you will have would be to create a second project to use in development.  Then use the verified one for production.
This solves any problems you may have if you are testing something that would require you to change scopes.  If you change the scopes used in your production application chances are it will have to go though verification again.  So having a test app is the best solution i have come up with.


text:
Q: Could not get audio input for record source 7 on quickblox I am using Quickblox  version 2.5.2 to develop video chat. But when ever the call connects its crashing. I have added the log files below.
E/AudioRecord: Could not get audio input for record source 7, sample rate 48000, format 0x1, channel mask 0x10, session 648, flags 0
E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22. E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
W/System.err: java.lang.AssertionError: Expected condition to be true
W/System.err: at org.webrtc.voiceengine.WebRtcAudioRecord.assertTrue(WebRtcAudioRecord.java:266)
W/System.err: at org.webrtc.voiceengine.WebRtcAudioRecord.InitRecording(WebRtcAudioRecord.java:186)
E/rtc: #
# Fatal error in ../../webrtc/modules/utility/source/jvm_android.cc, line 117
# Check failed: !jni_->ExceptionCheck()
# Error during CallIntMethod
#
A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 13555 (Thread-2350)

I googled to solve this issue, but I didn't get any relevant answer.


text:
Q: See how the website is visited (mouse movements DOM) Open Web Analytics has a great feature that allows to see how a visitor visited your website, you can "replay" his visit, and see how the DOM of the website was visited, see the mouse movements, the page scrolls. This is an demo video.
Is this feature available in Google Analytics? If so, where? I haven't found it.


text:
Q: Removing impossible words from list to solve wordle I am making a Wordle AI bot and need some help. My bot isn't fancy just removes words it cant be based on the feedback from previous turn, then pick a random word from the possible words for the next turn. I need help with dealing with 'grey' letters. Annoyingly I cant just remove all words that have the grey letter in it because of words with double letters. E.g, the answer is LUNCH and I guess HELLO the first L would be yellow and the second grey. So basically I need help removing the words it definitely cant be. My code does work but removing words when the letter is grey isnt strict enough so I want to properly remove all words that the word cannot be. Cheers.
Note letter_states is -1 for yellow letter, 0 for grey and 1 for green
Note guess_counter is the turn goes from 0-6
Note letter is a list of each letter in alphabet
Note letter_index correspondes to the position in the alphabet the letter is. So 0 would correspond to A and 5 would correspond to F.
      if guess_counter == 0:

         self.dictionary_copy = list(self.dictionary)
         return (random.choice(self.dictionary_copy))

      #  If not first guess
      else:
         for letter_index in range(len(letter_states)):

            if letter_states[letter_index] == 1:  # 1 means green
               words_to_remove = []

               for word in self.dictionary_copy:
                  if self.letters[letter_indexes[letter_index]] not in word[letter_index]:
                     words_to_remove.append(word)

               for word in words_to_remove:
                  self.dictionary_copy.remove(word)

            elif letter_states[letter_index] == -1:  # -1 means yellow
               words_to_remove = []

               for word in self.dictionary_copy:
                  if self.letters[letter_indexes[letter_index]] not in word or self.letters[letter_indexes[letter_index]] in word[letter_index]:
                     words_to_remove.append(word)

               for word in words_to_remove:
                  self.dictionary_copy.remove(word)

            elif letter_states[letter_index] == 0:  # 0 means grey
               words_to_remove = []

               for word in self.dictionary_copy:
                  if self.letters[letter_indexes[letter_index]] in word[letter_index]:
                     words_to_remove.append(word)

               for word in words_to_remove:
                  self.dictionary_copy.remove(word)

      return (random.choice(self.dictionary_copy))


text:
Q: transparent layers on a stacked bar plot using ggplot2 dt1 <- data.frame(yr=c(2010,2010,2011,2011), val=c(1500,3000,2000,1100), x=c("a","b","a","b"))
dt1$alphayr <- as.factor(ifelse(dt1$yr == "2011", 0.5, 1))

ggplot() + geom_bar(data=dt1, aes(x=yr, y=val, fill=x, alpha=factor(alphayr)), stat="identity") +
  scale_x_continuous(breaks=dt1$yr) +
  scale_alpha_manual(values = c("0.5"=0.2, "1"=1), guide='none')

Instead of controlling which whole bars are transparent, I need to control which layers are transparent.
How to make it so that all of the lowest layers are 100% transparent?

A: It looks like you can achieve what you want to do by setting alpha = 0 wherever x == "b":
library(ggplot2)
library(dplyr)

dt1 <- tibble(yr=c(2010,2010,2011,2011), val=c(1500,3000,2000,1100), x=c("a","b","a","b")) %>%
  mutate(alphayr = ifelse(x == "b", 0, 1))

ggplot(dt1) +
  geom_col(aes(x = yr, y = val, fill = x, alpha = alphayr)) +
  scale_alpha_identity()


text:
Q: Java: how to index elements that have an associated interval? Suppose I have a number of objects with a start value and an end value that are comparable via some Comparator.
What kind of collection can I use to make an index of the objects, so that given an arbitrary value V, I can find all the objects where V is between the start and end values?
I'm stumped.

A: See http://en.wikipedia.org/wiki/Interval_tree. You should probably ignore the complicated "centered tree" construction that occurs first there, and look instead at the "augmented tree" which is the standard way to do it.

A: I some circumstances, a relational database, possibly with temporal support, may be a suitable alternative.


text:
Q: WPF RichTextBox - Replace Selected Text with Custom Control Before I start hacking in a really crude solution, I thought I'd see if someone could give me a little nudge in the right direction.
What I really want to do is let a user select some text in a RichTextBox, click a button, and convert that text into a custom rendered control.  Convert it to a Button containing the text they had selected, for instance.

A: You can do this with Command and CommandParameter
First, bind the button to an ICommand, like:
<Button Content="Go" Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=myRichTextBox, Path=Selection}" />
<RichTextBox Name="myRichTextBox" />

Then in your ViewModel or Controller or Code-behind or wherever, you expose the ICommand as a property,and point it to a method to do the work, like...
public ICommand MyCommand
{
    get
    {
        if (_queryCommand == null)
        {
            _queryCommand = new RelayCommand<TextSelection>(DoWork);
        }
        return _queryCommand;
    }
}

private void DoWork(TextSelection param)
{
    string selectedText = param.Text;

    // Build your control here...
    // probably put it in an ObservableCollection<Control> which is bound by an Items Control, like a ListBox
}

Note: I have used the RelayCommand from Josh Smith's excellent MVVM Foundation, but you could equally use a RoutedUICommand for example (which would add the extra benefit of letting you associate input gestures to your command)

A: You'll need to write some code that takes your selection and wraps it in an InlineUIContainer - that's how you get controls inside a rich text box:
<RichTextBox>
    <FlowDocument>
        <Paragraph>
            <Run>Fo</Run>
            <InlineUIContainer>
                <Button IsEnabled="True">oB</Button>
            </InlineUIContainer>
            <Run>ar</Run>
        </Paragraph>
    </FlowDocument>
</RichTextBox>


text:
Q: use mmap in C to write into memory. I want to use mmap() to create a file containing some integers. I want to write to this file by writing to memory. I know that the data in memory is binary format and hence the data in file will also be in binary.
Can I use mmap for this purpose? where can I find good resources on how to use mmap? I didn't find a good manual to start with.

A: Ressources -> mmap man 2
Examples :
          Linux's cp by fahmy
 if ((dst = mmap (0, statbuf.st_size, PROT_READ | PROT_WRITE,
   MAP_SHARED, fdout, 0)) == (caddr_t) -1)
   err_sys ("mmap error for output");

 /* this copies the input file to the output file */
 memcpy (dst, src, statbuf.st_size);

And  the mmap wiki example
#include <sys/types.h>
#include <sys/mman.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* Does not work on OS X, as you can't mmap over /dev/zero */
int main(void)
{
        const char str1[] = "string 1";
        const char str2[] = "string 2";
        int parpid = getpid(), childpid;
        int fd = -1;
        char *anon, *zero;

        if ((fd = open("/dev/zero", O_RDWR, 0)) == -1)
                err(1, "open");

        anon = (char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0);
        zero = (char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0);

        if (anon == MAP_FAILED || zero == MAP_FAILED)
                errx(1, "either mmap");

        strcpy(anon, str1);
        strcpy(zero, str1);

        printf("PID %d:\tanonymous %s, zero-backed %s\n", parpid, anon, zero);
        switch ((childpid = fork())) {
        case -1:
                err(1, "fork");
                /* NOTREACHED */
        case 0:
                childpid = getpid();
                printf("PID %d:\tanonymous %s, zero-backed %s\n", childpid, anon, zero);
                sleep(3);

                printf("PID %d:\tanonymous %s, zero-backed %s\n", childpid, anon, zero);
                munmap(anon, 4096);
                munmap(zero, 4096);
                close(fd);
                return (EXIT_SUCCESS);
        }

        sleep(2);
        strcpy(anon, str2);
        strcpy(zero, str2);

        printf("PID %d:\tanonymous %s, zero-backed %s\n", parpid, anon, zero);
        munmap(anon, 4096);
        munmap(zero, 4096);
        close(fd);
        return (EXIT_SUCCESS);
}

Try using both and adapt them for your goal.

A: Here is an example:
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h> /* mmap() is defined in this header */
#include <fcntl.h>
#include <stdio.h>

void err_quit(char *msg)
{
    printf(msg);
    return 0;
}

int main (int argc, char *argv[])
{
 int fdin, fdout;
 char *src, *dst;
 struct stat statbuf;
 int mode = 0x0777;

 if (argc != 3)
   err_quit ("usage: a.out <fromfile> <tofile>");

 /* open the input file */
 if ((fdin = open (argv[1], O_RDONLY)) < 0)
   {printf("can't open %s for reading", argv[1]);
    return 0;
   }

 /* open/create the output file */
 if ((fdout = open (argv[2], O_RDWR | O_CREAT | O_TRUNC, mode )) < 0)//edited here
   {printf ("can't create %s for writing", argv[2]);
    return 0;
   }

 /* find size of input file */
 if (fstat (fdin,&statbuf) < 0)
   {printf ("fstat error");
    return 0;
   }

 /* go to the location corresponding to the last byte */
 if (lseek (fdout, statbuf.st_size - 1, SEEK_SET) == -1)
   {printf ("lseek error");
    return 0;
   }

 /* write a dummy byte at the last location */
 if (write (fdout, "", 1) != 1)
   {printf ("write error");
     return 0;
   }

 /* mmap the input file */
 if ((src = mmap (0, statbuf.st_size, PROT_READ, MAP_SHARED, fdin, 0))
   == (caddr_t) -1)
   {printf ("mmap error for input");
    return 0;
   }

 /* mmap the output file */
 if ((dst = mmap (0, statbuf.st_size, PROT_READ | PROT_WRITE,
   MAP_SHARED, fdout, 0)) == (caddr_t) -1)
   {printf ("mmap error for output");
    return 0;
   }

 /* this copies the input file to the output file */
 memcpy (dst, src, statbuf.st_size);
 return 0;

} /* main */

From Here
Another Linux example
Windows implementation of memory mapping.


text:
Q: Implementing jquery read more & show less for dynamic li tags In my code li tag is generated using php. It is dynamic , some times there may be more than 3 li tags , some times less than 3 li tags . In this case i have to show 'read more' and 'show less' when li tags are more than 3 .
Here i am showing my html and jquery what i tried. Is there any other easy method to implement this .

Samsung Galaxy Note 3 comes with Android  v4.3 Jelly Bean OS.

It has a 1.9 GHz Octa Core Processor and 3 GB RAM.

Samsung Galaxy Note 3 has 5.7 Inches Screen with Full HD Display.

It has a 13 MP Rear Camera and 2 MP Front Camera.

Samsung Galaxy Note 3 has 3G Connectivity.

It has FM Radio.

The Phone is powered by Li-ion 3200 mAh  standard battery with Upto 21 hours Talktime.

here is fiddle : http://jsfiddle.net/b9Qgj/1/

A: You can use below given JS for reference
  $('.media-item').hide();
    $('.media-item').slice(0, 3).show();
    $('.view-less-text').hide();
    var length=$('.media-item').length;
    $("ul li:nth-child(3)").append(" Read More...");
    $('ul li:nth-child('+length+')').append(" Read Less...");
    $('.media').click(function () {
        var $relatedItems = $('.media-item').slice(3);
        if ($('.media-item').hasClass('show')) {
            $relatedItems.hide().removeClass('show');
            $('.view-all-text').show();
            $('.view-less-text').hide();
        }
        else {
            $relatedItems.slideDown('slow').addClass('show');
            $('.view-all-text').hide();
            $('.view-less-text').show();
        }
        return false;
    });

Check Now Demo

A: Your code is working fine.
There is a very small issue.
Just replace this:
$('this').hide();

with this:-
$(this).hide();

A:     jQuery(document).ready(function($){ var a = $(".bul5 li").length;

     if (a > 3)
     {
         $(".bul5 li:nth-child(3)").append(" Read More...");

     }
     for( i = 3; i<a; i++ )
     {
        $(".bul5 li").eq(i).hide();

     }
     $('.bul5 .readMore').click(function(event){

        $('.bul5 .readMore').hide();

        for( i = 3; i<a; i++ )
        {

           $(".bul5 li").eq(i).show();
           $('this').hide();

        }

        $(".bul5 li:nth-child("+i+")").append(" Show Less...");

        $('.bul5 .showless').click(function(event){

          $('.bul5 .showless').hide();

         for( i = 3; i<a; i++ )
         {
           $(this).hide();
            $(".bul5 li").eq(i).hide();
            $('.bul5 .readMore').show();

         }
        });

     });
   });

This is the js with proper read more and showless


text:
Q: Netbeans First Time Compiler Build Error I recently decided to try NetBeans, and upon downloading and linking MinGW was greeted with the following error when trying to compiler a "Hello World" program.
"/C/MinGW/msys/1.0/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/c/Users/David/Documents/NetBeansProjects/Welcome_2'
"/C/MinGW/msys/1.0/bin/make.exe"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW_TDM-Windows/welcome_2.exe
make.exe[2]: Entering directory `/c/Users/David/Documents/NetBeansProjects/Welcome_2'
mkdir -p build/Debug/MinGW_TDM-Windows
make.exe[2]: mkdir: Command not found
make.exe[2]: *** [build/Debug/MinGW_TDM-Windows/welcome.o] Error 127
make.exe[2]: Leaving directory `/c/Users/David/Documents/NetBeansProjects/Welcome_2'
make.exe[1]: *** [.build-conf] Error 2
make.exe[1]: Leaving directory `/c/Users/David/Documents/NetBeansProjects/Welcome_2'
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 1s)

For my options under tools\options\c/c++\Build Tools I have
Base Directory: C:\MinGW32\bin
C Compiler: C:\MinGW32\bin\gcc.exe
C++ Compiler: C:\MinGW32\bin\g++.exe
Assembler: C:\MinGW32\bin\as.exe
Make Command: C:\MinGW\msys\1.0\bin\make.exe
Debugger Command: C:\MinGW32\bin\gdb.exe
It's possible that I could have just linked something wrong, but if it would be easier to reinstall some stuff, then I am open to that as well.

A: Going off of the similarity to this post, shutting down and restarting Netbeans might fix this issue (by updating yourPATH).
Here's hoping it is that easy!


text:
Q: Why is the direct image sheaf a left exact functor and not just exact? This might be a rather stupid question, however, I cannot make sense of what is going wrong.

Let $f:X\to Y$ be a morphism of ringed spaces, and $\mathcal{F,G,H}$ sheaves of abelian groups on $X$. Show that the direct image functor $f_*$ is left exact.

Suppose $0\to\mathcal F\to\mathcal G\to\mathcal H\to 0$ is a short exact sequence of sheaves. In particular, for every $U\subset X$, the sequence $0\to\mathcal F(U)\to\mathcal G(U)\to\mathcal H(U)\to 0$ is short exact.
Consider the sequence $0\to f_* \mathcal F\to f_* \mathcal G\to f_* \mathcal H\to 0$. This is left exact if the sequence $0\to f_* \mathcal F (V)\to f_* \mathcal G(V)\to f_* \mathcal H(V)\to 0$ is left exact for every $V\subset Y$ open. This latter sequence can also be written by definition as $0\to \mathcal F (f^{-1}(V))\to \mathcal G(f^{-1}(V))\to \mathcal H(f^{-1}(V))\to 0$. But since $f^{-1}(V)$ is open in $X$, then the previous sequence is already short exact.
What is wrong in this argument? I think I am missing something big.

A: You will have exactness at the stalks, but in general you do not have exactness at sections over $U$.


text:
Q: OOP & Transactions between objects JAVA i hope somebody can help me with this, i have 2 clases User and Adress
both have addNewUser() and addNewAdress() this methods do a transactions with preparedsatement, but i dont know how to join the objets because when i add a new user i need to add a new adrees with the user id.
class User{
  public boolean addNewUser(){
        Connection con = conecctions.getconnection;

    Statement stmt = null;
    Boolean result = false;

            try {

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);

        PreparedStatement addUser =
           con.prepareStatement(query);
          addUser.setBoolean(1, false);
          addUser.setString(1, "name");

        con.commit();

          ...
          ...
          ...
        Adress newAdress = new Adress("new_user_id", "addres");
      newAdrees.addNewAdress();

  }

i think do that its wrong, how can i implement composition? and use the same commit for both methods. thanks!

A: You don't have to commit the transaction to get the insert id. (There is an answered question on how you can get it here). Then, you need to commit just once the transaction at the end of your unit of work. I would suggest to leave the transaction management outside of this object's scope, and don't commit the transaction in any of these objects (either User or Address). This will limit their scope and the code become cleaner, also the transaction code (commit-rollback-exception handling) will be standalone and reusable.


text:
Q: Next js dynamic folder based routing I am beginner in next js and i am trying to integrate dynamic folder based routing.
For example if we want to create dynamic route we can use [id].js or [slud].js but i want to create routing like,
/pages/[name]/index.js
i tried many ways suggested on blogs and documentation but unable to resolve this
Need help on this part.....
I tried to achieve this by finding slug in index file which works but whenever i redirect to another page that slug is gone but i want to fix that slug on routing while accessing the other pages.
i tried this but getting 404 and getting redirected back to homepage with code