text:
Q: C++ A-star implementation -- determining whether a node is already in the priority queue of open items One step in the A* pathfinding algorithm requires searching the list of open nodes for the node you're currently interacting with, and adding that node to the list if it isn't already there, or updating its value and parent, if it's present but with a higher weight than the current version of the node.
These behaviors aren't supported in the STL priority_queue structure. How should I implement that step?
Updates since this question is getting a lot of views:

*

*std::priority_queue may look like a good choice for this, but it isn't.

*Implementing A* yourself is an enormous confidence-booster, but after you've done it, you should try to switch to using the one provided by boost. I was nervous about installing it when I asked this question, but installation is very easy and won't produce any complications; and A* isn't the only useful functionality that boost provides. (In particular, if you don't use their string-processing functionality, you'll end up writing your own copy of it; I speak from personal experience...)

A: STL priority_queue does not suit for A* implementation. You need a heap structure that supports the increase operation to change the priority of already inserted items. Use Boost.Heap for an implementation of many classical heaps.
EDIT: Boost.Graph library has an implementation of A* search too.

A: If you are limited to STL you could use STL Set and constantly erasing and re-inserting the elements (with new priority).
Set< pair<int,int> > s; // < priority,value >
s.insert( make_pair(0,5) );

// Decrease Key operation //
s.erase( s.find( make_pair(0,5) ) );
s.insert( make_pair(1,5) );

Time complexity is still O(log N) but it will probably take more time for large sets.

A: You can use a plain vector or array to store the elements and then use std::make_heap, std::push_heap, std::pop_heap, std::sort_heap, std::is_heap and std::is_heap_until to manage it.
This allows you to break containment and implement custom operations on a priority queue, without having to implement the standard operations yourself.

A: Here is the solution I used for this if you really want to use std::priority_queue:
When you need to update a node that is already in the priority queue, just insert a new node having the same state and a new cost value and parent into the queue. The most recently updated copy of this node will come off the queue first and be added to your visited set. To deal with the older duplicates, check any node coming off the queue against your visited set before processing it. If it is in the visited set then the lowest-cost path through this node has already been seen, so just ignore it and process the next node.

A: There are three likely solutions to this:

*

*Track the list of nodes currently open independently of the priority queue. Try creating a list of nodes in the same manner you do for closed nodes.

*Create a map of nodes (by coordinate) to open-closed state.

*Install the Boost library, which includes a templated implementation of A* (I think in <graph>).


text: Q: Installed 20.04 in Hyper-V, getting black screen after install SIFT supports only 20.04 LTS so I have to use that but I cannot get past the black screen. I have another VM running the 22.04 version and it comes up fine but not this 20.04 VM for some reason. I attempted to edit the grub settings to remove the squash config but that didn't work. Any ideas I should look at? Yes, I did re-download the ISO and checked it. And removed the VM and reinstalled it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Describing disparities in different levels I am struggling to describe disparities in different levels.
Let's take an example, showing disparities in income between the different regions of UK.

*

*Does the map show country-level disparities or regional level disparities?

*And let's assume an increased variation of income in of the regions of UK. This means an upward trend in inequality in income. Should I call it regional level or citizen level trend?


text:
Q: Best way to store addin settings in Excel addin I am developing an excel addin in Visual Studio. This addin is communicating with WCF service.
I want to give user ability to change WCF server address in Excel addin. So I have a Windows Form and I saving the string as Property.
Now I store server address in:
Properties.Settings.Default.serviceAddress

The server address must:
-be changeable through Excel addin
-server address needs to be stored after Excel is closed
Is there a better way to do it?

A: You could use the Backstage Info tab for storing user specific settings.
How to customize back stage?
here and here
You need to decide where to store the settings, I had Sql server to store user details like these settings and favourite documents. You can store it in a file stored in roaming profile area and read from the file while opening excel.

A: You may consider using an XML based file with your settings where you can read and write changes back. Actually, it is up to you what format is to use - JSON, XML and etc. I think it will solve the points you mnetioned in the post above.

A: Create your own file in Folders like ProgramData or AppData to save settings.
For internal structuring purposes, you can use your defined XML, a DataTable based XML, a DataSet based XML, object Serialization, CSV etc.
Easiest is DataTable based XML. Use methods like WriteXML and ReadXML with Schema Mode


text:
Q: Overwritten session variable I've a problem with session variable in a Coldfusion project running on IIS 6.
If I access the site not behind a proxy everything works fine, but if I login behind a proxy (from client side obviously) it works normally at first, but when a second user login, the first one assumes the second one's identity on page refresh.
It's like the session variable on server is being overwritten on each login.
Could you help me?
This is my code for setting session
<cfquery name="qCheckUser" datasource="#myDataSource#">
    SELECT * FROM users WHERE username = '#username#' and pwd = '#pwd#'
</cfquery>

<cflock scope="session" type="exclusive" timeout="10">
    <cfset session.userID = qCheckUser.userID>
</cflock>

Username and pwd come from a classic login form.
Then I use session.userID to retrieve the userId after the login.


text:
Q: Export data to file I have a function f[x,y,z,i] that returns the solutions {x1,y1,z1} for each step "i".
I would like to use a repeating command  (such as Do[...]) to get the outputs of this function f saved in a file. More specifically, I thought using something like Do[f[x,y,z,i],{i,1,10,1}] combined with Save, but I do not know how to combine these two commands with the interation of "i"


text:
Q: How to Sum only hours using Sumif() from excel I am Calculating Over Time of the employees in time format cell using Microsoft Excel 2007. In my result, its calculated as hh and mm. But I want only Hours and ignore Min.
Eg : I have to get this result of SANIA SARWER 0.18 as 0.0
See the screenshot below.

A: =SUMPRODUCT(Int(24*$B:$B),--($A:$A=D2))

How does it work?
Well, SUMPRODUCT will go through each item and multiply them together (So SUMPRODUCT(A1:A3,B1:B3) is the same as =(A1*B1)+(A2*B2)+(A3*B3)) - now, let's looks at each of the columns we're multiplying.
INT(24*$B:$B) is just Days, converted to Hours, and trim off the decimal part (minutes/seconds) - fairly simple.
--($A:$A=D2) first checks if the value in column A is the same as in D2 and gives TRUE or FALSE.  The -- then converts this into 1 or 0, which we multiply by the hours before adding them all up.

A: Easiest way would be to Round Down the data using ROUND function, and then use SUM function to add the rounding data up.
You can find a simple example below.


text: Q: Proof of Cayley Bacharach Theorem That Doesn't Refer to "Independent Conditions" Could anyone direct me to a proof of the Cayley Bacharach theorem that doesn't use "independent conditions" in place of Hilbert functions? I am trying to prove it algebraically and I am having trouble using that phrase in a way that makes sense to me and seems rigorous. Essentially, where I can find an algebraic proof of Cayley Bacharach that uses Hilbert functions?


text:
Q: To override HOME_BUTTON android I have tried the following ways to Override the HOME Button:-

*

*By using KeyDown method.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    Log.e("Pressed", "" + keyCode);

if (keyCode == KeyEvent.KEYCODE_HOME)
{
    Log.e("HOME_PRESSED", "Ignoring HOME Button.");
    return true;
}
else if (keyCode == KeyEvent.KEYCODE_BACK)
{
    Log.e("BACK_PRESSED", "Ignore back pressing.");
    return true;
}
        return super.onKeyDown(keyCode, event);
}

*By using NewIntent method.
@Override
    protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_MAIN))
{
    Log.e("MAIN_PRESSED", "Ignoring MAIN Button.");
}
}

But I am unable to Override the HOME Button Press Event.
So, as per my knowledge and by Logs I figured out that everytime I press Home button.
It fires ACT-AM_ON_PAUSE_CALLED. (Unaware about it)
I tried to Google this thing to know more about it but nothing relevant found!.
Please help to Override the HOME Button in application.

A: It's generally not recommended to override the Home button of the Android OS. The home button is a "safety" button when things go wrong in an application and you just want to get out of there. It is sort of an "eject" button if you will.
You can Override it to some degree by declaring it in the manifest as an application/action that the user can chose whenever the Home button is hit and set your app as the default option whenever the Home button is pressed. However, this method would ask the user to choose between your app and the default home action and assign a default (otherwise he would have to chose between those two options every time he presses the home button) - which isn't recommended at all (bad user experience).

A: From accepted answer here
you cant override it but you can add some code to onStop() which is called upon home button click

A: That is impossible and it has been prohibited to Override it (security issues). This is handled by the framework and you can't do what you like with it.


text:
Q: InnoDB : Deadlock from one reader and one writer This sort of has me miffed.  One query is doing a select that includes a table that is undergoing a heavy UPDATE, but that update takes under 1/2 a second, and there are no other writers to that table.  So I could see how the reader would "wait" until the update completes but I don't understand why this is considered a "deadlock", where neither the update nor the select can proceed.
Here are some facts :

*

*The table nasd_real has 23,000 rows

*Every 15 seconds, an update happens that updates approx 1500 rows

*This update takes under 1/2 a second, which I know because I can run it from the command line as the data from the source of the update is still there.

*The select is doing an aggregation that joins to nasd_real, the result of that join is inserted int a temp table.

Some settings :
mysql> show global variables like '%tx%';
+---------------+-----------------+
| Variable_name | Value           |
+---------------+-----------------+
| tx_isolation  | REPEATABLE-READ |
+---------------+-----------------+
1 row in set (0.01 sec)

mysql> show global variables like '%autocommit%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| autocommit    | ON    |
+---------------+-------+

I included the output from show engine innodb status\G below.
If anyone has seen this type of problem under similar conditions, I would most interested what you think!
TIA.
Don
------------------------
LATEST DETECTED DEADLOCK
------------------------
120720  6:58:15
*** (1) TRANSACTION:
TRANSACTION 1902337, ACTIVE 0 sec starting index read
mysql tables in use 5, locked 5
LOCK WAIT 24 lock struct(s), heap size 3112, 302 row lock(s)
MySQL thread id 45032, OS thread handle 0x7f87c4720700, query id 76514460     localhost prog Copying to tmp table
insert into t_open_existing
select p.portfolio_id
            , op.position_type_id
            , sum(op.position_size * ifnull(nr.last,today.last))
            , sum(op.position_size
     *(ifnull(nr.last,today.last)-ifnull(nr.prev,today.prev))
                                    * (pt.direction))
from member.portfolio as p
 , today
 , position_types as pt
 , member.open_positions as op
LEFT JOIN nasd_real AS nr
 ON   ( op.symbol_id = nr.symbol_id )

 where p.person_id =  NAME_CONST('p_person_id',1)
    and p.portfolio_type_id =  NAME_CONST('l_portfolio_type_id',1)
 and op.portfolio_id = p.portfolio_id
 and today.symbol_id = op.symbol_id
 and op.load_id <  NAME_CONST('l_today',5177)
 and pt.position_type_id = op.position_type_id
 group by p.portfolio_id, op.position_type_id

*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 409609 n bits 320 index `PRIMARY` of table `    prog`.`nasd_real` trx id 1902337 lock mode S locks rec but not gap waiting
*** (2) TRANSACTION:
TRANSACTION 190232C, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
57 lock struct(s), heap size 14776, 942 row lock(s)
MySQL thread id 42342, OS thread handle 0x7f87c4567700, query id
  76514371     localhost prog Sending data
update  nasd_real,
            stream_last
 set             nasd_real.last_updated = stream_last.last_updated,
            nasd_real.volume = stream_last.volume,
            nasd_real.last = stream_last.last,
            nasd_real.high = stream_last.high,
            nasd_real.low = stream_last.low
where   nasd_real.symbol_id = stream_last.symbol_id

*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 0 page no 409609 n bits 320 index `PRIMARY` of
 table     `prog`.`nasd_real` trx id 190232C lock_mode X locks rec but not gap
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 409604 n bits 320 index `PRIMARY` of
table
`prog`.`nasd_real` trx id 190232C lock_mode X locks rec but not gap waiting
*** WE ROLL BACK TRANSACTION (1)
------------
TRANSACTIONS
------------

A: Due to how MySQL handles replication of INSERT INTO ... SELECT, it will actually do some locking on the rows of the tables involved in the SELECT portion of your query. Here is an older article detailing the issue.
The solution is to use row-based replication and set the transaction level to READ-COMMITTED.
To clarify, the locking of INSERT INTO .. SELECT will happen regardless of if you are using replication at all, it is just part of the internals.


text:
Q: Segments prevent the display of tooltips of markers in R plotly I try to create a plot in R using plotly. This plot consists of several elements, i.e. segments and markers. Segments do not display tooltips and markers do display tooltips.
Each marker is located exactly at the end of a segment which results in the following problem. Marker tooltips are generally displayed, but not in the area where segment tooltips would have been shown (which are suppressed). Hence, the center of the marker does not display a tooltip.
How can I modify my code so that the marker tooltip is displayed in the whole area without that 'blind spot' from the segment?
plotly_4.7.1
R version 3.4.1 (2017-06-30)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.3 LTS
#install.packages("plotly")
library("plotly")

p <- plot_ly()
p <- add_segments(p, x = 1, y = 1, xend = 1, yend = 0,
                  line = list(color = "red", layer="below"),
                  hoverinfo="none"
)
p <- add_markers(p, x = 1, y = 1,
                 marker=list(size = 10, color = "blue", layer="above"),
                 hoverinfo="text", hovertext="here!", hoveron="points+fills"
)
p


text:
Q: How to chain I²C level shifters? How can I chain two level shifters in a multi-master I²C system?
The following picture shows the I²C bus. Due to low-voltage to the masters, the A side (low-voltage side) of the level-shifter needs to be connected to master and the B-side (high-voltage side) is connected to the slaves.
Bus architecture:

With TCA9517 device, we see a swinging or bouncing behavior on the bus, when either master sends a zero to the bus.
Are there alternative I²C level-shifters to solve this problem?

Edit:
It's not required that master 1 can communicated to master 2 or reverse. Both masters are using the slaves at the 3v3 bus.

A: Yes, there is sometimes an alternative to using I2C level shifters.
Since I2C is an open-drain bus, it is (often) possible to connect multiple master and slave devices to the same bus, as long as these rules are followed:

*

*The I2C bus is pulled up to the higher voltage, e.g. 3v3 in your example

*For each master and slave device, verify datasheet Electrical Characteristics table for SCL and SDA, supports the higher voltage (SCL/SDA exceeding the chip's supply voltage.)

*For each master and slave device, verify datasheet Electrical Characteristics table for SCL and SDA, uses compatible logic thresholds (minimum logic high voltage, and maximum logic low voltage)

*Maximum I2C capacitive loading (400pF) is not exceeded and all other I2C specs are met

Proper I2C devices are designed with open-drain structures on their SCL and SDA pins, so there is no direct electrical connection to the chip's supply voltage. What limits the maximum voltage the chip's SCL/SDA can tolerate, is the foundry "process" used by the manufacturer. A chip that normally runs at 3.3V might be manufactured on a process whose Absolute Maximum (permanent damage) rating is 6V. As long as the Absolute Maximum rating is never violated, and there is no internal structure that becomes a random forward-biased PN diode junction when SCL>VDD, then that chip shouldn't need a level translator to interface to the higher voltage I2C bus. (Assuming logic level thresholds and timing are compatible.)
This doesn't apply if the chip has push-pull structures, such as a microcontroller bit-banging I2C on its GPIO pins. Those GPIO pins have internal pull-up transistors present in the output structure, even if not used, so there's a path for SCL>VDD to do harm. In that case the datasheet would restrict the GPIO (SCL) not to exceed chip VDD. I'm not sure whether this applies to your system's FPGA pins, you'll need to investigate. If the manufacturer designed them specifically for I2C, they should be open-drain, but otherwise you may be stuck using at least the one level translator for the FPGA.
Be sure to check the datasheet for the logic thresholds for each chip. Sometimes the logic-high and logic-low thresholds are specified as a % of the chip's supply voltage, and sometimes the thresholds are specified by voltage.
It may still be necessary to use I2C level shifters or digital isolators in cases where the master or slave cannot tolerate the higher bus voltage, or in cases where ground return isolation is needed.


text:
Q: javascript mobile view chrome click not working $(document).off("click", ".switch_cities").on("click", ".switch_cities", function(e) {
        alert('uuuu');
        e.preventDefault();
        var r = $("#from").val(),
            t = $("#to").val();
        ("" != r || "" != t) && ($("#from").val(t), $("#to").val(r))
    })

The above code is used to switch cities in two text boxes
it works in Firefox and chrome but it doesn't work in Various mobile views of chrome

A: In your javascript you use the on then click, technically you are not using click on a mobile phone.
You can try the accepted answer in the following link which has the same problem.
https://stackoverflow.com/a/22015946/2619909

A: Instead of using click, use tap event handlers. Judging by your above snippet you seem to use jQuery. jQuery has awesome event handlers, use this link to see how to utilize jQuery tap events.
Bonus point of using tap is they also seem to work on desktop browsers, as seen in the demo on the above link. Cheers!


text:
Q: How to Print Embed tag html or content? Hi I am using this code for Printing the window content
"


text:
Q: Android Studio Emulator stopped working after installing Windows Subsystem for Android on Windows 11 I have installed Windows Subsystem for Android and I am able to run apps on windows 11 however when I tried to run the emulator I created on Android Studio, it just does not no longer work and Android emulator is not responding.
It was working prior to the install, so I am assuming the cause could be when I installed WSA

A: Try turning on/off the Hyper-V option which you will get in the programs and features tab in control panel.

A: These are the four solution might help you to solve your problem.
This error occurs after installing latest android studio with amd processor.

*

*Turning on/off SVM Mode will solve.

*Install HAXM again

*Turn on/off Hyper-V

*AMD processor most of time shows this type of errors.


text:
Q: Как преобразовать строку с датами в массив из чисел у меня есть строка из БД, вида
var date = '2022-07-28 2022-07-29 2022-07-30'

мне нужно превратить это в
date_array = ['2022-07-28', '2022-07-29', '2022-07-30']

в JavaScript, уже пробовал использовать:
let date_array = +date; // NaN,
let date_array = Number(date); // NaN,
let date_array = JSON.parse("[" + date + "]"); // SyntaxError: Unexpected token . in JSON at position 9 at JSON.parse (<anonymous>),
let date_array = parseInt(date); // выдает только год 2022, не подходит

Помогите пожалуйста, я уже с ума схожу и ничего не понимаю

A:

let date = '2022-07-28 2022-07-29 2022-07-30';
let date_array = date.split(' ');

console.log(date_array);


text:
Q: Refreshing the listview of MainActivity after finishing another activity I have troubles with refreshing my listview adapter after I close another activity. I am making program for delivery notes and my main screen is a list with notes. My problem is that when I add a new note(which I am making in another activity) the new note is note appearing on the list. It appears only after rotation of the screen or refreshing the whole program. Here is my code for the MainActivity:
protected override void OnCreate (Bundle SavedInstanceState)
    {
        base.OnCreate (SavedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        // Get our UI controls from the loaded layout
        Button addButton = FindViewById<Button>(Resource.Id.AddButton);
        // Loading the already saved notes from external file
        objectToSerialize = new ObjectToSerialize();
        serializer = new Serializer ();
        var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
        if (System.IO.File.Exists (path + "outputFile.txt")) {
            deserialize ();
        }
        //Displaying the Notes in a custom made ListView
        objListItem = FindViewById<ListView> (Resource.Id.listView1);
        objListItem.Adapter = new MonoBaseAdapter2 (this, _lstNoteInfo);
        objListItem.FastScrollEnabled = true;

        objListItem.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs e) {
            var itemClicked = new Intent(this,typeof(InfoActivity));
            itemClicked.PutExtra("File name",_lstNoteInfo[e.Position].ImageID);
            itemClicked.PutExtra("Date",_lstNoteInfo[e.Position].Date);
            itemClicked.PutExtra("Type",_lstNoteInfo[e.Position].Type);
            itemClicked.PutExtra("Supplier",_lstNoteInfo[e.Position].Supplier);
            itemClicked.PutExtra("Amount",_lstNoteInfo[e.Position].Amount);
            itemClicked.PutExtra("Info",_lstNoteInfo[e.Position].AddInfo);
            StartActivity (itemClicked);
        };

        addButton.Click += delegate {
            StartActivity (typeof(AddActivity));
        };

    }

I have tried with overriding onResume() and using the invalidate(), notifyDataSetChanged(), refreshDrawableState(); methods, but none of them worked. Maybe I am not using them as I should I don't know .. I would appreciate any ideas! :)

A: For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.
When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.

A: @Override
protected void onResume() {
    super.onResume();
    posts.clear();
    posts.addAll(tempPosts);
    postsAdapter.notifyDataSetChanged();
}

I use this in my project, works like a charm.
Post is my List, and tempPost is list where I save edited post list.

A: Try StartActivityForResult instead, then you can @Override the onActivityResult method and do some stuff there (like notifyDataSetChanged() or adding your new row)


text:
Q: pyspark connection to MariaDB fails with ClassNotFoundException I'm trying to retrieve data from MariaDB with pyspark.
I created spark_session with configuration to include jdbc jar file, but couldn't solve problem. Current code to create session looks like below.

path = "hdfs://nameservice1/user/PATH/TO/JDBC/mariadb-java-client-2.7.1.jar"
# or path = "/home/PATH/TO/JDBC/mariadb-java-client-2.7.1.jar"

spark = SparkSession.config("spark.jars", path)\
        .config("spark.driver.extraClassPath", path)\
        .config("spark.executor.extraClassPath", path)\
        .enableHiveSupport()
        .getOrCreate()

Note that I've tried every case of configuration I know
(Check Permission, change directory both hdfs or local, add or remove configuration ...)
And then, code to load data is.
sql = "SOME_SQL_TO_RETRIEVE_DATA"

spark = spark.read.format('jdbc').option('dbtable', sql)
        .option('url', 'jdbc:mariadb://{host}:{port}/{db}')\
        .option("user", SOME_USER)
        .option("password", SOME_PASSWORD)
        .option("driver", 'org.mariadb.jdbc.Driver')
        .load()

But it fails with java.lang.ClassNotFoundException: org.mariadb.jdbc.Driver
When I tried this with spark-submit, I saw log message.
... INFO SparkContext: Added Jar /PATH/TO/JDBC/mariadb-java-client-2.7.1.jar at spark://SOME_PATH/jars/mariadb-java-client-2.7.1.jar with timestamp SOME_TIMESTAMP

What is wrong?

A: For anyone who suffers from same problem.
I figured out. Spark Document says that

Note: In client mode, this config must not be set through the SparkConf directly in your application, because the driver JVM has already started at that point. Instead, please set this through the --driver-class-path command line option or in your default properties file.

So instead setting configuration on python code, I added arguments on spark-submit following this document.
spark-submit {other arguments ...} \
--driver-class-path PATH/TO/JDBC/my-jdbc.jar \
--jars PATH/TO/JDBC/my-jdbc.jar \
MY_PYTHON_SCRIPT.py


text:
Q: Regular expression to not to match two same character in the sequence I know this is very simple for you guys, but i'm scratching my head to find the regular expression to match below strings. Have tried different reg ex, but failed every time. Below are the string that needs to be matched/unmatched.
S__ATHEESH – not match
S_A_T_HEESH – match
S'_ATHEESH – match
S''ATHEESH – not match
S-A_THEESH - match

and here is the requirement
a.       A name can have the special characters – space, apostrophe, underscore and hyphen.
b.      There can be more than 1 special character in a name, but same special character cannot repeat more than once continuously.
c.       There should be minimum 2 characters entered in the name field

I have below reg ex, that needs to be modified
^([a-zA-Z]+[ _'-])*[a-zA-Z]+$

Thanks for your help.

A: The following regular expression will meet your requirements:
^(?=.{2})(?:[a-zA-Z]+|([ _''-])(?!\1))+$

*

*^ assert position at the beginning of the string

*(?=.{2}) at least 2 characters

*and (:

*

*[a-zA-Z]+ at least one alphabetic character

*or:

*

*([ _''-]) a space, underscore, magic apostrophe, apostrophe or dash, captured in capture group 1

*(?!\1) negative lookahead that what was just captured isn't also the next character

*)+ as many times as possible

*$ assert position at the end of the string

Demo

A: You can use a lookahead based solution like
/^(?!.*([-_ '])\1)(?=(?:[^a-z]*[a-z]){2})[-_ 'a-z]+$/i

*

*(?!.*([-_ '])\1) checks, that there is no doubled special character

*(?=(?:[^a-z]*[a-z]){2}) checks the presence of at least two letters

*^[-_ 'a-z]+$ matches, if only the allowed characters are present

I used case-insenstive modifier to avoid writing a-zA-Z all the time.
I'm not sure ' is the correct hyphen character, but it's the one you used.
Here's a demo: https://regex101.com/r/fD1gV0/1

A: Correct me if I'm wrong, but your requirement is simply for strings which do not contains 2 spaces (or apostrophes, underscores or hyphens) one after the other.
In RegEx land, AFAICT, it's not straightforward to assert a "not", but the requirement seems simple enough to be treated in reverse:
(  |__|''|'')

will match what you mark as "not match", so you just have to negate the boolean match result.
Good luck.
Edit: just to make sure I'm not misunderstood. I'm not saying you cannot do exactly what the op is asking, I'm just saying that negating the requirement is a lot simpler and easier to maintain by someone else.


text:
Q: Yet another "ssh agent forwarding not working" I can ssh from hostA to hostB and from hostA to hostC using keys loaded into ssh-agent without any problems.  However, if I do ssh -A hostB from hostA, then try ssh hostC from hostB, public key authentication doesn't work and it asks for my password.
Some details:

*

*I am using ssh-agent that comes with OpenSSH, not GNOME Keyring or anything like that.

*Both ssh -v hostB from hostA and ssh -v hostC from hostA show:
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/rhansen/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: Authentication succeeded (publickey).

*I see my key when I run ssh-add -L on hostB.

*My key on hostA is protected with a password.

*On hostB, /etc/ssh/sshd_config does NOT contain AllowAgentForwarding no.

*All three systems run Ubuntu 15.10 (Wily) with OpenSSH 6.6.1p1.

*When I run ssh -vvv hostC from hostB, the following is logged:
...
debug2: key: /home/rhansen/.ssh/id_rsa ((nil)),
debug2: key: /home/rhansen/.ssh/id_dsa ((nil)),
debug2: key: /home/rhansen/.ssh/id_ecdsa ((nil)),
debug2: key: /home/rhansen/.ssh/id_ed25519 ((nil)),
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/rhansen/.ssh/id_rsa
debug3: no such identity: /home/rhansen/.ssh/id_rsa: No such file or directory
debug1: Trying private key: /home/rhansen/.ssh/id_dsa
debug3: no such identity: /home/rhansen/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/rhansen/.ssh/id_ecdsa
debug3: no such identity: /home/rhansen/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/rhansen/.ssh/id_ed25519
debug3: no such identity: /home/rhansen/.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password

*If I do ssh -vvv hostB from hostA, then do ssh hostC, the following is logged by hostA just before the hostC password prompt:
debug1: client_input_channel_open: ctype auth-agent@openssh.com rchan 2 win 65536 max 16384
debug2: fd 10 setting O_NONBLOCK
debug3: fd 10 is O_NONBLOCK
debug1: channel 2: new [authentication agent connection]
debug1: confirm auth-agent@openssh.com

*My ~/.ssh/config on all systems contains the following uncommon settings (plus some common ones that I don't think are relevant):
ControlMaster auto
ProxyCommand sh ~/.ssh/proxy.sh '%h' '%p' '%r'
IdentitiesOnly yes

Any ideas?

A: It turns out the culprit was the following line in my ~/.ssh/config:
IdentitiesOnly yes

I had added that a while back when I was experimenting with lots of keys that were causing "too many attempts" rejections.  I forgot about it when I finished experimenting so I never removed it.  (It had never caused any problems until I started using agent forwarding.)

A: I am glad to see that you were able to fix the issue on your own.
Your issue was different from the one I was having, but I will add the one I was having just in case someone comes across this post with the one I had.
In my case, the issue was that my home directory had permissions of 775, which ssh does not allow. Not only does the .ssh/ directory need to be 700, and the authorized_keys need to 600, but the home directory itself has to be 755 or below (e.g. 700).


text:
Q: Caused by: java.lang.NoSuchFieldError: com.squareup.okhttp.internal.http.HttpMethod.METHODS when I using retrofit my post request

@POST("/users/login-facebook")
@FormUrlEncoded
void loginFaceboook(@Field("token") String accessToken, @Field("fbId") String facebookId, @Field("platform") int platform,

                    Callback<LoginSignupResponse> callback)

my gradle
   compile 'com.squareup.okhttp:okhttp:2.0.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
 compile 'com.squareup.retrofit:retrofit:1.6.1'

also my all post services have an same error

A: Your dependency versions are ancient and incompatible.
For retrofit 1.x the latest is 1.9.0 and with it you want to use latest okhttp 2.x which is currently 2.7.5.
Consider migrating to retrofit 2.x and okhttp 3.x though.

*

*https://github.com/square/retrofit/releases

*https://github.com/square/okhttp/releases

A: try this,
put this in gradle:
 compile 'com.squareup.retrofit:retrofit:1.6.1'
compile 'com.squareup.okhttp:okhttp:2.0.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0-RC1'
compile 'com.squareup.okio:okio:1.0.0'

@FormUrlEncoded
@POST("/users/login-facebook")
void loginFaceboook(@Field("token") String accessToken, @Field("fbId") String facebookId, @Field("platform") int platform,

                    Callback<LoginSignupResponse> callback)

A: Try below instead
compile 'com.squareup.retrofit:retrofit:1.9.0'
Also, there is no need to put entries for okhttp or okio in gradle.


text:
Q: How to update a schema object, after creation, inside a Joi object? Wasn't sure the best way to phrase the question, but here is an example of what I am trying to do.
const schema = Joi.Object().keys({
   array: Joi.array().length(5)
});

Then after creation I am wanting to update the length method to be a different number.
this.schema.keys({ array: Joi.array().length(8) });

The above code does not work and I'm really just not sure what else to try. (This isn't the only thing I have tried, just where I'm currently at) I've been looking through documentation but haven't found anything helpful for updating a schema. Maybe someone knows of a way to do it?
Any help would be much appreciated!

A: const Joi = require('joi');

////
// update schema itself.
////
let scheme = Joi.object().keys({
  foo: Joi.array().length(5),
});

const a1 = scheme.validate({ foo: [1,2,3,4,5] });
console.log(a1.error); // undefined. valid.

scheme = scheme.keys({
  foo: Joi.array().length(8),
});

const a2 = scheme.validate({ foo: [1,2,3,4,5] });
console.log(a2.error); // array.length error occurred.

const a3 = scheme.validate({ foo: [1,2,3,4,5,6,7,8] });
console.log(a3.error); // undefined. vaild.

////
// using base scheme.
////
const base = Joi.object().keys({
  foo: Joi.array(),
});

const base_a = base.keys({
  foo: Joi.array().length(5),
});
console.log('Using base a1', (base_a.validate({ foo: [1,2,3,4,5]})).error);

const base_b = base.keys({
  foo: Joi.array().length(8),
});
console.log('Using base a2', (base_b.validate({ foo: [1,2,3,4,5]})).error);
console.log('Using base a3', (base_b.validate({ foo: [1,2,3,4,5,6,7,8]})).error);

////
// Not good but works.
////
const obj = Joi.object({
  foo: Joi.array().length(5),
});
console.log('Obj a1', (obj.validate({ foo: [1,2,3,4,5]})).error);

const merged = Object.assign(obj, Joi.object({
  foo: Joi.array().length(8),
}));

console.log('Obj a2', (merged.validate({ foo: [1,2,3,4,5]})).error);
console.log('Obj a3', (merged.validate({ foo: [1,2,3,4,5,6,7,8]})).error);


text:
Q: PHP preg_replace with capture group How can I use preg_replace with a capture group as so?:
preg_replace('/testing\[([0-9]+)\]/', $this->storeNew[**THE NUMBER THAT WAS IN BETWEEN**], $this->code);

A: You should probably use preg_replace_callback with a custom function to achieve that.
You could do it for example this way:
class A {

    private $code = 'testing[82]';

    public function match() {
            return preg_replace_callback('/testing\[([0-9]+)\]/',function($matches) {

         return $this->storeNew($matches[1]);

    }, $this->code);

    }

    private function storeNew($number){
        return ++$number;
    }

}

$a = new A();
echo $a->match();

It gets a bit tricky with $this, so you might need something like (below  @NiettheDarkAbsol code):
$src = $this->storeNew;
preg_replace('/testing\[([0-9]+)\]/', function($n) use ($src) {
    return isset($src[$n[1]]) ? $src[$n[1]] : $n[0];
    // return unchanged if not found in array
},$this->code);

A: I am unsure in which way you would like to make use of the number. If you are just in need of the number itself and nothing else I wouldn't make use of a RegEx, instead use:
filter_var('testing[83]', FILTER_SANITIZE_NUMBER_INT);


text:
Q: Get everything after first character Is it possible to get all strings after a the first character?
var val = 'asdasd:111122:123123123';
var response = val.substring(val.lastIndexOf(":")+1);

alert(response ); // "123123123"
// Would like: ":111122:123123123"

Thank you!

A: Use indexOf(...) instead of lastIndexOf(...)
If you want to include the ":" then do not add one to the index.
Like this:

var val = 'asdasd:111122:123123123';
var response = val.substring(val.indexOf(":"));

alert(response); // ":111122:123123123"

A: var mobileWithCode="+91-9842505145";//mobile value with nation code

mobile = mobileWithCode.substring(mobileWithCode.indexof("-"));

alert(mobile);

A: Just Remove +1 And Go ahead your code will work fine
var response = val.substring(val.lastIndexOf(":"));

alert(response); // Would Become: ":111122:123123123"


text:
Q: Dynamic model filter in Laravel's Eloquent I'm looking for a way to make a dynamic & global model filter in Laravel.
I'm imagining a function like the following in my User.php model:
public function filter() {
    return ($someVariable === true);
}

Whenever I do a query using Eloquent's query builder, I only want users to show up in the collection when the filter above returns true. I would have thought a feature like that existed, but a quick look at the documentation suggests otherwise. Or did I miss it?

A: I believe what you're looking for is Query Scopes.
They are methods that may be defined in a global or local context, that mutate the current query for a given model.
https://laravel.com/docs/5.5/eloquent#query-scopes
For example:
Lets say I have a database table called "Teams" and it has a column on it called "Wins." If I wanted to retrieve all Teams that had a number of Wins between Aand B I could write the following Local scope method on the teams model:
public function scopeWinsBetween($query, int $min, int $max)
{
    return $query->whereBetween('wins', $min, $max);
}

And it could be invoked as such:
$teams = Teams::winsBetween(50, 100)->get();

A: I think you could use Collection macro but you will need to suffix all your eloquent get(); to get()->userDynamicFilter();
Collection::macro('userDynamicFilter', function () {
    //$expected = ...
    return $this->filter(function ($value) use($expected) {
        return $value == $expected;
    });
});

A: Thanks. For now I've simply added a post filter option to the models using the following code:
// Apply a post filter on the model collection
$data = $data->filter(function($modelObject) {
    return (method_exists($modelObject, 'postFilter')) ? $modelObject->postFilter($modelObject) : true;
});

in Illuminate/Database/Eloquent/Builder.php's get() function, after creating the collection. This allows me to add a function postFilter($model) into my model which returns either true or false.
Probably not the cleanest solution but a working one for now.


text:
Q: .net linq with regex ismatch in where In the following C# method, I know that the Directory.GetFileNsmes() does return the list of files. And, I can add in the Where contains(contact) which works. However for the life of me I can not determine why the searchPatter.IsMatch() fails to find files. I've tested the pattern in http://regexpal.com/ and it qorks as expected. The namePattern is "^\d{3}(.*).pdf" and there should be a match.
 public static List<string> GetFileNames(string pathName, string namePattern, string contact)
 {
   var searchPattern = new Regex(namePattern, RegexOptions.IgnoreCase);
   var files = Directory.GetFiles(pathName).Where(f => searchPattern.IsMatch(f));
       //.Where(f => f.Contains(contact));
   return files.ToList();
 }

If this is already answered somewhere please let me know but I've not been able to locate it. I thought this it was pretty simple and straight forward.

A: Directory.GetFiles will return fill file path which will be Drive\Directory\File.ext. That's why your pattern doesn't seem to match. You need FileName alone as subject. Try this
var files = Directory.GetFiles(pathName)
                 .Where(f => searchPattern.IsMatch(Path.GetFileName(f)));

A: Directory.GetFiles() returns a list of filenames appended to the path supplied as a parameter. Your regular expression is "^\d{3}(.*).pdf", that is a string beginning with three digits. If you supplied a string that's  an absolute path, it will start with either "/" on Unix or "C:\" on Windows and if it's a relative path, it will start with a directory name. Your code would work if pathName was just an empty string and you were searching the current directory.


text:
Q: How to define the order of fields on foreign key mapping using Hibernate and JPA? I'm having some problems when hibernate is deploying my application.
I see some errors on the log that say hibernate can't update tables because found foreign keys violations, like this:
Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "order" violates foreign key constraint "fk1w50d63tw42cwgrb7pjn11crs"
  Detail: Key (id_office_o, id_period)=(2, 1) is not present in table "office".

But on my table definition i have the FK fk_order_office_o as a (id_period, id_office_o) relation.
Here is my tables definitions.
CREATE TABLE period (
    id_period INTEGER PRIMARY KEY NOT NULL,
    initial_date TIMESTAMP,
    final_date TIMESTAMP
);

CREATE TABLE office (
    id_period INTEGER NOT NULL,
    id_office INTEGER NOT NULL,
    large_name VARCHAR(50) NOT NULL,
    code_name VARCHAR(2) NOT NULL,
    CONSTRAINT pk_office PRIMARY KEY (id_periodo, id_office),
    CONSTRAINT fk_office_period FOREIGN KEY (id_period) REFERENCES period (id_period)
);
CREATE UNIQUE INDEX uk_office_id_office ON office (id_office);

CREATE TABLE order (
    id_order INTEGER PRIMARY KEY NOT NULL,
    id_period INTEGER,
    id_office_o INTEGER,
    id_office_d INTEGER,
    status INTEGER,
    CONSTRAINT fk_order_office_o
        FOREIGN KEY (id_period, id_office_o)
        REFERENCES office (id_period, id_office)
        MATCH SIMPLE ON UPDATE CASCADE ON DELETE RESTRICT,
    CONSTRAINT fk_order_office_d
        FOREIGN KEY (id_period, id_office_d)
        REFERENCES office (id_period, id_office),
        MATCH SIMPLE ON UPDATE CASCADE ON DELETE RESTRICT,
    CONSTRAINT fk_order_period
        FOREIGN KEY (id_period)
        REFERENCES period (id_period)
        MATCH SIMPLE ON UPDATE CASCADE ON DELETE RESTRICT
);

And these is the data on my tables.
Period.
+------------+--------------+------------+
| id_period  | initial_date | final_date |
|------------|--------------|------------+
| 1          | 2016-01-01   | 2017-12-31 |
+------------+--------------+------------+

Office.
+------------+-----------+------------+-----------+
| id_period  | id_office | large_name | code_name |
|------------|-----------|------------|-----------|
| 1          | 1         | Sales      | SL        |
| 1          | 2         | Billing    | BL        |
| 1          | 3         | Shipments  | SH        |
| 1          | 4         | Returns    | RT        |
+------------+-----------+------------+-----------+

Order.
+------------+-----------+--------------+--------------+-----------+
| id_order   | id_period | id_office_o  | id_office_d  | status    |
+------------+-----------+--------------+--------------+-----------+
| 1          | 1         | 2            | 3            | 1         |
| 2          | 1         | 2            | 3            | 1         |
| 1          | 1         | 3            | 4            | 1         |
| 1          | 1         | 1            | 2            | 1         |
+------------+-----------+--------------+--------------+-----------+

As you can see, the FK of the office table that related with the order table have a CONSTRAINT named fk_order_office_o that use the id_period and id_office, in thats order.
The entity mappings is here:
@Embeddable
public class OfficePK implements Serializable {

    @Column(name = "id_period")
    private Integer idPeriod;

    @Column(name="id_office")
    private Integer idOffice;

    public OfficePK() {
    }

    public OfficePK(Integer idPeriod, Integer idOffice) {
        this.idPeriod = idPeriod;
        this.idOffice = idOffice;
    }

    ...

}

@Entity
@Table(schema="enterprise", name="office")
public class Office {

    @EmbeddedId
    private OfficePK idOffice;

    private String largeName;
    private String codeName;

    public Office() {
    }

    public OfficePK getIdOffice() {
        return this.idOffice;
    }

    public void setIdOffice(OfficePK idOffice) {
        this.idOffice = idOffice;
    }

    ...

}

@Entity
@Table(schema="operation", name = "order")
public class Order {

    @Column(name="id_order")
    private Integer idOrder;

    @ManyToOne
    @JoinColumns(
        value = {
            @JoinColumn(name="id_period",
                        referencedColumnName = "id_period",
                        nullable = false, insertable = false,
                        updatable = false),
            @JoinColumn(name="id_office_o",
                        referencedColumnName = "id_office",
                        nullable = false, insertable = false,
                        updatable = false)
        },
        foreignKey = @ForeignKey(name = "fk_order_office_o")
    )
    private Office officeO;

    @ManyToOne
    @JoinColumns(
        value = {
            @JoinColumn(name="id_period",
                        referencedColumnName = "id_period",
                        nullable = false, insertable = false,
                        updatable = false),
            @JoinColumn(name="id_office_d",
                        referencedColumnName = "id_office",
                        nullable = false, insertable = false,
                        updatable = false)
        },
        foreignKey = @ForeignKey(name = "fk_order_office_d")
    )
    private Office officeD;

    public Order() {
    }

    ...

}

When the application is deploying, i see some errors that call my atention:

*

*I don't define the foreign key in the order thats show on log file, the log file are looking the pair for (id_office_o, id_period), but the foreign key was defined as (id_period, id_office_o) in the table and in the mapping.

*I'm setting the name of the foreign key, but hibernate are setting a random name like fk1w50d63tw42cwgrb7pjn11crs
How can define the order of the fields on the foreign key mapping of the entities?, it is possible?.. or how should define or mapping the fields for the foreign key?
I'm using

*

*Hibernate 5.2.6.Final

*Spring-JPA 1.10.6.RELEASE

Thanks everyone.

A: The part related to the @ForeignKey name might be related to HHH-11180.
The part about the foreign key order, you can solve it by providing a custom org.hibernate.boot.model.naming.ImplicitNamingStrategy implementation, which extends from the default org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl and overrides the determineForeignKeyName method so that it generates the Foreign Key with the columns in the order that you need.
Now, all this effort you're going through is a smell that you're not managing the schema properly. You should never use the automatic HBM2DDL schema generation in production. You should use Flyway instead. That's the root problem in your environment.


text:
Q: vb.net find 4th Wednesday of month with visual basic I am trying to find the fourth Wednesday of the current Month and Year when a form loads
I have converted numerous C# code to Visual Basic with no results
Would someone explain what is wrong with this code OR explain how to accomplish this in VB Code
    Private Sub SurroundingSub()
    Dim thisDate As Date = Today

    tbMonth.Text = thisDate.ToString("MMMM")
    tbYear.Text = thisDate.ToString("yyyy")
    Dim month As Integer
    month = tbMonth.Text
    Dim year As Integer
    year = tbYear.Text
    Dim fourthWed As Date = New Date(year, month, 4)
    tbFour.Text = fourthWed.ToLongDateString

    While fourthWed.DayOfWeek <> DayOfWeek.Wednesday
        fourthWed = fourthWed.AddDays(1)
        tbFour.Text = fourthWed.ToShortDateString
    End While

End Sub

This is a JavaFX statement that I am trying to implement in VB.Net
if(TorF.equals("F") && today.isAfter(fourthTUEofMONTH))

This sets the date
    public void setDATES() throws IOException, SQLException{
    today = LocalDate.now();
    fourthTUEofMONTH = LocalDate.now();
    fourthTUEofMONTH = fourthTUEofMONTH.with(TemporalAdjusters.dayOfWeekInMonth(4, DayOfWeek.TUESDAY));
    endMONTH = LocalDate.now();
    endMONTH = endMONTH.with(TemporalAdjusters.lastDayOfMonth());
}

A: For a more general solution, with my function you can easily find the first, second, third, forth or fifth sunday, monday, tuesday, wednesday or whatever you want:
Public Function GetXDayOfWeek(Day As DateTime,
                              DayOfWeek As DayOfWeek,
                              Optional Index As Integer = 1) As DateTime
    Dim First As New Date(Day.Year, Day.Month, 1)
    Dim Diff As Integer = (DayOfWeek - First.DayOfWeek + 7) Mod 7

    Return First.AddDays(Diff + (Index - 1) * 7)
End Function

So if you want to find the forth wednesday of the current month, use it like:
Dim DateToFind As DateTime = GetXDayOfWeek(Today, DayOfWeek.Wednesday, 4)

A: Your while statement will stop on the first Wednesday it finds, not the fourth.  Keep track of the number of Wednesdays you encounter as you iterate and once you find the fourth then you can update tbFour.
Also as mentioned in the comments you'll want to start at the first day of the year.
Dim fourthWed As Date = New Date(year, month, 1)

Dim wednesdayCursor As Integer = 0

While wednesdayCursor < 4

    If fourthWed.DayOfWeek = DayOfWeek.Wednesday Then

        wednesdayCursor += 1

    End If

    fourthWed = fourthWed.AddDays(1)

End While

'Subtract one day because we added one on loop:
fbFour.Text = fourthWed.AddDays(-1).ToShortDateString()

A: You should make the function of getting the fourth Wednesday into a separate method, perhaps generalizing it for any day of the week, but just for the fourth Wednesday...
Module Module1

    Function FourthWedOfMonth(dt As DateTime) As Integer
        Dim currDate = New DateTime(dt.Year, dt.Month, 1)
        Dim nWednesdays = 0

        While nWednesdays < 4
            If currDate.DayOfWeek = DayOfWeek.Wednesday Then
                nWednesdays += 1
            End If
            currDate = currDate.AddDays(1)
        End While

        Return currDate.Day - 1

    End Function

    Sub Main()
        For mo = 1 To 12
            Console.Write(FourthWedOfMonth(New DateTime(2020, mo, 17)) & " ")
        Next

        Console.ReadLine()

    End Sub

End Module

Outputs the correct days for 2020:

22 26 25 22 27 24 22 26 23 28 25 23

If you wanted the DateTime of the fourth Wednesday, you could
Function FourthWedOfMonth(dt As DateTime) As DateTime
    Dim currDate = New DateTime(dt.Year, dt.Month, 1)
    Dim nWednesdays = 0

    While nWednesdays < 4
        If currDate.DayOfWeek = DayOfWeek.Wednesday Then
            nWednesdays += 1
        End If
        currDate = currDate.AddDays(1)
    End While

    Return New DateTime(dt.Year, dt.Month, currDate.Day - 1)

End Function

and then Console.WriteLine(FourthWedOfMonth(DateTime.Today).ToString("dd-MMM-yyyy")) would output "22-Jul-2020" (at the time of writing).

A: I'd find the fourth Wednesday of the current month this way:
Private Sub FourthWednesdayOfCurrentMonth()
    Dim firstOfMonth As DateTime = DateTime.Today.AddDays(-1 * (DateTime.Today.Day - 1))
    Dim firstWednesday As DateTime = firstOfMonth.AddDays((7 + (DayOfWeek.Wednesday - firstOfMonth.DayOfWeek)) Mod 7)
    Dim fourthWednesday As DateTime = firstWednesday.AddDays(21)

    tbYear.Text = fourthWednesday.Year
    tbMonth.Text = fourthWednesday.Month
    tbFour.Text = fourthWednesday.Day
End Sub

Written generically for any day of the week, that would change to:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim fourthWednesday As DateTime = FourthWeekDayOfCurrentMonth(DayOfWeek.Wednesday)
    tbYear.Text = fourthWednesday.Year
    tbMonth.Text = fourthWednesday.Month
    tbFour.Text = fourthWednesday.Day
End Sub

Private Function FourthWeekDayOfCurrentMonth(ByVal WeekDay As DayOfWeek) As DateTime
    Dim firstOfMonth As DateTime = DateTime.Today.AddDays(-1 * (DateTime.Today.Day - 1))
    Dim firstWeekday As DateTime = firstOfMonth.AddDays((7 + (WeekDay - firstOfMonth.DayOfWeek)) Mod 7)
    Return firstWeekday.AddDays(21)
End Function


text:
Q: Invalid API Token I am pretty new to CORS. I am building a React App which simply posts data to a backend API. According to the API documentation I have to send a BASIC Authentication Header along with the request which is exactly what I am doing. The request works just fine when I send it through POSTMAN. But when I make the same request from my APP it says Invalid API Key. Below is my code:
App.js:
import React from 'react';

class App extends React.Component{

    state = {
        data: 'data'
    };

    handleClick = async () =>{
        const res = await fetch('https://myapi.com/post',{
             method: 'POST',
             body: JSON.stringify({tp:'0'}),
             mode: 'cors',
             headers: {
                 content-type:'application/x-www-form-urlencoded',
                 Authorization : 'Basic ' + new Buffer('username:password').toString(base64)
             }
        });
        const data = await res.json();
        this.setState({data});
    }

    render() {
        return(

{this.state.data}

                 <button onClick={this.handleClick}>Post</button>

        );
    }
}

I looked into the issue and found out that the headers are not being set when sending the request. When further digging into it I found out that the above request is not a simple request and hence the browser makes a preflight OPTIONS request to server. I do not know how the server is handling the requests but I think the server is not configured to handle the preflight OPTIONS. I might be wrong. I do not have any access to the server code. The same request through CORS Anywhere proxy and POSTMAN client is working fine but not while using the actual app. I used create-react-app to setup the boilerplate.
All I get is an Invalid API Token Error while sending request through the app.
Any help on how to get the headers through to the server would be appreciated.

A: According to another post, you might want to wrap the Authorization header in a Headers-object. I guess you should not really pay attention to the OPTIONS-request, that request shouldn't contain any user credentials and the server shouldn't really look for any credentials on a OPTIONS-request, more info.
What happens if you make the following changes (don't forget to npm install base-64).
import React from 'react';
const base64 = require('base-64');

class App extends React.Component{

    state = {
        data: 'data'
    };

    handleClick = async () => {
        const headers = new Headers();
        headers.append("Authorization", "Basic " + base64.encode("user:password"));

        const res = await fetch('https://myapi.com/post',{
             method: 'POST',
             body: JSON.stringify({tp:'0'}),
             mode: 'cors',
             headers: headers
        });
        const data = await res.json();
        this.setState({data});
    }

    render() {
        return(

{this.state.data}

                 <button onClick={this.handleClick}>Post</button>

        );
    }
}


text:
Q: Time formats for NSDate I have datetime values coming into my app from a web service. The format is as follows:
2013-03-24T09:45:00.000-04:00
I need only the time from this value. I am using NSDateFormatter and am setting the date format as follows:
[df setDateFormat:@"HH:mm:ss"];

and when I do this I get a rather cryptic runtime error. However, I have no errors when I use the following (though it doesn't satisfy my requirement):
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.sssz"];

Can someone help?

A: Try this
NSString *originalDateString = @"2013-03-24T09:45:00.000-04:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.sssz"];
NSDate *date  = [dateFormatter dateFromString:originalDateString];

[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *newDateString = [dateFormatter stringFromDate:date];

A: Maybe if you use date formater to retrieve a NSDate instance and from there do you own formating.
NSSTring *dateString = "2013-03-24T09:45:00.000-04:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *dateFromWebApp = [dateFormatter dateFromString:dateString];

Haven't tested tho but it should work.
Cheers


text:
Q: How to create thumbnail for first pdf page with carrierwave I'm processing thumbnail for PDF file in this way:
  version :thumb do
    process :resize_to_limit => [260, 192]
    process :convert => :jpg
    process :set_content_type
  end

  def set_content_type(*args)
    self.file.instance_variable_set(:@content_type, "image/jpeg")
  end

But when PDF file is multipage it produces thumbnail for all pages in one jpg file.
Is there any way to produce thumbnail only for first page?

A: Great solution by Tanzeeb! Thank you.
So i could do something like this:
 def cover
    manipulate! do |frame, index|
      frame if index.zero?
    end
  end

and used this for the thumb generation
  version :thumb do
    process :cover
    process :resize_to_fill => [50, 50, Magick::NorthGravity]
    process :convert => 'png'
  end

great!

A: I ran across this post when searching for a solution to this same problem.  When you convert a pdf to jpeg it creates a long pdf with all the pages attached end to end, so you need to crop the image to the aspect ratio that you want and discard the rest.  Below is what I ended up using:
version :thumb_safari do #special version for safari and ios
  process :resize_to_fit => [200,200]
  process :convert => 'jpg'
  process :paper_shape
  def full_filename (for_file = model.logo.file)
     super.chomp(File.extname(super)) + '.jpg'
  end
end

version :thumb do #all browsers except safari
  process :resize_to_fit => [200,200]
  process :convert => 'jpg' #must convert to jpg before running paper shape
  process :paper_shape
  process :convert => 'jpg' #after running paper_shape it will default to original file type
  def full_filename (for_file = model.logo.file)
    super.chomp(File.extname(super)) + '.jpg'
  end
end

def paper_shape
   manipulate! do |img|
     if img.rows*4 != img.columns*3
       width=img.columns
       height=img.columns/3*4
       img.crop!(0,0,width,height,true)
     else
       img
     end
   end
 end

In the controller/view I used the useragent gem and did this:
documents_controller.rb
def index
  @user_agent=UserAgent.parse(request.user_agent)
  @search = Document.search(params[:q])
end

index.html.rb
<% if @user_agent.browser.downcase == 'safari' %>
<%= link_to(image_tag(doc.pdfdoc_url(:thumb_safari).to_s, :class=>"dropshadow", :size => "150x225"), doc.pdfdoc_url)%>
<% else %>
<%= link_to(image_tag(doc.pdfdoc_url(:thumb).to_s, :class=>"dropshadow", :size => "150x225"), doc.pdfdoc_url)%>
<% end %>

No doubt there is a better way to do this but this is working for now.

A: I submitted a patch earlier this year to do just this. Use a custom processor:
def cover
  manipulate! do |frame, index|
    frame if index.zero?
  end
end

process :cover


text:
Q: How write an efficient overload function of __dict__? I want to implement a to_dict function that behaves similarly to the built-in __dict__ attribute but allows me to have custom logic. (It is used for construct a pandas DataFrame. See the example below. )
However I find out that my to_dict function is ~25% slower than __dict__
 even when they do exactly the same thing. How can I improve my code?
class Foo:
    def __init__(self, a,b,c,d):
        self.a = a
        self.b = b
        self.c = c
        self.d = d

    def to_dict(self):
        return {
            'a':self.a,
            'b':self.b,
            'c':self.c,
            'd':self.d,
        }

list_test = [Foo(i,i,i,i)for i in range(100000)]

%%timeit
pd.DataFrame(t.to_dict() for t in list_test)
# Output: 199 ms ± 4.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
pd.DataFrame(t.__dict__ for t in list_test)
# Output: 156 ms ± 948 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

A digress to this question but related to my final goal: what is the most efficient way to construct a pandas DataFrame from a list of custom objects? My current approach is taken from https://stackoverflow.com/a/54975755/1087924

A: __dict__ does not "convert" an object to a dict (unlike __int__, __str__, etc), it's where the object's (writable) attributes are stored.
I think your implementation is reasonably efficient. Consider this simplified example:
import dis

class Foo:
    def __init__(self, a):
        self.a = a
    def to_dict(self):
        return {'a': self.a}

foo = Foo(1)

dis.dis(foo.to_dict)
dis.dis('foo.__dict__')

We can see that Python looks up the attributes and creates a new dict every time (plus you'd need to make a call to .to_dict, not shown here):
  7           0 LOAD_CONST               1 ('a')
              2 LOAD_FAST                0 (self)
              4 LOAD_ATTR                0 (a)
              6 BUILD_MAP                1
              8 RETURN_VALUE

while accessing an existing attribute is much simpler:
  1           0 LOAD_NAME                0 (foo)
              2 LOAD_ATTR                1 (__dict__)
              4 RETURN_VALUE

You could however store your custom representation on the instance, achieving the same exact bytecode as with __dict__, but then you need to update it correctly on all changes to Foo (which will cost some speed and memory). If updates are uncommon in your use-case, this could be an acceptable trade-off.
In your example, a simple option is to override __getattribute__, but I'm guessing Foo has other attributes, so having setters is probably going to be more convenient:
class Foo:
    def __init__(self, a):
        self.dict = {}
        self.a = a

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value
        self.dict['a'] = value

foo = Foo(1)
print(foo.dict)  # {'a': 1}
foo.a = 10
print(foo.dict)  # {'a': 10}


text:
Q: NativeProcess communication giving error I am trying to communicate to a python script through actionscript. it gives me error on line :
var stdOut:ByteArray = process.standardOutput;
from the function shown below :
public function onOutputData(event:ProgressEvent):void
{
    var stdOut:ByteArray = process.standardOutput; //error
    var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable);
    trace("Got: ", data);
}

Error is:

Implicit coercion of a value with static type IDataInput to a possibly
  unrelated type ByteArray.

I am following the same approach as on Adobe's page. Here is some testable code :
package
{
    import flash.display.Sprite;
    import flash.desktop.NativeProcessStartupInfo;
    import flash.filesystem.File;
    import flash.desktop.NativeProcess;
    import flash.events.ProgressEvent;
    import flash.utils.ByteArray;

    public class InstaUtility extends Sprite
    {
        public var nativeProcessStartupInfo:NativeProcessStartupInfo = new     NativeProcessStartupInfo();
        public var file:File = new File("C:/Python27/python.exe");
        public var process:NativeProcess = new NativeProcess();
        public function InstaUtility()
        {
            nativeProcessStartupInfo.executable = file;
            nativeProcessStartupInfo.workingDirectory =     File.applicationDirectory.resolvePath(".");
            trace("Location " + File.applicationDirectory.resolvePath(".").nativePath);
            var processArgs:Vector.<String> = new Vector.<String>();
            processArgs[0] = "test.py";
            nativeProcessStartupInfo.arguments = processArgs;
            var process:NativeProcess = new NativeProcess();
            process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
            process.start(nativeProcessStartupInfo);
        }
        public function onOutputData(event:ProgressEvent):void
        {
            var stdOut:ByteArray = process.standardOutput; //error
            var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable);
            trace("Got: ", data);
        }

    }
}

A:
The NativeProcess could not be started. Not supported in current
  profile.

Are you testing in Flash IDE?

*

*Test within IDE : In your AIR Publish Settings make sure you ticked only "extended Desktop" when debugging through IDE. This way you also get traces etc.

*Test after Publish : You must tick both "Desktop" and "extended Desktop" and also tick "Windows Installer (.exe)". Install your App using the generated .exe file (not the .air file).

Implicit coercion of a value with static type IDataInput to a possibly
  unrelated type ByteArray.

var stdOut:ByteArray = process.standardOutput; //error is not how it's done!! Don't make any var each time the progress event fires up. Each firing holds around 32kb or 64kb of bytes only (can't remember), so if the expected result is larger it will continue to fire in multiple chunks... Use and recycle a  single public byteArray to hold all the result data.
Try a setup like below :
//# Declare the public variables
public var stdOut : ByteArray = new ByteArray();
public var data_String : String = "";

Your process also needs a NativeProcessExitEvent.EXIT listener.
process.addEventListener(NativeProcessExitEvent.EXIT, on_Process_Exit );

Before you .start a process, also clear the byteArray ready for new data with stdOut.clear();.
Now your progressEvent can look like this below... (Process puts result data into stdOut bytes).
public function onOutputData (event:ProgressEvent) : void
{
    //var stdOut:ByteArray = process.standardOutput; //error

    //# Progress could fire many times so keep adding data to build the final result
    //# "stdOut.length" will be zero at first but add more data to tail end (ie: length)
    process.standardOutput.readBytes( stdOut, stdOut.length, process.standardOutput.bytesAvailable );

    //# Below should be in a Process "Exit" listener but might work here too
    stdOut.position = 0; //move pointer back before reading bytes
    data_String = stdOut.readUTFBytes( stdOut.length );
    trace("function onOutputData -- Got : "  + data_String );
}

But you really need to add an "onProcessExit" listener and then only check for results when the process itself has completed. (Tracing here is much safer for a guaranteed result).
public function on_Process_Exit (event : NativeProcessExitEvent) : void
{
    trace ("PYTHON Process finished : ############# " )
    stdOut.position = 0; //# move pointer back before reading bytes
    data_String = stdOut.readUTFBytes( stdOut.length );
    trace("PYTHON Process Got : "  + data_String );

}


text:
Q: Click item in listbox and View details in multiline textbox I would like to click on an item in a listbox and display the attributes that were passed into that listbox to a multiline textbox.
Below is the code I have written on form initialisation
public Form1()
    {
        InitializeComponent();
        ReadFromFile.Read("sample.GED");

        foreach (KeyValuePair<int, Individual> kvp in ReadFromFile.individuals)
        {
            listBox2.Items.Add("ID = " + kvp.Value.id + " Name = " + kvp.Value.name.givenName + " " + kvp.Value.name.surname + " DoB = " + kvp.Value.birth.date);
        }

        int testIndividual = 94;

        string genderOut = "";
        if (ReadFromFile.individuals[testIndividual].gender == "M")
        {
            genderOut = "MALE";
        }
        else if (ReadFromFile.individuals[testIndividual].gender == "F")
        {
            genderOut = "FEMALE";
        }

        try
        {
            textBox1.AppendText(
                "Name = " + ReadFromFile.individuals[testIndividual].name.givenName + " "
                + ReadFromFile.individuals[testIndividual].name.surname
                + Environment.NewLine + "Gender = " + genderOut
                + Environment.NewLine + "Birth date = " + ReadFromFile.individuals[testIndividual].birth.date
                + Environment.NewLine + "Birth place = " + ReadFromFile.individuals[testIndividual].birth.place
                + Environment.NewLine + "Death date = " + ReadFromFile.individuals[testIndividual].death.date
                + Environment.NewLine + "Death place = " + ReadFromFile.individuals[testIndividual].death.place);
        }
        catch
        {
            MessageBox.Show("This individual doesnt exist");
        }
    }
}

I would like to add more so I can click on a listbox item and the details for that item will be shown in the textbox
I get the feeling I may have to override the ToString() method or regex it. Im still quite a novice programmer so go easy on me :) THANK YOU

A: You need to handle the SelectedIndexChanged event for your listbox.
One way to do this is to bring up Form1.cs[Design] and select the listbox. In the property grid (Alt+Enter) click the icon that looks like this:

Find the event SelectedIndexChanged and double click it. That will hook up an event handler for you in the auto generated Form1.cs.designer file.
Next, replace the code for your Form1 class with the following:
public partial class Form1 : Form
{
    private Dictionary<int, Individual> _individuals;

    public Form1()
    {
        InitializeComponent();
        ReadFromFile.Read("sample.GED");
        _individuals = ReadFromFile.individuals;

        listBox1.DataSource = _individuals.Select(individual => individual.Value).ToList();
        listBox1.DisplayMember = "name";
        listBox1.ValueMember = "id";
    }

    private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        textBox1.Clear();
        var individual = listBox1.SelectedItem as Individual;
        string genderOut = (individual.Gender == "M") ? "MALE" : "FEMALE";
        var displayText
            = String.Format("Name = {0} {1}\r\n" +
                            "Gender = {2}\r\n" +
                            "Birth date = {3}\r\n" +
                            "Birth place = {4}\r\n" +
                            "Death date = {5}\r\n" +
                            "Death place = {6}"
                            , individual.name.givenName
                            , individual.name.surname
                            , genderOut
                            , individual.birth.date
                            , individual.birth.place
                            , individual.death.date
                            , individual.death.place);
        textBox1.AppendText(displayText);
    }
}

A few notes about some of the things i've changed.

*

*I've moved the code that was setting the textbox value into the SelectedIndexChanged event handler

*I've refactored that code so that it's more readable by using the static String.Format method (all those Environment.NewLine repeats you had were messy).

*I've setup the data for the list box using the DataSource property instead of your foreach loop.

Also, one thing you'll notice with this is that the list items in the listbox will not show the correct text. This is because you appear to be using some custom classes or structs for the name, birth and death of an Individual? To fix this, you need to add a new property to the Individual class like this:
public class Individual
{
    // ... your code
    public string DisplayName
    {
        get { return String.Format("{0} {1}), name.givenName, name.surname; }
    }
    // ... the rest of your code
}

Then you will need to change the line in my code above that looks like this:
listBox1.DisplayMember = "name";

to this:
listBox1.DisplayMember = "DisplayName";

Final note: You should probably be using "Upper Camel Case" for your property names. That means that they start with an upper case letter and then the first letter of each word is also upper case. For example, name.givenName should be Name.GivenName. This is a widely used convention.


text:
Q: Multiprocessing Not Running I've recently switched from my MacBook to my windows PC and my multithreading is no longer running.
8 python processes spin up in task manager but they all use 0% CPU and the ParalellMonteCarlo does not return anything (it just runs eternally). This code worked fine on my MacBook and google colab so I assume it is a problem with windows.
def Sample():
    return 'test'

def _paralell_mc(num_iter):
    pool=mp.Pool(8)
    future_res = [pool.apply_async(Sample, for _ in range(num_iter)]
    res = [f.get() for f in future_res]
    return res

def ParalellMonteCarlo(num_iter=100):
    samples = _paralell_mc(num_iter)
    return samples

(code simplified to demonstrate the problem - this does not terminate)
Thanks in advance!


text:
Q: SSIS - Using the SQL Server Schema Name as a Variable for Queries and Procedure Calls If this is a duplicate question, then please just point me in the right direction.
My employer has asked me to substitute SSIS for a number of custom SQL Server procedures.  The setup is for development and pre-production to be on one SQL Server database separated by the schema name and then production will be a second SQL server database with a separate schema of its own.
DBName              Schema
---------------     -------
OperationsTrials    Sandbox
OperationsTrials    PreProd
OperationsProd      Prod

This means within SSIS, all calls to tables, stored procedures etc will need to have the schema name passed in as a variable somehow.  Is this possible and how would one do that?
For example: I created a project variable called "SchemaName" and assigned it the value "Sandbox". Then created a lookup within a package and tried something like the following:
" SELECT DateKey, Date from ''' + @[$Project::SchemaName] + '''.Dim_Date"

SSIS considers this to be a call to a procedure, (when clearly its not) and therefore fails.
" SELECT DateKey, Date from " + @[$Project::SchemaName] + ".Dim_Date"

also fails due to a syntax error at the "+" sign.
SSIS will be doing all DDL and DML within the SQL Server 2012+ environment with Visual Studio 2017 and SSDT 2017.
My SSIS skills are marginal still, so any detailed suggestions would be greatly appreciated.

A: It sounds like you have a great approach. Create a Project Parameter called SchemaName and put a value in. After this is deployed, you can pass in the schema name via environment variables or by overriding values in the SQL Agent job, but I'm not going to cover that in this answer. You seem to be on the right track for your source query.
Create a variable of type String. Paste the expression your wrote in the expression builder, and evaluate it to make sure it works. Then click OK.

Create a data flow task, and in the task add a data source. In this screenshot, I am using an OLE DB Data Source. Choose a connection manager. For Data access mode, choose "SQL command from variable" and then select the variable that contains the source query you just created.

At this point add your columns and build your data flow like normal.


text:
Q: auto-renewable subscription renew? there I am new to auto-renewable subscriptions.
I have implemented the subscription. My problem is if the user buys the subscription for the first time app will go premium. but in any case, his second payment is not happened because of any reason. how did I know that the payment was not successful and or successful? I followed the WWDC tutorial for in-app purchases. implemented with storekit 2.
func purchase(_ product: Product) async throws -> Transaction? {
        //Begin a purchase.
        let result = try await product.purchase()

        switch result {
        case .success(let verification):
            let transaction = try checkVerified(verification)
            print(transaction)
            print(transaction.expirationDate as Any)

            //Deliver content to the user.
            await updatePurchasedIdentifiers(transaction)

            if !purchasedIdentifiers.isEmpty{
                IAP.premiumEndDate = transaction.expirationDate
            }
            //Always finish a transaction.
            await transaction.finish()

            return transaction
        case .userCancelled, .pending:
            return nil
        default:
            return nil
        }
    }

A: In IAP's apple generate a receipt against each transaction containing a lot of information like a digital signature to validate the purchase, history of transactions including successful and unsuccessful transaction, the current status of the subscription, expiry date, and much more.
You have to validate the receipt by fetching from the Apple server to get all this information. you can check this to know how to fetch receipt data.
for validation, we can go with 2 techniques

*

*On-device validation(validation on the device locally if you're not using server in your app)

*Server-side validation(Recommended)

you can read more about choosing receipt validation technique here.
When you fetch receipt it will give you a receiptData  and you will convert it to base64EncodedString and hit API for receipt.
For SandBox use https://sandbox.itunes.apple.com/verifyReceipt and for production use https://buy.itunes.apple.com/verifyReceipt. pass it two parameters Receipt base64String and App-Specific Shared Secret you can find App-Specific Shared Secret on App store on the top right corner of your in-app purchases list.
You will receive a response containing all information about the subscription.
Check this video of title Engineering Subscriptions from WWDC 2018. This video is really helpful in understanding subscriptions.


text:
Q: Knight's tour using Graph(DFS) Java I'm trying to implement knight's tour using DFS. My board is 5x5 for simplicity.
below is my code
class StackK
   {
   private final int SIZE = 25;
   private int[] st;
   private int top;
// ------------------------------------------------------------
   public boolean isFull()
   {return (top == SIZE-1);}
// ------------------------------------------------------------
   public StackK()           // constructor
      {
  st = new int[SIZE];    // make array
  top = -1;
  }
  public void push(int j)   // put item on stack
      { st[++top] = j; }
// ------------------------------------------------------------
   public int pop()          // take item off stack
  { return st[top--]; }
// ------------------------------------------------------------
   public int peek()         // peek at top of stack
  { return st[top]; }
// ------------------------------------------------------------
   public boolean isEmpty()  // true if nothing on st   ack
      { return (top == -1); }
// ------------------------------------------------------------
   }  // end class StackK
////////////////////////////////////////////////////////////////

class VertexK
   {
   public String label;        // label (e.g. 'A')
   public boolean wasVisited;
   public int lastVisited;
// ------------------------------------------------------------
   public VertexK()   // constructor
      {
      label = "O";
      wasVisited = false;
      lastVisited = 0;
      }
// ------------------------------------------------------------
   }  // end class VertexK
////////////////////////////////////////////////////////////////
class GraphK
   {
   private final int SIZE = 5;
   private final int AREA = 5*5;
   private VertexK vertexList[]; // list of vertices
   private int adjMat[][];      // adjacency matrix
   private int nVerts;          // current number of vertices
   private StackK theStack;

// ------------------------------------------------------------
   public GraphK()               // constructor
      {
      vertexList = new VertexK[AREA];// chess board

  adjMat = new int[AREA][AREA];// adjacency matrix

  nVerts = 0; // number of vertices

  for(int y=0; y<SIZE; y++)      // set adjacency
     for(int x=0; x<SIZE; x++)   //    matrix to 0
        adjMat[x][y] = 0;

  theStack = new StackK(); //initialize stack

  for(int i=0;i<AREA;i++)  // make a chess board
       addVertex();

  for(int i = 0; i < SIZE; i++) // add all possible moves to adjMat
        for(int j = 0; j < SIZE; j++)
            addMoves(i, j);
  }
// ---------------------------------------------------------------
   public void displayBoard(){
   int count =0;
   for(int i=0;i<5;i++){
       for(int j=0;j<5;j++){
           System.out.print(vertexList[(count+j)].label+" ");
       }
       count = count+5;
       System.out.println("");
   }
   System.out.println("----------------------------------------------");
   }
// ---------------------------------------------------------------
   public void addMoves(int i, int j)
    {
    int currentRow = i*SIZE; //row
    int currentCol = j; //col
    int currentVertex = currentRow+currentCol;

    if(i-1>=0){
        if(j-2>=0){
            addEdge(currentVertex,currentVertex-SIZE-2);
        }
        if(j+2<SIZE){
            addEdge(currentVertex,currentVertex-SIZE+2);
        }
    }
    if(i+1<SIZE)
    {
        if(j-2>=0){
            addEdge(currentVertex, currentVertex+SIZE-2);
        }
        if(j+2<SIZE){
            addEdge(currentVertex, currentVertex+SIZE+2);
        }
    }
    if(i-2>=0){
        if(j-1>=0){
            addEdge(currentVertex, currentVertex-(SIZE*2)-1);
        }
        if(j+1<SIZE){
            addEdge(currentVertex,currentVertex-(SIZE*2)+1);
        }

    }
    if(i+2<SIZE){
        if(j-1>=0){
            addEdge(currentVertex,currentVertex+(SIZE*2)-1);
        }
        if(j+1<SIZE){
            addEdge(currentVertex,currentVertex+(SIZE*2)+1);
        }
    }

}

// ------------------------------------------------------------
   public void addVertex()
      {
      vertexList[nVerts++] = new VertexK();
      }
// ------------------------------------------------------------
   public void addEdge(int start, int end)
      {
      adjMat[start][end] = 1;
      }

// ------------------------------------------------------------
   public void dfs()  // depth-first search
   {
   vertexList[0].wasVisited = true;
   vertexList[0].label = "V";
   theStack.push(0);

   while( !theStack.isEmpty() )
  {
  if(theStack.isFull()){
      System.out.println("You Win");
  }
  int last = theStack.peek();
  int v = getNext( theStack.peek() );

  if(v == -1){

     System.out.println("DEAD END HERE");
     theStack.pop();
     vertexList[last].label = "O";
     displayBoard();

  }
  else
     {

     vertexList[v].label = "V";
     displayBoard();
     vertexList[v].lastVisited = last;
     vertexList[v].wasVisited = true;

     theStack.push(v);
     }
  }  // end while

   // stack is empty, so we're done
       }

  // ------------------------------------------------------------
 // returns an unvisited VertexK adj to v
 public int getNext(int v)
   {
   for(int j=0; j<nVerts; j++)
      if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
     return j;
   return -1;
   }  // end getAdjUnvisitedVertexK()
 // ------------------------------------------------------------
     public void displayAdj()
 {
    for(int i=0;i<AREA;i++){
    System.out.print(i+"th row: ");
    for(int k=0;k<AREA;k++)
        System.out.print(adjMat[i][k]);
    System.out.println("");
    }
 }
// ------------------------------------------------------------
   }  // end class GraphK

public class KnightApp
   {
   public static void main(String[] args)
  {
  GraphK k = new GraphK();

  k.displayAdj();
  k.dfs();
  k.displayBoard();

  }  // end main()
   }  // end class DFSApp

My program starts out at index 0 and goes to index 7 as you would notice if you ran the code, this is not the right solution(I also wrote knight's tour recursively to check where I should start to get the right solution). So it's supposed to backtrack all the way to the starting square which is 0,0 and go to index 11 instead it just stops because the while loop is over when theStack is empty. How can I make it still go when it backtracks all the way back to the starting point also how do I mark the visited squares to false again when backtracking. LIFT TJE BAN
thank you in advance.

A: When you find a dead end, you need to make wasVisted of current Vertex to false, remove it from adjacency of its (current's) last vertex and set its(current's) lastVistied to zero:
So now the if condition in method dfs will be:
if (v == -1) {
    System.out.println("DEAD END HERE");
    theStack.pop();
    vertexList[last].label = "O";
    vertexList[last].wasVisited = false;
    adjMat[vertexList[last].lastVisited][last] = 0;
    vertexList[last].lastVisited = 0;
    displayBoard();
}


text:
Q: Live resize of root partition in case of "LUKS on LVM" Having read about the pros and cons of "LUKS on LVM" vs "LVM on LUKS" I came to the conclusion that "LUKS on LVM" does not provide live resize. But why? And is this even true as of todays implementations?
For the context this is what I have in my /etc/crypttab:
decrypted_root  /dev/vg_ubuntu/LV_crypted_root none luks

This is my /etc/fstab:
/dev/mapper/decrypted_root   /   ext4    errors=remount-ro 0       1

Here is what I did:
lvextend -L +10G /dev/vg_ubuntu/LV_crypted_root
cryptsetup resize decrypted_root
resize2fs /dev/mapper/decrypted_root

And now my overall question: What could possibly go wrong with this?


text:
Q: Объясните пож. просто чудеса происходят))) Вопрос по js На скриншоте явно видно, что результат 0.3, т.е все работает как нужно. Но, если вырезаю и вставляю это же условие в this.dasplayValue = ..... , то, при уже выдает NaN, хотя условие тоже.
Подскажите пож. в чем ошибка, и как сделать, чтоб калькулятор работал корректно. Обычные числа считал без остатка, а дробные показывал без знаменитой всем ошибки 0. 3000000000000000004
calc() {
      this.displayValue = eval(Math.floor(this.displayValue * 100) / 100);
      // console.log(eval(Math.floor(this.displayValue * 100) / 100));
    },

Vue.createApp({
  data() {
    return {
      item: ['-', 9, 8, 7, '+', 6, 5, 4, '.', 3, 2, 1, 0, '*', '/'],
      displayValue: '',
    };
  },
  methods: {
    buttonShow(num) {
      this.displayValue += num;
    },
    clear() {
      this.displayValue = '';
    },
    calc() {
      this.displayValue = eval(Math.floor(this.displayValue * 100) / 100);
      // console.log(eval(Math.floor(this.displayValue * 100) / 100));
    },
    back() {
      if (this.displayValue) {
        this.displayValue = this.displayValue.substring(
          0,
          this.displayValue.length - 1
        );
      }
    },
    percent() {
      this.displayValue = this.displayValue / 100;
    },
  },
}).mount('#app');
.grid{
   max-width: 360px;
   margin: 50px auto;
   padding: 20px;
   display: grid;
   grid-gap: 10px;
   grid-template-columns: repeat(4, 1fr);
   background-color: #233244;
   user-select: none;

}

.item {
   padding: 15px;
   border: none;
   color: white;
   font-size: 28px;
   background-color: #31455e;
   cursor: pointer;
   transition: .3s ease-in;
}

.item:hover{
   transform: scale(1.05);
   background-color: turquoise;
}

.input {
   background-color: #31455e;
   grid-column: 1/-1;
   height: 50px;
   outline: none;
   text-align: right;
   padding-right: 10px;
   font-size: 28px;
   color: white;
}

.equally{
   grid-column: 4/-1;
   grid-row: 5/7;
}
<!DOCTYPE html>

   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Calculator</title>
   <link rel="stylesheet" href="style.css">

         <input class="input" type="text" readonly v-bind:value="displayValue">
         <button class="item" @click="clear()">C</button>
         <button class="item back" @click="back()">⇽</button>
         <button class="item" @click="percent()">%</button>
         <button class="item" v-for="i of item" @click="buttonShow(i)">{{i}}</button>
         <button class="item equally" @click="calc()">=</button>

A: Всему виной некорректная проверка.
Так, сначала вычисляется выражение
this.displayValue = eval(this.displayValue);

И лишь затем происходит вывод
console.log(eval(Math.floor(this.displayValue * 100) / 100));

В данном случае this.displayValue - уже число, а не строка, поэтому все отрабатывает корректно.
В случае без console.log
this.displayValue = eval(Math.floor(this.displayValue * 100) / 100);

this.displayValue - это строка, и результат умножения может варьироваться в зависимости от конкретного значения.
Так как, например, строка 0.1+0.2 - не может привестись к числу, результат умножения - NaN.
Для решения, достаточно сначала вычислить выражение и лишь затем округлять
Math.floor(eval(this.displayValue) * 100) / 100

Пример

Vue.createApp({
  data() {
    return {
      item: ['-', 9, 8, 7, '+', 6, 5, 4, '.', 3, 2, 1, 0, '*', '/'],
      displayValue: '',
    };
  },
  methods: {
    buttonShow(num) {
      this.displayValue += num;
    },
    clear() {
      this.displayValue = '';
    },
    calc() {
      this.displayValue = Math.floor(eval(this.displayValue) * 100) / 100;
    },
    back() {
      if (this.displayValue) {
        this.displayValue = this.displayValue.substring(
          0,
          this.displayValue.length - 1
        );
      }
    },
    percent() {
      this.displayValue = this.displayValue / 100;
    },
  },
}).mount('#app');
.grid {
  max-width: 360px;
  margin: 50px auto;
  padding: 20px;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(4, 1fr);
  background-color: #233244;
  user-select: none;
}

.item {
  padding: 15px;
  border: none;
  color: white;
  font-size: 28px;
  background-color: #31455e;
  cursor: pointer;
  transition: .3s ease-in;
}

.item:hover {
  transform: scale(1.05);
  background-color: turquoise;
}

.input {
  background-color: #31455e;
  grid-column: 1/-1;
  height: 50px;
  outline: none;
  text-align: right;
  padding-right: 10px;
  font-size: 28px;
  color: white;
}

.equally {
  grid-column: 4/-1;
  grid-row: 5/7;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>
  <link rel="stylesheet" href="style.css">

      <input class="input" type="text" readonly v-bind:value="displayValue">
      <button class="item" @click="clear()">C</button>
      <button class="item back" @click="back()">⇽</button>
      <button class="item" @click="percent()">%</button>
      <button class="item" v-for="i of item" @click="buttonShow(i)">{{i}}</button>
      <button class="item equally" @click="calc()">=</button>


text:
Q: Test on the difference of reciprocals I am trying to prove that a certain series $\sum a_n$ diverges.
All I know is that the terms are positive, strictly decreasing and tend to zero.
Moreover  the two following limits hold:
$$\lim_{n \rightarrow   \infty} \frac{a_{n+1}}{a_n} = 1$$
$$\lim_{n \rightarrow   \infty} \frac{1}{a_{n+1}}-\frac{1}{a_n}= \frac{1}{3}$$
Is there any standard test that comes to your mind?
I have been wondering if the following is true:
if $\sum a_n$ converges then $\frac{1}{a_{n+1}}-\frac{1}{a_n}$ is unbounded
Not sure if this holds but it would solve the problem as well.
Thank you very much for any hint/suggestion you might have!

A: Hint:  here is a heuristic argument:
Using a telescoping series, $\frac{1}{a_n} - \frac{1}{a_1} \approx \frac{n}{3}$.  Taking reciprocals,
$a_n \approx \frac{3}{n}$, so the series behaves like the harmonic series, which diverges.  You must fill in some missing steps, probably by showing your series is greater than some constant multiple of the harmonic series.
To make this more rigorous, one way would be to use the fact that $\frac{1}{a_{n+1}} - \frac{1}{a_n} < \frac{1}{2}$ for $n \geq N$ (for some $N \in \mathbb{N}^+$), use a telescoping series to bound $1/a_n$ from above, and hence $a_{n}$ from below for large $n$, and compare $a_n$ to some multiple of $1/n$ for large $n$, thereby showing that a "tail" of the series diverges.  A comment below suggests using the Limit Comparison Test.  If you can get this to work, it would probably lead to a cleaner and more elegant solution.
The assumption that the terms in the series are decreasing seems to be unnecessary.
Your idea ("I have been wondering...") is an interesting one.  Doubtless someone will prove it one way or the other soon.
I don't know if any of the "standard tests" work.  Obviously the Ratio Test fails.


text:
Q: Use Native Java UUID.getRandom() as Sharding key and as the _id? I understand that with a write-heavy application, using the ObjectId is a really bad idea for a sharding key. However, would it be a good idea to use native *UUID.randomUUID() from Java as a Shard key since they are truly random and won't cause hotspotting for a single shard.
These IDs are 128 bit ID and look like :

*

*5842fa92557947f1b020041ff74868a4

*308947443e564d80b97dd8411b4b727e

*f8a7ee765bed4ce3bcc5800ac3a2a710

*1bcfd08b89e94c58ae7695b3e7a1bc4f

It's very similar to an ObjectId (96bit int).
Plus, since this is mandatory to have an Index on the _id, the shard key would be the _id and we would save RAM by creating another index for the shard_key. Everything collection would be ready for sharding.
Is it for performances issues within Mongod or for disk/ram space problem?
The collision rate for a UUID is (from wikipedia) :
only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs.

A: Using UUID would distribute your write access across the shards but you would have no query isolation, so you'll have less than optimum results with your queries. The fastest queries are the one answered by only one shard.
http://docs.mongodb.org/manual/core/sharding-internals/#sharding-shard-key-query-isolation
That would help to know what is in your collection to help you more efficiently.

A: Using UUIDs is perfectly ok (provided that you are only going to lookup those documents by their primary/shard key). One of the purposes of shard key is to group related documents together. If we're building, say, flickr, our shard key would start with user_id, so that photos of a user sit together on one shard. If your documents are not related and primary key is also a shard key, then there's no problem.

A: You may run into a problem due to https://jira.mongodb.org/browse/JAVA-403, which is slated to be fixed in the next release.