How to identify potentially unsafe electrical connectors in use?

Question: One can buy inexpensive wago-style connectors that have the CE Marking but I am doubtful that they are really certified:
.
When purchasing such items, I can ask about certifications (the ebay listing does not mention CE certification). However, when encountering these devices in the field, how might one know if it is safe for use?
To be clear: I have encountered these in the wild. The real Wagos mention ENEC 15 certification.
Comment: Wow! So there exist, and you think you have encountered, counterfeit WAGO connectors, presumably made in China or elsewhere in the far east? Do you swap them out when you encounter them? Could these be "first generation" genuine WAGOs that have a slightly different appearance?   What do WAGO say about this?
Comment: CE is **not** a certification. CE means "Cheap Excrement" because *when they lead* with the CE mark, it's because they have no certs at all, because they know that no lab on earth would certify it. UL, CSA, TUV, ETL are testing labs. Heck, I would trust an Edna Mode mark because at least she has a testing lab. It's not a high bar. *(Literally, CE is a promise by the manufacturer that they adhere to certain EU safety rules e.g. use of non-lead RoHS solder, so it's a nothingburger).
Comment: Are there any identifying marks or details of construction that distinguish the suspect connectors from genuine WAGO?
Comment: OK, I see the ad does not describe these as WAGO connectors and states they are from China. Presumably this would be patent infringement.
Answer: Buy from reputable firms
Or to be more precise, don't buy from firms who have workers with apartments in Shenzhen or Hong Kong, because they spend so much time there turning over rocks looking for super cheap suppliers of goods to private-label. That means you can cross off the list:

eBay
Amazon Marketplace, and possibly "sold by and ships from Amazon" as well
Alibaba/AliExpress, obviously
The orange Borg
The blue Borg
The green Borg "11% off"

And we're down to pretty much Grainger, McMaster-Carr, maybe Fastenal though they have some dodgy stuff, and of course, your friendly neighborhood local electrical supply house.
It's the same rule as auto parts.  I buy my auto parts at shops which have a fleet of small pickup trucks because they do 90% of their business out the back door to mechanics.  Why?  Mechanics have to stand behind the work, it's their time, rep and loaner cars at stake.  A high failure rate will put them out of business.  It'll put me at the side of the road, so our goals align.
Oh, but price!!!
Electrical parts have a very low cost to weight ratio, and that makes them expensive to ship.  Another example of such a product is bottled or canned sodas.  For those, the distribution model of "mail order to the consumer" makes no financial sense, it makes sense to distribute bulk materials by truck to local outlets and sell retail.  You see that in prices, like $180 total to ship $105 of wire, or a 75 cent item at the electrical supply costing 75 cents "plus $6 shipping".
"But I have Amazon Prime! Shipping is freeeee!"
There's no free lunch.  You pay for the Amazon Prime shipping one way or the other, and the $99 membership fee is not the way. They overcharge for the item and lowball or zero the shipping.  Now that 75 cent item is $3 -- and if you go check out the fees Amazon charges its Marketplace partners to use Amazon fulfillment,  you quickly see why it's $3.
So to be competitive, there is huge motivation to use counterfeits.  And absolutely nothing prevents a Marketplace seller from selecting a genuine Wago SKU and claiming to have that exact item when it's actually a counterfeit, or right off the Wago assembly line that are either dumpster-dived QA rejects, or stolen good product.
Comment: As I've mentioned before, the "orange Borg" and, though I have less specific experience, the "blue Borg" can be perfectly fine. The main thing is to know what you are buying. You can, as with Amazon (but unlike Amazon, you actually pick up the item yourself so you know it is really "x brand" and not just "sort of like x brand but you won't know until you get it" - and I buy plenty of stuff from Amazon, but I am careful about what I buy). There is junk at "orange" and there is some really good stuff there too - you need to know when it matters/why it matters - and shop wisely.
Comment: As far as Prime - 100% correct. You need to know when it pays - like computer memory I just ordered, got it the next day, no shipping cost (unlike direct from manufacturer) and no long drive to the only local computer store that I trust. And I know enough to get the same **name brand** that I have used & trusted for years instead of the no-name that might be fine...but might not. But there are plenty of things I've looked for on Amazon and **NOT** gotten because it is clear the price is higher to cover the "free shipping". TANSTAAFL
Comment: And last, Harper's advice is not limited to electrical supplies. When it comes to computer parts, there is only one store in my area that I go to myself or send anyone else to. Not exactly the same but they know what they sell (unlike a LOT of big box stores of all types), they support what they sell (which I find "orange" does too, at least credit/replace bad items - but many stores do a poor job of that) and they don't simply sell whatever is "hot" at the moment (unlike certain other big computer stores). **If you don't know what you're buying then buy from someone you trust to guide you.**
Comment: The big-box use a shotgun approach to customer service, they don't care and throw money at you to keep you happy.  Having spent several years in customer service and having iterated on every method, I conclude they are right.
Comment: What's amazing is how some big companies get it "right" and some really, really don't. Actually, not so amazing - the ones that are in near-monopoly industries talk a great game but don't deliver, because they don't **have** to. That being said, I am amazed in the instances where there really is a big difference (in my case, computer stores which I know quite well being in the computer business for > 30 years) the average Joe is clueless and doesn't know when they are being sold "the wrong tool for the job" or (as this conversation started with) total junk.
Comment: Thank you for this very thorough answer. However good, the answer addresses the purchasing process but the question specifically asks about **encountering these devices in the field**.


Blowfish encryption - encrypted in php and java, I got different encrypted values

Question: The encryption test data:
key: 'ABC';
data:'1234567';
algorithm:  MCRYPT_BLOWFISH;
mode: MCRYPT_MODE_ECB;

PHP code
$key  = 'ABC';
$data = '1234567';
$alg  = MCRYPT_BLOWFISH;
$mode = MCRYPT_MODE_ECB;

$encrypted_data = mcrypt_encrypt($alg, $key, $data, $mode);

$phpgeneratedtoken  = base64_encode($encrypted_data);

print "PHP generated token: " . $phpgeneratedtoken."   ";
// return
// In6uDpDqt1g=

// Decode the token just generated by php

$decoded = mcrypt_decrypt($alg,$key,base64_decode("In6uDpDqt1g="),$mode);
print "Decoded from php generated token:" . $decoded."    ";

//return
//1234567

// This is the encrypted token generated by java with same key and value
$javageneratedtoken  = "Cg8qY4gRMaI=";

// Decode the token generated by Java
$decoded = mcrypt_decrypt($alg,$key,base64_decode("Cg8qY4gRMaI="),$mode);
print "Decoded from Java Generated token: " . $decoded."    ";
// return
// 1234567

// Both tokens generated by java and php, are decrypted back to the same value.

Java Code:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class BlowfishTest {

    public static void main(String[] args) throws Exception {
        encrypt("1234567");
        decrypt("In6uDpDqt1g=");
    }

    private static void encrypt(String password) throws Exception {
        byte[] keyData = ("ABC").getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] hasil = cipher.doFinal(password.getBytes());
        System.out.println(new BASE64Encoder().encode(hasil));
    }

    private static void decrypt(String string) throws Exception {
        byte[] keyData = ("ABC").getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
        Cipher cipher = Cipher.getInstance("blowfish/ecb/nopadding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] hasil = cipher.doFinal(new BASE64Decoder().decodeBuffer(string));
        System.out.println(new String(hasil));
    }
}

The PHP generated encrypted value is: In6uDpDqt1g=.
The Java generated encrypted value is: Cg8qY4gRMaI=.
The issue is at Java Code's
Cipher cipher = Cipher.getInstance("blowfish");

I need to find a way to make my PHP generated encrypted value the same as the Java generated encrypted value.
Both encrypted values I can decrypt them back in PHP. Both encrypted values I could decrypt them back in java too, ONLY IF I set,
Cipher cipher = Cipher.getInstance("blowfish/ecb/nopadding");

But when I try to decrypt PHP encrypted value, In6uDpDqt1g=, in Java.
If I set,
Cipher cipher = Cipher.getInstance("blowfish");

I got the error:

"Given final block not properly padded".

The problem is I am supposed to use PHP to encrypt value, and my client would use java to decrypt value. With the setup Cipher cipher = Cipher.getInstance("blowfish") to decrypt my value.
So I want to find a way that I should use PHP to get the same encrypted value as Java, with Cipher cipher = Cipher.getInstance("Blowfish"), would get.
If there is no such solution, then I would have to ask my client to change his java codes to use
Cipher cipher = Cipher.getInstance("blowfish/ecb/nopadding");

Comment: **Never use [ECB mode](http://crypto.stackexchange.com/q/14487/13022)**. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like [CBC](http://crypto.stackexchange.com/q/22260/13022) or [CTR](http://crypto.stackexchange.com/a/2378/13022). It is better to authenticate your ciphertexts so that attacks like a [padding oracle attack](http://crypto.stackexchange.com/q/18185/13022) are not possible. This can be done with authenticated modes like GCM or EAX, or with an [encrypt-then-MAC](http://crypto.stackexchange.com/q/202/13022) scheme.
Comment: Why don't use use `Cipher.getInstance("blowfish/cbc/pkcs5padding")`, transmit the IV and [use proper padding in PHP](http://stackoverflow.com/a/27590539/1816580).
Answer: OK, I find my answer. I need to change my php code to
$key  = 'ABC';
$data = '1234567';
$alg  = MCRYPT_BLOWFISH;
$mode = MCRYPT_MODE_ECB;

$blocksize = mcrypt_get_block_size('blowfish', 'ecb'); // get block size
$pkcs = $blocksize - (strlen($data) % $blocksize); // get pkcs5 pad length
$data.= str_repeat(chr($pkcs), $pkcs);

$encrypted_data = mcrypt_encrypt($alg, $key, $data, $mode);

$phpgeneratedtoken  = base64_encode($encrypted_data);

print "PHP generated token: " . $phpgeneratedtoken."   ";
// return
// Cg8qY4gRMaI=


Logstash: Reading multiline data from optional lines

Question: I have a log file which contains lines which begin with a timestamp. An uncertain number of extra lines might follow each such timestamped line:
SOMETIMESTAMP some data
extra line 1 2
extra line 3 4

The extra lines would provide supplementary information for the timestamped line. I want to extract the 1, 2, 3, and 4 and save them as variables. I can parse the extra lines into variables if I know how many of them there are. For example, if I know there are two extra lines, the grok filter below will work. But what should I do if I don't know, in advance, how many extra lines will exist? Is there some way to parse these lines one-by-one, before applying the multiline filter? That might help.
Also, even if I know I will only have 2 extra lines, is the filter below the best way to access them?
filter {
    multiline {
        pattern => "^%{SOMETIMESTAMP}"
        negate => "true"
        what => "previous"
    }

    if "multiline" in [tags] {
        grok {
            match => { "message" => "(?m)^%{SOMETIMESTAMP} %{DATA:firstline}(?<newline>[\r\n]+)%{DATA:secondline}(?<newline>[\r\n]+)%{DATA:thirdline}$" }
        }
    }
    # After this would be grok filters to process the contents of
    # 'firstline', 'secondline', and 'thirdline'. I would then remove
    # these three temporary fields from the final output.
}

(I separated the lines into separate variables since this allows me to do additional pattern matching on the contents of the lines separately, without having to refer to the entire pattern all over again. For example, based on the contents of the first line, I might want to present branching behavior for the other lines.)
Answer: Why do you need this?
Are you going to be inserting one single event with all of the values or are they really separate events that just need to share the same time stamp?
If they all need to appear in the same event, you'll like need to resort to a ruby filter to separate out the extra lines into fields on the event that you can then further work on.
For example:
if "multiline" in [tags] {
    grok {
        match => { "message" => "(?m)^%{SOMETIMESTAMP} %{DATA:firstline}(?<newline>[\r\n]+)" }
    }
    ruby {
       code => '
         event["lines"] = event["message"].scan(/[^\r\n]+[\r\n]*/);
       '
    }
}

If they are really separate events, you could use the memorize plugin for logstash 1.5 and later.
Comment: edited to add a * instead of a + -- so that the newline at the end is optional
Comment: Having separated the lines into a **lines** array, is there some way to apply a grok filter to each line in that array? So I can get the 1, 2, 3, and 4 from the input data.
Comment: It seems like you should be able to use %{[lines][1]} (see https://groups.google.com/forum/#!topic/logstash-users/mlfMs-2iuVI).  Also you could probably have used split filter instead of a ruby filter
Comment: Nice find... still, is there a way to apply this to an arbitrary number of lines? So, I would be able to run a grok filter on %{[lines][1]} and %{[lines][2]}, etc. -- as many extra lines as I happen to have, since that number is arbitrary.
Comment: You have the full power of ruby in a ruby filter, so you can do just about anything you want. But there is no looping construct in the logstash config language.
Comment: Ah... so the best way to do this would probably be to write a Ruby script to do some simple regex work, then use event[] to create new variables. (Instead of using grok.)
Comment: That's what I would do.
Answer: This has changed over versions of ELK
Direct event field references (i.e. event['field']) have been disabled in favor of using event get and set methods (e.g. event.get('field')).
filter {
    grok {
        match => { "message" => "%{TIMESTAMP_ISO8601:logtime} %{LOGLEVEL:level}%{DATA:firstline}" }
    }
    ruby { code => "event.set('message', event.get('message').scan(/[^\r\n]+[\r\n]*/))" }
}


call anonymous function composable in other component vuejs 3

Question: I´m trying to call anonymous function defined in constant variable in my composable, and i need to call it in my component parent, that this anonimous function will fill my table with any data. I´m trying this:
my composable:
export default function useNcalls(){
    let calls = ref([])
    let param_search = ref([])
    let pagination = ref([])

    const getCall = async (param_search) => {
        let response = await axios.get('/api/callApi', {param_search: {'param_search': param_search} })
        console.log("llego")
        calls.value = response.data.data
    }
    const deleteCall = (id) => axios.post(`/api/callApi/${id}`, {_method: 'delete'}).then(res => {
        confirm("¿Está seguro de que desea eliminar el registro?")
        location.reload();
    }).catch(err => {
        console.log(err);
    });

    const queryForKeywords = async (event) => {
        const response = await axios.get('/api/callApi/show', { params: { 'searchParams': event } })
        calls.value = response.data.data
    };

    const getResults = async (page) => {
        const response = axios.get('api/callApi?page=' + page)
        calls.value = response.data
    };

    const getItems = async (page) => {
        axios.get('/api/callApi?page='+page)
            .then(response => {
                calls.value = response.data.data;
                pagination.value = response.data.meta;
            });
    };

    return{
        calls,
        getCall,
        deleteCall,
        queryForKeywords,
        getResults,
        getItems
    }
}

i have one component that create table and any methods that use this composable:

and i have my component parent, that include before component that i expose:

In my function searchRegisters() i need call getCall sending param_search that this anonymous function call laravel API to get all my data.
always return en my console:
Uncaught TypeError: _roomBooss_nasignedCalls__WEBPACK_IMPORTED_MODULE_3__.default.getCall is not a function
    at Proxy.searchRegisters (app.js:20026:114)
    at onClick._cache.<computed>._cache.<computed> (app.js:21762:21)
    at callWithErrorHandling (app.js:7336:22)
    at callWithAsyncErrorHandling (app.js:7345:21)
    at HTMLInputElement.invoker (app.js:15616:86)

or app.js:7203 [Vue warn]: expose() should be called only once per setup().
thanks for readme and sorry for my bad english
Comment: The question lacks https://stackoverflow.com/help/mcve . There's no getCall in searchRegisters. The error suggests that you tried to do something like nasignedCall.getCall(), this is not how it works. nasignedCall is component i.e. component options. You need to a ref of component instance
Comment: @EstusFlask thanks for your response and sorry for my bad question... How i can solve my problem? define a ref¿?
Comment: Specifically, template ref https://vuejs.org/guide/essentials/template-refs.html . There should be childRef.value.getCall() in searchRegisters, no expose() there.  If this still doesn't work, please, update the question with relevant details.
Answer: I think what you are trying to do is to use the composable in your child component, and then use template refs to pass the result around. IMO it does not make sense to use a composable that way, and I would try to avoid using template refs in general.
Looking at your code, the issue seems to be that the functions from the composable change the calls ref, and you have to make sure that both parent and child component use functions that alter the same calls ref. A way to do this is to use provide/inject inside the composable. Then you can setup the provide in the parent component, and inject the ref into any component that needs it.
You code doesn't even need to change much. This is what the composable could look like:
import { provide, inject } from 'vue'

const callsSymbol = Symbol.for('calls-api-variable') // <---- create a symbol for the injection

export function createCallsApi(){
  const calls = ref([])
  const pagination = ref([])

  const getCall = async (param_search) => {...}
  const deleteCall = (id) => ...
  const queryForKeywords = async (event) => {...};
  const getResults = async (page) => {...};
  const getItems = async (page) => {...};

  const callsApi = {
    calls,
    getCall,
    deleteCall,
    queryForKeywords,
    getResults,
    getItems
  }

  provide(callsSymbol, callsApi) // <----- add a provide
  return callsApi
}

export function useCallsApi(){ // <---- composable to resolve the inject
  const callsApi = inject(callsSymbol)
  if (!callsApi) throw new Error('Failed to inject callsApi. Did you call createCallsApi() in a parent component?')
  return callsApi
}

With that, in your parent, you do
const { calls, getCall,...} = createCallsApi()

and in the child:
const { calls, getCall,...} = useCallsApi()

And that's all, no fumbling around with template refs.
Does that work for you, does it make sense?
Comment: thanks for your response and your help. I think that this can help me. But when i updated my code with all your response, en console when i clicked my button to send data to composable, return: Uncaught ReferenceError: provide is not defined
Comment: Oh, you need to import provide and inject from vue. I have added the statement to the answer
Comment: thanks, also if i remove default in export, return WARNING in ./resources/js/components/formTelemarketing.vue?vue&type=script⟨=js (./node_modules/babel-loader/lib/index.js??clonedRuleSet-5.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./resources/js/components/formTelemarketing.vue?vue&type=script⟨=js) 20:26-40
export 'default' (imported as 'createCallsApi') was not found in '../composables/ncalls' (possible exports: createCallsApi, useCallsApi)
Comment: use `import { createCallsApi } from '../composables/ncalls'`
Comment: now i apply your response, but form not show nothing, no action
Comment: now to use import return ERROR in ./resources/js/composables/ncalls.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\xampp\htdocs\gds_nuevo\resources\js\composables\ncalls.js: Identifier 'createCallsApi' has already been declared. (8:16)
Comment: if it's any use i need call this composable in action button that call to function searchRegisters() in my component form
Comment: Looks like you declared `createCallsApi` twice. You IDE should mark that as an error too
Comment: only have createCallsApi one twice, in export function, and import... how said me
Comment: now i can to do that your response run for me. But i don´t know how i can to do, for send parameter to my anonymous function getCall and this return my data... when i clicked my button in form. Thanks for help
Answer: i resolve my question with this code:
first in my component:
call to my function ref
getCall(toRef(param_search,'param_search'))

in my composable add onMounted and watch
onMounted(() => {
        if (param_search) {
            getCall(param_search)
        }
    })
    watch(
        () => param_search,
            (val) => {
                if (val) {
                loading.value = true
                getCall(val)
            }
        },
    )

with this, i can access to my function


Wordpress custom database table not recognized

Question: I've manually created a custom table, sdp_invites, for my wordpress (v3.4.2) site. I've done this many times in the past, but now I'm unable to use any of the $wpdb methods:
global $wpdb;
global $current_user;

$query = "INSERT INTO spd_invites (sender_id,receiver_id,job_id,job_title,job_slug,employer_id) VALUES ('{$current_user->ID}','{$resume->user_id}','{$job_id}','{$job_title}','{$job_slug}','{$employer_id}')";

$wpdb->get_results($query); //ERROR...
$wpdb->query($query); //ERROR...

Here's the error:
WordPress database error: [Table 'sow2.spd_invites' doesn't exist]
INSERT INTO spd_invites (sender_id,receiver_id,job_id,job_title,job_slug,employer_id) VALUES ('799','809','6','Professional Basket Weaver','professional-basket-weaver','5')

I know the table exists because I manually created it and I can see it in phpMyAdmin. Any idea why I'm getting this error?
UPDATE:
The WP user is called "root" (on my local dev setup). Here's the privileges listed in phpMyAdmin:
User    Host             Type    Privileges  Grant  Action
root    localhost    global  ALL PRIVILEGES  Yes

UPDATE2:
Just to rule out a bunch of possibilities, I tried a simpler query: "SELECT * FROM sdp_invites". This throws the same error. When I change to a wp core table, it works without error "SELECT * FROM sdp_invites"
Comment: Is the correct database selected?
Comment: This should certainly work if you have the proper schema selected - are wordpress and your custom table in the same schema?
Comment: @rsz it won't do that unless you use `$wpdb->prefix`
Comment: Does doing just a select of that table throw the same error?
Comment: Yes. sow2 is the correct DB. And everything else on the site is working.
Comment: is spd the same prefix as all the wp tables?
Comment: Did you create the table with the same user as Wordpress is logging in as?
Comment: @MrD Yes. Same error with `SELECT...` and no, the core tables use `wp_` as the prefix.
Comment: My suggestion is as @doublesharp look at users and permissions, and if not then create the table again but using the wpdb class... odd one
Comment: you have a prefix for the wp tables and wp is automatically assigning that to the tables
Comment: @doublesharp I'm not sure I understand the question. Are you talking about the PHP user? I create the table using phpMyAdmin, so I *think* the answer is yes. And the custom table is in the same db (sow2) as the rest of the WP core tables.
Comment: You have a syntax error on the question. Is this is in the code too?
Comment: @PhilipWhitehouse What's the error?
Comment: You double-close the `";` Hence why the colour-coding is messed up. If it's on the file I'm surprised it even runs.
Comment: @PhilipWhitehouse Just a copy/paste typo. Not in the source code. (fixed above)
Comment: I was just reading this peace of text he inserted:
`WordPress database error: [Table 'sow2.spd_invites' doesn't exist]
INSERT INTO spd_invites (sender_id,receiver_id,job_id,job_title,job_slug,employer_id) VALUES ('799','809','6','Professional Basket Weaver','professional-basket-weaver','5')`
Comment: @Emerson - I just updated my answer with a function that will print out all the tables visible to the WP user, verified it works on a local site on my computer.
Comment: @doublesharp That was COOL! I ran it and `sdp_invites` is listed.
Answer: My best guess is that you haven't granted permission to you Wordpress MySQL database user for your new custom table, presumably because you created it with a different MySQL user through phpMyAdmin. Try running:
GRANT ALL PRIVILEGES ON sow2.spd_invites TO 'wordpress_user'@'wordpress_host';
FLUSH PRIVILEGES; -- load new privileges

Replace "wordpress_user" with your Wordpress MySQL username (can be found in wp-config.php) and "wordpress_host" with the hostname of your Wordpress server (or localhost if it's on the same server).
Keep in mind that this will allow the Wordpress MySQL full permissions (SELECT, INSERT, DROP, etc) to this table, which may not be desirable. See the MySQL docs for my info on the GRANT command - http://dev.mysql.com/doc/refman/5.5/en/grant.html
You will want to run your insert using the query() function as it won't return any results:
$wpdb->query($query);

To view all tables visible to your Wordpress MySQL user, add the following to your theme's functions.php file to print out the table names at the bottom of every page:
function show_all_tables(){
    global $wpdb;
    foreach($wpdb->get_results("SHOW TABLES", ARRAY_N) as $table):
        echo $table[0]."
";
    endforeach;
}
add_action('wp_footer', 'show_all_tables');

Comment: Is there an easy way to figure out what 'wordpress_user'@'wordpress_host' should be for my specific instance?
Comment: or since you have phpmyadmin access there is a tab called privilegdes, all users are listed there
Comment: Tried it. SQL query was successful. But when I reload the page I get the same error.
Comment: @MrD Good point, with the schema selected you can choose the privileges tab, and then edit the privileges from there - this is a good way to make sure you edit same user@host that you're using for login
Comment: I double checked that also, and all privileges are granted to the wp user.
Comment: @Emerson - try going the `phpMyAdmin` route, it might make it a bit easier to see what's going on if you aren't familiar with MySQL commands.
Comment: run `FLUSH PRIVILEGES` to load the new privileges.
Comment: @doublesharp Ran that query also. No change. I added the phpMyAdmin privileges to the question.
Comment: @Emerson to me that says you don't have `INSERT` privileges on the new table for some reason.
Comment: @doublesharp I just deleted that comment because NOW all of a sudden I'm again seeing the error for the SELECT query also. I'm not sure if it was working or I made a mistake. Sorry for the confusion.
Comment: @Emerson can you see the table when you run the function that calls `SHOW TABLES`?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18824/discussion-between-doublesharp-and-emerson)
Comment: Yup. It lists my entire DB and `sdp_invites` is included. I've been reloading the page again and again and it looks like I'm not crazy: the error does appear INCONSISTENTLY when I test using the SELECT command. I copied the code into another template file and I get an error on one but nothing on the other. Really confusing.


How to find locked rows in Oracle

Question: We have an Oracle database, and the customer account table has about a million rows. Over the years, we've built four different UIs (two in Oracle Forms, two in .Net), all of which remain in use. We have a number of background tasks (both persistent and scheduled) as well.
Something is occasionally holding a long lock (say, more than 30 seconds) on a row in the account table, which causes one of the persistent background tasks to fail. The background task in question restarts itself once the update times out. We find out about it a few minutes after it happens, but by then the lock has been released.
We have reason to believe that it might be a misbehaving UI, but haven't been able to find a "smoking gun".
I've found some queries that list blocks, but that's for when you've got two jobs contending for a row. I want to know which rows have locks when there's not necessarily a second job trying to get a lock.
We're on 11g, but have been experiencing the problem since 8i.
Answer: Oracle's locking concept is quite different from that of the other systems.
When a row in Oracle gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.
This means that locking a record in Oracle means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE on a read only tablespace.
More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.
This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.
Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.
You can obtain some special locks, like locked metadata objects (using v$locked_object), lock waits (using v$session) etc, but not the list of all locks on all objects in the database.
Comment: Cant' you use V$LOCK to obtain all the locks? Even if you can't determine the specific rows that are being locked, at least you know which tables.
Answer: You can find the locked tables in Oracle with the following query.
select
   c.owner,
   c.object_name,
   c.object_type,
   b.sid,
   b.serial#,
   b.status,
   b.osuser,
   b.machine
from
   v$locked_object a,
   v$session b,
   dba_objects c
where
   b.sid = a.session_id and
   a.object_id = c.object_id;

Comment: to execute this query required DBA admin rights? getting invalid view or table
Answer: Rather than locks, I suggest you look at long-running transactions, using v$transaction. From there you can join to v$session, which should give you an idea about the UI (try the program and machine columns) as well as the user.
Comment: How do I join from v$transaction to v$session?
Answer: Look at the dba_blockers, dba_waiters and dba_locks for locking. The names should be self explanatory.
You could create a job that runs, say, once a minute and logged the values in the dba_blockers  and the current active sql_id for that session. (via v$session and v$sqlstats).
You may also want to look in v$sql_monitor. This will be default log all SQL that takes longer than 5 seconds. It is also visible on the "SQL Monitoring" page in Enterprise Manager.
Comment: `dba_blockers` and other views you mentioned will only list locks being waited for. @op specified that he wants all locks, not only those on the records being contended.
Comment: But if nothing is being blocked then a session can lock for as long as it likes as it won't affect performance.

Only blocking locks affect performance.
Answer: The below PL/SQL block finds all locked rows in a table.  The other answers only find the blocking session, finding the actual locked rows requires reading and testing each row.
(However, you probably do not need to run this code.  If you're having a locking problem, it's usually easier to find the culprit using GV$SESSION.BLOCKING_SESSION and other related data dictionary views.  Please try another approach before you run this abysmally slow code.)
First, let's create a sample table and some data.  Run this in session #1.
--Sample schema.
create table test_locking(a number);
insert into test_locking values(1);
insert into test_locking values(2);
commit;
update test_locking set a = a+1 where a = 1;

In session #2, create a table to hold the locked ROWIDs.
--Create table to hold locked ROWIDs.
create table locked_rowids(the_rowid rowid);
--Remove old rows if table is already created:
--delete from locked_rowids;
--commit;

In session #2, run this PL/SQL block to read the entire table, probe each row, and store the locked ROWIDs.  Be warned, this may be ridiculously slow.  In your real version of this query, change both references to TEST_LOCKING to your own table.
--Save all locked ROWIDs from a table.
--WARNING: This PL/SQL block will be slow and will temporarily lock rows.
--You probably don't need this information - it's usually good enough to know
--what other sessions are locking a statement, which you can find in
--GV$SESSION.BLOCKING_SESSION.
declare
    v_resource_busy exception;
    pragma exception_init(v_resource_busy, -00054);
    v_throwaway number;
    type rowid_nt is table of rowid;
    v_rowids rowid_nt := rowid_nt();
begin
    --Loop through all the rows in the table.
    for all_rows in
    (
        select rowid
        from test_locking
    ) loop
        --Try to look each row.
        begin
            select 1
            into v_throwaway
            from test_locking
            where rowid = all_rows.rowid
            for update nowait;
        --If it doesn't lock, then record the ROWID.
        exception when v_resource_busy then
            v_rowids.extend;
            v_rowids(v_rowids.count) := all_rows.rowid;
        end;

        rollback;
    end loop;

    --Display count:
    dbms_output.put_line('Rows locked: '||v_rowids.count);

    --Save all the ROWIDs.
    --(Row-by-row because ROWID type is weird and doesn't work in types.)
    for i in 1 .. v_rowids.count loop
        insert into locked_rowids values(v_rowids(i));
    end loop;
    commit;
end;
/

Finally, we can view the locked rows by joining to the LOCKED_ROWIDS table.
--Display locked rows.
select *
from test_locking
where rowid in (select the_rowid from locked_rowids);

A
-
1

Answer: Given some table, you can find which rows are not locked with SELECT FOR UPDATESKIP LOCKED.
For example, this query will lock (and return) every unlocked row:
SELECT * FROM mytable FOR UPDATE SKIP LOCKED

References

Ask TOM "How to get ROWID for locked rows in oracle".

How to find locked rows in Oracle


How to set workspaces in Ubuntu 21.10?

Question: How can a row of six workspaces be set in the top panel in Ubuntu 21.10?
Comment: Does [this](https://extensions.gnome.org/extension/1485/workspace-matrix/) extension work for you? It is much simpler to customize the desktop in MATE/KDE/XFCE. You may consider switching to one of them, if you plan to heavily customize the desktop.
Answer: In Gnome Tweaks, you can set a fixed number of workspaces using Gnome Tweaks, Workspaces tab . This option will be included in the main Gnome settings in future versions.
You then can set up a workspace indicator in the top bar using extensions.
Workspace Indicator by fmuellner is an official extension, which is part of the extensions for Gnome Classic (Gnome Shell configured like the classical Gnome 2, with application menu and task bar on the bottom). Install these extensions with the command:
sudo apt install gnome-shell-extensions

Turn the extension "Workspace Indicator" on using the Extensions tool or using the command line.
Gnome Tweaks and the Extensions tool are not installed by default. Install them using Software or with the command line:
sudo apt install gnome-tweaks gnome-shell-extension-prefs

How to set workspaces in Ubuntu 21.10?


Creating a reusable Redux Wrapper

Question: I am working on a RoR project that uses webpacker and react-rails.  We are slowly moving away from haml to React.  Because of this, each page we are doing react_component('page_to_render') We are also using Redux and I had been calling my component directly in the Provider and it was working fine.  Because of the way we are using this, each page will in a sense be it's own React app, I am trying to make a reusable component to pass the store.  My thought was the following:
import React, { Component } from 'react'
import { Provider } from 'react-redux'

import store from './store'

class ReduxState extends Component {
  render() {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    )
  }
}
export default ReduxState

So for each page, we'd just have to wrap it in <ReduxState></ReduxState>, but when I do this I get:
Could not find "store" in the context of "Connect(BillingPage)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(BillingPage) in connect options.
It seems that store should be passed down to anything wrapped in  but that isn't the case.  I feel like I might be missing something about how Redux works.  Is there a better way to approach this?
Comment: Please, provide https://stackoverflow.com/help/mcve for your case. I'd expect that ReduxState and connected components use different copies of `react-redux` package.
Answer: After reading more into my errors, I realized that I am returning the Provider within JSX and that the BillingPage class itself has no reference to ReduxState
I realized I needed a HOC.  Solution below:
import React, { Component } from 'react'
import { Provider } from 'react-redux'

import store from './store'

const ReduxState = WrappedComponent => {
  return class extends Component {
    render() {
      return (
        <Provider store={store}>
          <WrappedComponent {...this.props} />
        </Provider>
      )
    }
  }
}

export default ReduxState

const composedHoc = compose(
  ReduxState,
  connect(
    mapStateToProps,
    {
      addBill,
      removeBill
    }
  )
)

export default composedHoc(BillingPage)

Creating a reusable Redux Wrapper


Limit of holomorphic and bounded functions that can be extended to a ball

Question: Let $(f_n)$ be a sequence of bounded and holomorphic functions on the annulus $A=\{z\in\mathbb{C}\,|\, 1<|z|<2\}$ such that each $f_n$ can be holomorphically extended to $B_2(0) = \{ z\in\mathbb{C}\,|\, |z|<2\}$. Let $(f_n)$ converge uniformly to a holomorphic and bounded function $f$ on $A$. Show that $f$ can be holomorphically extended to $B_2(0)$.
My attempt: We find a sequence $(g_n)$ of holomorphic functions on $B_2(0)$ with $f_n = g_n|_A$ for all $n\in\mathbb{N}$. As each $f_n$ is bounded, we have $|g_n| = |f_n| \leq M$ on $A$. In addition, as holomorphic functions are continuous, we infer $m:=\max_{z\in \overline{B_{3/2}(0)}} |g_n(z)|<\infty$. Together, this yields $|g_n|\leq \max\{m, M\}$ on $B_2(0)$, i.e. each $g_n$ is bounded on $B_2(0)$. If I could now show that $(g_n)$ is Cauchy with respect to the supremum norm on $B_2(0)$ (I achieved to show compact convergence on $B_2(0)$ by using the maximum modulus principle, but according to this post, this is not equivalent to uniform convergence), there would be a holomorphic and bounded limit $g: B_2(0)\rightarrow \mathbb{C}$, as the set of holomorphic and bounded functions on a domain of $\mathbb{C}$ is Banach. But then $f_n$ converges uniformly to $f$ on $A$ and $f_n = g_n|_A$ converges uniformly to $g$ on $A$. By uniqueness of limits, $f=g$ on $A$. Thus, $g$ is the desired holomorphic extension of $f$ to $B_2(0)$. How can I show that $(g_n)$ is Cauchy?
Comment: another way is to remember that a holomorphic function in an annulus can be extended to the inner disc iff the negative power part of its Laurent series is null iff $\int_C f(z)z^ndz=0, n \ge 0$ where $C$ is a circle in the annulus parallel to the boundary circles (eg $|z| =3/2$ here will do); uniform convergence of $f_m$ on the circle $C$ then gives that for $f$
Comment: Can you define what you mean by $B_2(0)$?  Normally this stands for the open ball, but calling it "the disk" suggests you are considering the "closed ball".
Comment: I mean the open ball, I have edited the question.
Comment: Have you tried using the maximum modulus principle?
Comment: Yes, but I only achieved to show that the supremum of $|g_n(z)-g_m(z)|$ for $z\in K$ is smaller than $\epsilon$ where $K\subset B_2(0)$ is an arbitrary compact set, as the functions $g_n$ are not defined on $\partial B_2(0)$.
Comment: $$
  \sup_{|z|\leq1}|g_n(z)-g_m(z)| \leq \sup_{|z|=3/2}|g_n(z)-g_m(z)| = \sup_{|z|=3/2}|f_n(z)-f_m(z)|
  $$
Comment: And then you estimate $\sup_{|z| = 3/2}$ by $\sup_{z\in A}$ and use the uniform convergence of $(f_n)$ on $A$?
Answer: Based on the comments by Ruy, we have using the maximum modulus principle
\begin{align}
\sup_{|z|\leq 1} |g_n(z)-g_m(z)| &\leq \sup_{|z|\leq 3/2} |g_n(z)-g_m(z)| \leq \sup_{|z|= 3/2} |g_n(z)-g_m(z)|\\
&= \sup_{|z|=3/2} |f_n(z)-f_m(z)|\leq \sup_{z\in A} |f_n(z)-f_m(z)|<\epsilon,
\end{align}
as $f_n\to f$ uniformly on $A$ and convergent sequences are Cauchy. Then
\begin{equation}
\sup_{z\in B_2(0)} |g_n(z)-g_m(z)|\leq \max\Bigg\{ \sup_{|z|\leq 1} |g_n(z)-g_m(z)|,\,\, \sup_{z\in A} |g_n(z)-g_m(z)|\Bigg\}<\epsilon,
\end{equation}
so we indeed have that $(g_n)$ is Cauchy with respect to the supremum norm on $B_2(0)$.


Android's Policy for throwing processes out of memory

Question: I have a service in Android which takes a lot of memory and is occasionally removed from running.
What is the rule by which Android decides to remove a process? If so - how can I tell I'm about to stop running due to too much memory consumption? Most of the memory I allocate is allocated in native code.
Answer: If some other Application is consuming memory then also service can be terminated.Because there are not enough heap memory to allocate for your Application.To handle this you can handle low memory functions and inform user that Application is running on low memory.Also, while starting your service you can set to restart again.
Cheers.


Implementing recursive function with __iter__ method in a Python class

Question: So I'm working on a problem in which I'm to create a Python Class to generate all Permutations of a list and I'm running across the following questions:

I can complete this easily with a simple recursive function, but as a class it seems like I would want to use the iter method.  My method calls a recursive function (list_all) that's almost identical to my iter, which is very unsettling.  How do I modify my recursive function to be in compliance with best practices for iter?
I wrote this code, saw that it worked, and I feel like I don't understand it!  I try to trace the code line by line in a test case, but to me it looks like the first element in the list is frozen each time, and the rest of the list is shuffled.  Instead the output comes out in an unexpected order.  I'm not understanding something!

Thanks!
class permutations():
  def __init__(self, ls):
    self.list = ls

  def __iter__(self):
    ls = self.list
    length = len(ls)
    if length <= 1:
      yield ls
    else:
      for p in self.list_all(ls[1:]):
        for x in range(length):
          yield p[:x] + ls[0:1] + p[x:]

  def list_all(self, ls):
    length = len(ls)
    if length <= 1:
      yield ls
    else:
      for p in self.list_all(ls[1:]):
        for x in range(length):
          yield p[:x] + ls[0:1] + p[x:]

Comment: If your function works well, why would you want to squeeze it into a class? If the point is to lazily generate the permutations, just use `yield` in your function.
Comment: I am in agreement with this.  The word class was specifically stated in the question, so I'm trying to think how I would make it an iterable class that interfaces with the __iter__ method.
Answer: Just call self.list_all from __iter__:
class permutations():
  def __init__(self, ls):
    self.list = ls

  def __iter__(self):
    for item in self.list_all(self.list):
      yield item

  def list_all(self, ls):
    length = len(ls)
    if length <= 1:
      yield ls
    else:
      for p in self.list_all(ls[1:]):
        for x in range(length):
          yield p[:x] + ls[0:1] + p[x:]

Comment: This is one of those bittersweet moments in the learning process.  Happy I can get the desired result.  Irritated I didn't make this connection earlier.

Thanks!
Answer: Your list_all method is already a generator, so you can return that directly in __iter__:
class permutations():
    def __init__(self, ls):
        self.list = ls

    def __iter__(self):
        return self.list_all(self.list)

    def list_all(self, ls):
        length = len(ls)
        if length <= 1:
            yield ls
        else:
            for p in self.list_all(ls[1:]):
                for x in range(length):
                    yield p[:x] + ls[0:1] + p[x:]

This is both cleaner to read and executes faster.
You also have option is to define list_all inside __iter__.
class permutations2():
    def __init__(self, ls):
        self.list = ls

    def __iter__(self):
        def list_all(ls):
            length = len(ls)
            if length <= 1:
                yield ls
            else:
                for p in list_all(ls[1:]):
                    for x in range(length):
                        yield p[:x] + ls[0:1] + p[x:]

        return list_all(self.list)

Timing permutations vs my permutations2 gives almost identical results.


Taking learning into account in a development process

Question: How to deal with the fact that you don't know the language/framework in a development process?
For instance, suppose a group of Java developers are about to start a .NET project, they don't know the platform well and might end up finding solutions that the framework already solves or solves better.
The sort of questions I have are: which are the best practices in this case? Is RTFM before going on a good pratice? When should one stop RTFM and start asking/searching/playing? Is not RTFM and just searching/asking/playing a good practice? What about estimates?
I'd like to hear from your experience :-)
Answer: Learn the platform before writing production code!
Often people just jump in and start writing their app, and it becomes a mess, the developers learn lots then regret the "noob" stuff they did, but are locked in.
So my theory is take a few spikes and go throughan implement a very very thin feature that goes through all layers of a framework.
ie,  say if it was a web mvc / web services..... something that has javascript - > ajax -> html -> web service -> Controller -> Model -> Database.
Get people to review it.   Don't spend time building a framework layer when you don't know a lot about the Technology you are dealing with.   Spend some time exploring what kind of flexibility your technology has  (ie, try a number of different ways you can skin a cat)
Answer: Hands-on learning effort will beat RTFM almost every time assuming you have a team of skilled developers and the new technology is somewhat equivalent to what the team has historically done.  For example, I could see undertaking .NET web development with a bunch of Java web developers, but I would not be very comfortable undertaking .NET web development with a team that has been focused on VB Windows applications.  You should start with spikes of basic functionality that span all layers.  Best practice would be to add an expert or two to the team to help mentor and guide the development process via pair programming.  For estimating purposes, I would significantly reduce the number of story points I would allow the team to undertake in the first few iterations.  Conservatively, I would plan on achieving no more than half the team's historical velocity in the first few iterations.
Comment: I agree with the expert part, if it is possible it is totally worth hiring someone experience to accelerate the learning. But what if it isn't?
Answer: I think, as well as other, that it is important to have a good mental model and to understand abstractions you will use... However, sometimes it is not as easy, maybe because of insufficient time, experience or even documentation.
You can get some thoughts here: http://www.se-radio.net/podcast/2009-06/episode-138-learning-part-development-allan-kelly
There is also an agile methodology which takes learning as its strategic part: Adaptive Software Development (ASD) http://en.wikipedia.org/wiki/Adaptive_Software_Development
Lastly, I want to mention exploratory tests in Test Driven Development, which can help with learning new frameworks http://en.wikipedia.org/wiki/Exploratory_testing .
Comment: Thanks for the references! I agree with the importance of mental models and understanding of abstractions, but these may be different and learning them (and to combine them) takes time. One simple example is the dependencies and bindings on WPF, which I'm struggling right now in one project.
Answer: What about some sort of code-review or related step where some experienced person could glance through and offer suggestions.
RTFM seems like it would just waste time, especially if you are doing agile development.
EDIT: Since you said 'nobody' in the team knows the language... I don't know, but RTFM still seems like a waste of time to try and 'learn the whole language' before you start.
Comment: Of course, he says nobody on the team has experience with the toolset/technology.
Comment: Ah, my bad. I updated my post to reflect.
Answer: Most of the teams I've been on have had at least one language enthusiast.  These guys love to learn everything they can about new languages and are more than happy to share.  Figure out who this person is on your team and let them know that you're going to be working with the new language.
Once you start, do code reviews.  Lots of them on small, manageable pieces of code.  The code enthusiast will be able to point out things that are handled better by the language.  The whole team learns this way.


Having root directory abstracted?

Question: Am trying to find a way of concealing my root directory and having my applications running from a different directory all together.
Would really appreciate ideas and opinions in this exploration.
Comment: Like with Chroot? https://man7.org/linux/man-pages/man2/chroot.2.html
Answer: Do you mean something like chroot? Could you otherwise give some examples of what you want?

Having root directory abstracted?


BeautifulSoup find text contents

Question: I have an html doc that I want to find/replace given text.
I am looking for this text within the document

I can do:
soup.find(lambda x: 'this text' in x.text)

But that gives me a Tag object.  Is there any way to get a NavigableString and/or the actual position of 'this text'?
I'd sure hate to have to search, and then search for the same thing again.
Comment: I don't see why its an issue to search twice  -- python doesn't make it that hard: https://www.tutorialspoint.com/python/string_index.htm
Answer: text is just a property of the object returned by soup.find()
soup.find(lambda x: 'this text' in x.text).text

you're accessing it in your lambda function, but not on your object once soup.find() returns it

BeautifulSoup find text contents


Chrome Native Messaging not closed when chrome closed

Question: I've made chrome host for passing native messages between my extension and my process,  my process starts when chrome starts but not closed when i close chrome, should i add parameter to the manifest of the host or should i add my process handling to close the process when the chrome closed ?
thanks.
Comment: What language are you using? Would you mind posting some code?
Answer: You don't offer a lot of details but I can answer some of your questions:
- no need to add a "parameter" to the manifest; there is no such parameter
- no need to detect, from your process, when Chrome closes
Chrome starts your native messaging host whenever you send a message to it or, if you're using long lived connection, when you open the connection. The application should close when the STDIN stream closes (simply put, you can't read anymore from stdin).
For a single threaded app, the flow looks like this:
1. Read request from stdin
2. process request
3. write response to stdout;
Repeat 1-3 as long as you can read from stdin; if you can't read from stdin, break the loop and exit.
    std::string req;
while(!(req=read_request()).empty())
{
       //process request and send response
}

read_request is up to you to implement: the first 4 BYTES of the request contain the message length so read those 4 first then read len bytes that contain the actual JSON request. If you can't read anything (empty), then the while loop will break and you exit the app.
Answer: Building upon bkdc's answer;
if you are using C library function - getchar(), this should work;
unsigned int c = getchar();
if (c == 0xFFFFFFFF){//this means native app finished its work
        return 0;
}


Mapping Multiple Controllers in Spring MVC

Question: Define two controllers user and data as follows:
// 1st Controller
@Controller
@RequestMapping(value = {"/", "user"})
public class UserLoginController {
  @Autowired
    private UserLoginService userLoginService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showLoginForm(@ModelAttribute UserLogin userLogin) {
        //model.addAttribute(new UserLogin());
        //System.out.println("showLoginForm() is called");

        return "loginForm";
    }

}

    //Second COntroller

@Controller
@RequestMapping(value = "user/data/")
public class WorkplanController {

    @Autowired
    private WorkplanService WorkplanService;

    @RequestMapping(value = "importForm", method = RequestMethod.GET)
    public ModelAndView importForm(@ModelAttribute SheetUpload sheetUpload){
        return new ModelAndView("uploadWorkplan");
    }

    @RequestMapping(value= "doUpload", method = RequestMethod.POST)
    public ModelAndView doUpload(@RequestParam CommonsMultipartFile[] uploadFile, SheetUpload fileUpload, Workplan workplan, HttpServletRequest request) {
return new ModelAndView("uploadSucess");
   }

}

When i make request to the doUpload(), it shows  HTTP Status 400 Error.
My question is two-fold:
1. Why do have i have to include the user like this: @RequestMapping(value = "user/data/") to make request to the 2nd controller why not like this @RequestMapping(value = "data/")?
2. What do i need to change to make a successful call to the 2nd method in the second controller?
Here is the form am trying to submit:
<form:form action="doUpload"  modelAttribute="sheetUpload" method="post"
   enctype="multipart/form-data">
   <form:select class="createusers_select_menu" path="From">
      <form:option value="">Select...</form:option>
      <form:option value="A">A</form:option>
      <form:option value="B">B</form:option>
      <form:option value="C">C</form:option>
   </form:select>
   <form:input class="browse_btn" path="uploadFile" type="file" />
   <input type="submit" class="selct_workplan_2_btn" name=""  value=" "/>
</form:form>

Answer:
Why do have i have to include the user like this: @RequestMapping(value = "user/data/") to make request to the 2nd controller why not like this @RequestMapping(value = "data/")?

You don't have to. Change it to @RequestMapping(value="/data")

What do i need to change to make a successful call to the 2nd method in the second controller?

Try to get it working with a single file field only, then report back. There are lots of tutorials on the web to show how to upload files with Spring.
Comment: Thanks @Neil. i had changed and worked. i guess my netbeans IDE was caching bcos previously it didnt work. And yes i only needed to solve that issue. its clear what do next now


How can I add an extra field in Drupal 8 menu Item. I want to add an extra image field

Question: How can I add an extra field in Drupal 8 menu item? I want to add an extra image field so that I can use that to display along with menu.
Answer: Check the Menu Item Extras module on Drupal.org projects site. https://www.drupal.org/project/menu_item_extras
But if you are looking for the harder way, you should manage differences in the rendering of menu items in the menu template, altering entity definition of menu_link_content entity using hook_entity_type_build(), altering menu_link_content form integrations such as node create\edit form, override default menu item create form controller (there is provided property bundle with value menu_link_content by the default).
It was not easy to extend menu item create/edit form using Field UI features because of the bug in Drupal core. https://www.drupal.org/project/drupal/issues/2903161
But for now, the issue is solved.
So for now, you can manage that situation as with usual entity type. https://drupal.stackexchange.com/q/222260/60214 or https://drupal.stackexchange.com/a/220463/60214
Answer: You can add it through code and then run update.php or drush command to updatedb.
You can check answers here: https://drupal.stackexchange.com/questions/205058/how-to-add-fields-to-menu-items
Also check comments because I had some problems with that and I've left solution in comments.


Installing Ubuntu on a Windows 8 UEFI laptop?

Question: I have created an USB installer with UNetbootin for Ubuntu 12.10 Live (I'm not sure if that is the right one for this)
I disabled Fast Boot, but I didn't change UEFI to Legacy because nothing will boot at all when I do that.
When I boot to my USB, I get a prompt:
<code>grub>
</code>
I really don't know what to do from here, or if I even did anything right up to that point.
If anyone can help me with this, I would be very grateful. Thank you in advance.
Comment: Follow the 1st paragraph of https://help.ubuntu.com/community/UEFI
Answer: I've gotten that grub> prompt before when trying to write a live iso. It sounds like the live usb wasn't created quite right, usually the live iso's (especially Ubuntu's) have pretty menus and even a timer that will automatically start it in a few seconds, getting a grub> prompt means it didn't load the menu correctly. I don't think it's related to the boot options since it did get to a grub> prompt from the USB, so at least that's good.
There's probably a way to edit some files on the usb to get the menu to show up correctly, but it's far easier to just write the iso to the usb again with a different tool that will hopefully work correctly this time.
If you can boot another Ubuntu try using ubuntu's usb-creator Ubuntu Documentation Installation/FromUSBStick
Or if running in Windows try PenDriveLinux.com's Universal USB Installer
Or also for windows try Linux Live USB Creator (also linked on the Ubuntu Installation/FromUSBStick page above)
Usually that unetbootin tool is supposed to at least work, but I've found it doesn't use the regular (nice) menus that the iso creators have setup
Of course, make sure the iso file doesn't have errors, check it's MD5 or SHA1 against what it's supposed to be.


Notifying multiple Activities of network connection

Question: I have around seven activities in my android project and on all seven activities, i want to monitor network disconnection.I have created a networkreceiver class which receive notification when wifi is enabled or disabled.
public class NetworkReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent arg1) {
    ConnectivityManager conMan = (ConnectivityManager) context.
        getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = conMan.getActiveNetworkInfo();
    if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI)
        Log.d("WifiReceiver", "Have Wifi Connection");
    else
        Log.d("WifiReceiver", "Don't have Wifi Connection");
    }
}

and in manifest
<receiver android:name=".NetworkReceiver" >
    <intent-filter>
         <action android:name="android.net.wifi.STATE_CHANGE" />
         <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

My question is , Since i created it as a seperate class, i am not getting how to get notify on every activity that wifi is not enable.or do i have to create a network receiver as inner class in every activity.
Answer: Well I think that the answer with the handlers is a bit smelly - the biggest smell being that you have to keep the instance of the broadcast receiver around - a manifest receiver at that instantiated by request. Instead drop the registration in the manifest and register unregister the receiver onSart/Stop of your activity - no need to make the receiver an inner class for that. Unregistering onStop may not work on Froyo but hey - we're on KitKat
This way is better IMO as you haver the receiver in the activity it should signal and not mixing activity and receiver logic in the receiver class. Plus if you manage to hold a reference to the receiver let me know how - I am curious
Comment: but how to stop task when i get notifide that internet is not available.
Comment: @wqrahd: stop _which_ task ?
Comment: let say i am downlaoding the file and in between network disconnect.then how to stop or pause the downloading task and when network again connect resume or start again the task that was stopped or paused.
Comment: @wqrahd: The receiver may call a static method of the class - but static means trouble. The receiver may be an inner class after all and have access to the Activity's methods/fields - a pain if you have to repeat for all 7. Easiest: The receiver changes an internal preference (call getDefaultSharedPreferences(context) _in_ `onReceive`) and the activities all listen for such a change. You may even have a base activity the implements shared prefs listener and defines common behavior - heck you can have in this base activity the onStart/onStop
Comment: let say i have sharedpreference variable. and iam making a http request. so do i have to make this request in while loop and check like that "while variable true make http call"?
Comment: request may be a web page request. Since this request is only one time so how do i get info of network broken in between requesting this page.
Comment: You don't - set a timeout and catch the timeout exception
Comment: thanks man you making things clear to me. now one more thing let say i have a time out for 10 sec and at 5th sec network disconnect. do my app say force close or raise any exception or run until for the 10 sec mean upto time out time.?
Comment: i tried to use time out exception but it say this exception is never thrown from try block. i added parameter to request like HttpConnectionParams.setConnectionTimeout(httpParams, 10);
     HttpConnectionParams.setSoTimeout(httpParams, 10);
Comment: @wqrahd: That's another question - and maybe it's not that simple was just an idea of mine. Make sure you solve the notification if network exists or not and edit your question _adding your final solution_
Comment: i used a method to check if internet is availavle or not, whenever i am going to make http call. but i think its not correct way to do because while my request is processing , if network goes down then it might get crashed.
Comment: @wqrahd: you have asked 9 questions and accepted only one answer - this means that your questions are not focused - you are asking a question here you get many answers and not one satisfies you because your question _is too broad_. Understand ? So better ask more carefully
Comment: oh thanks for clearing me.but i think my question is clear enough. like you understand my question and give advices that helped me understading problem.
Comment: can please explain me . how to make a perfect , complete http request using android. mean if it crashes in between or time out occur so my app should not get close.it should handle error or exception properly.
Comment: i am accepting this as answer because you helped me alot uptil now.
Comment: @wqrahd: Ok - thanks but I do not want you to accept my answer if it did not really answer your question. So `can please explain me . how to make a perfect , complete http request using android. mean if it crashes in between or time out occur so my app should not get close.it should handle error or exception properly` : this is TOO GENERAL for a question. The answer to this question is 25 pages ! You must break it into smaller steps and ask a question for each. That way you will receive answers you can accept and are useful. So write code and post SMALL questions for PARTICULAR problems.
Comment: then i have to ask a new question...:P....i meant that if there is any kind of link than can explain my answer. thank you...:)
Answer: A nice solution works as follows. Your broadcast receiver has an array of objects (one for every activity) and when a notification arrives, you loop through the objects to let them know the WiFi state changed.
The details:
First, your broadcast receiver instance should be available to all Activities (through a static variable, singleton or however you want).
Second, each activity has a Handler object to handle events, let's call it mHandler.
Third, the broadcast recevier has an array of Handlers, let's call it 'mHandlerArray'.
In your broadcast receiver class have an array of Handler objects. Each activity subscribes itself by passing a pointer to a mHandler owned by each Activity. Your broadcast receiver could have two methods: one to register and one to unregister.
So, each Activity implements onResume() and onPause()
void onResume()
{
    mBroadcastReceiver.register(mHandler);
}

void onPause()
{
    mBroadcastReceiver.unregister(mHandler);
}

The broadcast receiver does this:
void register(Handler handler)
{
    mHandlerArray.add(handler);
}

void register(Handler handler)
{
    mHandlerArray.remove(handler);
}

Finally, when the WiFi state changes, from your onReceive() you iterate through the mHandlerArray and send each Handler a message. Each Activity processes the message accordingly.
Comment: if some of those activities already destroyed.then what will happen?
Comment: onPause() unregisters the handler, so by the time the Activity is destroyed, the handler won't be in the array any more.
Comment: i mean before any broadcast, some activities will get destroyed so does it cause a problem.because activities will destroyed on certain parameters
Comment: No problem, destroyed Activities won't be notified. I use this technique on one of my projects and it's very elegant (not the easiest I admit).
Comment: does declaring handler as static cause problem.?
Answer: if you register your receiver in manifest, then only defined class can receive the broadcast info. So, you can define register and unregister option in application class, then Broadcast-receiver method can keep your activities class (which activity class need to know network status)
Comment: `then only defined class can receive the broadcast info` ??? clarify and let me know (or delete)
Answer: Create a separate class Networkinfo and create a methode to check Internet connection.
Where you want to check internet then you call this methode with object of that class.
below link will help to detect connectivity.
How do I see if Wi-Fi is connected on Android?
Best of luck.


Update selectedIndex options menu with JQuery.MSDropDown

Question: I'm using a <select> options menu with jQuery.msDropDown but for some reason the DOM won't update after setting the select.selectedIndex property with javascript/jquery.
After I click on the drop-down menu then click back on the page (to close it) it does update with the correct selectedIndex.
I'm updating the selectedIndex in a loop like this:
    $.fn.[unrelated function].after = function( opts, curr, next, fwd ) {
        var $sel = document.getElementById('selectElem');
        for(var i = 0, j = $sel.options.length; i < j; ++i) {
            if(($sel.options[i].value).substr(1) == next.title) {
                //I have tried various ways here
                $sel.selectedIndex = i;
                //$('#selectElem').prop("selectedIndex",i);
                break;
            }
        }
    };

P.S. there doesn't seem to be any documentation for msDropDown otherwise I would have tried to identify what event would trigger an update of the box.
Comment: jQuery hint: $('#selectElem') is a shortcut for document.getElementById('selectElem');
Comment: @Diodeus in the chance that jQuery may have had extra functionality to fix these things I also tried the jQuery method
Comment: @Ozzy Why the down vote?  You didn't mention in your code that you tried `$('#selectElem').attr('selectedIndex',i);`.  Sorry, I'm just trying to help.
Comment: You can't assume Ozzy was the one who down-voted.
Comment: @Diodeus Aha, so it was you!
Comment: No, I just don't like assumptions.
Comment: @Ross I down-voted your answer because if you read my question carefully I specifically wrote 'I have tried various ways here' and gave an example because I knew I'd get a tonne of junk answers like yours (don't take it to heart)
Comment: @Ozzy I undeleted my original answer and edited it.  I hope this solves it.
Answer: Try this -
var oHandler = $('#selectElem').msDropDown().data("dd");
if(oHandler) {
    oHandler.set("selectedIndex", i);
}

Comment: Great - it works, really appreciate that. Changed my vote to an up-vote too.
Comment: @Ozzy Awesomeness, just trying to help, no worries about the confusion :~)
Answer: Here is the complete code:
$(document).ready(function() {
    $("#Country").msDropdown();

    var country_code = 'in';
    var i = 0;
    var indexNumber = 0;
    $("#Country option").each(function(){
        if($(this).val() == country_code){
            indexNumber = i;
        }
        i++;
    });
    var oHandler = $('#Country').msDropDown().data("dd");
    if(oHandler) {
        oHandler.set("selectedIndex", indexNumber);
    }

});


How to Change Color of Radio Button in android?

Question: I want to know how to change color of circle and border of radio button in android.please help me i trying this for two days.
Comment: see this post https://stackoverflow.com/a/52802572/4797289
Answer: More simple, just set the buttonTint color: (only works on api level 21 or above)
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radio"
android:checked="true"
     android:buttonTint="@color/your_color"/>

in your values/colors.xml put your color in this case a reddish one:
<color name="your_color">#e75748</color>

Answer: You need to set drawable to your RadioButton to change the color and border or any other part of it.
You can find more info here: RadioButton - how to use a custom drawable?
You can use the tint feature, but this won't work in older devices. Choose this if you are not supporting < API 21.


Utilizing vespa only as vector database and not embedder

Question: I have utilized Vespa when trying to store embedding embedded using some model defined in services.xml file. However, I intend to generate embeddings externally and store them in Vespa and utilize it for nearest neighbor search for explicitly providing query vectors.
However, I face issue defining schema for such use-case.
Answer: To fix this: Move the embedding field inside the document block in the schema.
(Also, the document type should be named "neighbors", not "schema".)
Explanation: Your embedding field is not sourcing another field and mutating it, as when the embedding happens in the indexing statement, it is just a value of the document. Those must be defined inside the document block as they define the document type that you can write and get.
Comment: you have deep knowledge of Vespa.  I cannot find such documentaiton at Vespa website.  Where can I find such information? For query, how can I create my own embedding using my own models?
Comment: Creating a document field which is a vector is definitely part of the documentation. To do the embedding yourself either call an api for it or use your own model. Sounds like you'd be better off letting Vespa do this though.


What is the difference between "systemctl hibernate" and "hibernate" commands?

Question: I configured hibernate function by the instruction here for Ubuntu 20.04.
Then I tried systemctl hibernate and hibernate commands and both are working fine.
By description from man, help and because of different locations of systemctl and hibernate (fromwhereis, which) it seems that this commands have different implementation.
What is the difference between them? Which one should be used?
Related question: Difference of pm-hibernate and systemctl hibernate
Answer: hibernate command was replaced by systemctl hibernate.
It is recommended to use systemctl hibernate.
hibernate command is still available in the system for compatibility reasons.

In most Ubuntu and similar Linux distributions, the systemctl tool has
replaced power management commands that were used in previous
releases. The following commands for instance have been replaced by
systemctl as shown below : halt → systemctl halt poweroff → systemctl
poweroff reboot → systemctl reboot …. For compatibility reasons
however, the old commands are still available in the system, but it is
recommended to rely on systemctl.

Source: How to shut down, restart, suspend and hibernate Linux
How power management commands work:
Shutdown, Reboot, Suspend and Hibernate a Linux System


How to use vim command character to find an explain in it's help file

Question: I try some vim command, and find the gh command will start a new command mode, which shows --select-- in my screan. just like the --visual-- command mode, that this --select-- mode can select some text.
I want know more about this command mode, then I press F1 to show the vim help file in vi.
how can I find the gh command in this help file ?
Answer: In general, to find help for a command in Vim, use the command mode (the one where you type :wq for exiting):
:help gh

You can press Ctrld to show a list of possible completions after typing this,
:he gh
gh                               c_<Right>                        -menuheight                      zip-copyright                    match-highlight                  Vimball-copyright
ghc                              i_<Right>                        :belowright                      'cmdwinheight'                   netrw-copyright                  <ScrollWheelRight>
'ghr'                            c_<C-Right>                      'helpheight'                     'nosplitright'                   'nowinfixheight'                 <C-ScrollWheelRight>
g:ghc                            c_<S-Right>                      'splitright'                     'winfixheight'                   shift-left-right                 <S-ScrollWheelRight>

As you can see, gh is listed, so just press Enter:
                                                        gh
gh                      Start Select mode, characterwise.  This is like "v",
                        but starts Select mode instead of Visual mode.
                        Mnemonic: "get highlighted".

Answer: Use :h select-mode and you see the description of the select mode. Here an excerpt:
==============================================================================
8. Select mode                                          *Select* *Select-mode*

Select mode looks like Visual mode, but the commands accepted are quite
different.  This resembles the selection mode in Microsoft Windows.
When the 'showmode' option is set, "-- SELECT --" is shown in the last line.

Entering Select mode:
- Using the mouse to select an area, and 'selectmode' contains "mouse".
  'mouse' must also contain a flag for the current mode.
- Using a non-printable movement command, with the Shift key pressed, and
  'selectmode' contains "key".  For example: <S-Left> and <S-End>.  'keymodel'
  must also contain "startsel".
- Using "v", "V" or CTRL-V command, and 'selectmode' contains "cmd".
- Using "gh", "gH" or "g_CTRL-H" command in Normal mode.
- From Visual mode, press CTRL-G.                       *v_CTRL-G*

...
                                                        *gh*

gh                      Start Select mode, characterwise.  This is like "v",
                        but starts Select mode instead of Visual mode.
                        Mnemonic: "get highlighted".
...


How many levels are there in Minesweeper adventure mode?

Question: I have been persisting at the Windows 8 minesweeper adventure mode in the hopes that I could complete it, but after getting past level 100, I am wondering if perhaps it just generates levels indefinitely? Does anyone know if the game actually has an end?
Answer: I'll answer my own question. After playing on for a bit (up to level 131 now) it seems that the levels just go through a fairly repetitive cycle. Four out of every five levels can be completed using logical deduction only to find the way through to the exit (you don't need to guess or use pick axes/dynamite/maps). Then every fifth level (i.e. where the level number is a multiple of 5) has so many traps that you'll need to use some of your axes/dynamite/maps to get through unscathed. So long as you don't waste what you pick up in the intervening four levels, you have more than enough to keep going indefinitely (I typically use 5/6 dynamites and 1/2 maps in the tricky levels).
In the multiples of 5 levels, there are treasure chests which worth vastly more than all the other treasure, making it relatively pointless to waste dynamite on other levels getting at the much less valuable treasure.
I've also noticed that while you can stockpile shields, it doesn't seem to let you keep more than 3 "lives" even though you can pick up quite a few more as you progress through the levels.
Basically I think the game goes on indefinitely, with a repeating sequence of 10 levels, each having similar characteristics to the one 10 levels before, but differing slightly in the placement of walls, treasure, traps etc.
Update: I'm at level 500 now, the pattern is repeating predictably:

Update 2: Once your score goes above 2147483648 (2^31) it starts to go back down as you collect more treasure - clearly the score is held as a 32 bit signed integer. The score is shown with a leading 0 rather than a minus sign.


How to use Automapper IMappingAction with asp.net bolierplate?

Question: Dears,
I used Automapper IMappingAction to encapsulate Before and After Map Actions into small reusable classes but i can't make my class work with ASPNET Bolierplate Ioc Castle Windsor
configuration.CreateMap<CustomerDto, Customer>()
 .AfterMap<CustomerAction>().ReverseMap();

public class CustomerAction : IMappingAction<CustomerDto, Customer>
{
    private readonly IObjectMapper _objectMapper;

    public CustomerAction(IObjectMapper objectMapper)
    {
        _objectMapper = objectMapper;
    }

    public void Process(CustomerDto customerDto, Customer customer)
    {

    }
}

when my code get execute, i got exception that my class doesn't have parameterless constructor
Comment: Here's a link to documentation that may help:  https://aspnetboilerplate.com/Pages/Documents/Dependency-Injection
Comment: I already read this document but i don't know how to integrate automapper with boilerplate ioc
Comment: Which class exactly doesn't have a parameterless constructor? And have you tried adding a constructor with no parameters to that class?
Answer: https://github.com/aspnetzero/aspnet-zero-core/issues/1587#issuecomment-415617774
Do you try this?
cfg.CreateMap<CustomerDto, Customer>().AfterMap((source, destination) =>
{
    var action = IocManager.IocContainer.Resolve<CustomerAction>();
    action.Process(source, destination);
}).ReverseMap();

public class CustomerAction : IMappingAction<CustomerDto, Customer>, ITransientDependency
{
    private readonly IObjectMapper _objectMapper;

    public CustomerAction(IObjectMapper objectMapper)
    {
        _objectMapper = objectMapper;
    }

    public void Process(CustomerDto customerDto, Customer customer)
    {

    }
}

Comment: Welcome @maliming ;) he cannot open AspNet Zero private repository link unless he has ongoing AspNet Zero license. but your answer seems correct. `ITransientDependency ` should work.


Can iOS Web Apps receive Apple Push notifications?

Question: I'm trying to evaluate whether to implement my application as a Web App or native app and was wondering if its possible to a web app to receive Apple Push notifications?
I suspect not but want to confirm so.
TIA
Answer: No, you must use the SDK, the best way to achieve this would be to have a wrapper app for your web app.


What does the 2 arrow icon mean?

Question: I currently have 24/40 Pokemon in my bag, and my Charmander and Bulbasaur each have an icon in the lower left corner with a left and right arrow.  What does this icon mean?  None of my other Pokemon have that.

Note: I have not yet traded any Pokemon (or anything else for that matter).  These 2 are specifically the ones you get from the "tutorial" section of the game (along with the Squirtle and the Pichu also pictured).
Comment: @RoijanEskor I should have included that in the post.  I have not traded anything yet.
Comment: My guess is that those pokemon were traded? Here's a video with a Bulbasaur with the same icon. https://youtu.be/BRC_BJy-yRo?t=935
Answer: Original answer:
For these Pokemon you have an extra button under their profile. Exchange. It shows a "Tree View". Which I'm still not sure what it does, but this is what the arrows mean, that you have access to their "tree view". I'm guessing that having all the Monsters on the tree allows you to upgrade/combine/evolve them to the one on the top of this tree.
I'm editing the answer now that I know exactly what the arrows mean.
Detail answer:
The arrows mean that these Specific Pokemon and Elemental attribute are part of an available Exchange. You can click on the Exchange icon in the Pokemon info and you will see the Tree it belongs to. After leveling up your account, not your Pokemon, you get access to an Exchange building. In this building you can exchange the Required Pokemon for another. Exchanges are done 4 Pokemon at a time, you can see the Exchange Tree divided in 4 smaller Exchanges, I call them lower level Exchanges. These require 4 Level 30, 4 Star Specific Pokemon and Elemental attribute.
Have in mind that the Tree shows you the Evolved Pokemon, but when you go on the Exchange Building, you get the Non-Evolved Pokemon at Level 1, and 4 or 5 Star, depending the Exchange that you completed. Lower level Exchange costs 100,000 and Higher level Exchange costs 500,000.

What does the 2 arrow icon mean?


What kind of data type is ('a'..'z')?

Question: If I type ('a'..'z').each { |a| puts a}, what exactly is going on at the datatype level? I know that when it's printed, it's individual strings but what is 'a'..'z' on its own? Is it an array?
Answer: It's a Range:
 ('a'..'z').class
 => Range

You can convert it to an array with ('a'..'z').to_a.
Answer: It's a Range:
irb(main):001:0> ('a'..'z').class
=> Range

Answer: To answer the second part of your question, 'a'..'z' is a Range. Like others have said:
('a'..'z').class # => Range

To answer the first part of your question about what is happening at the data type level, a range is like an array in several ways. When you use letters as your range endpoints, the range contains discrete elements, just like an array would. In other words, it contains all the letters from 'a' to 'z', inclusively. The same goes for when you use integers. 1..5 contains 1, 2, 3, 4, and 5. Like the Array class, Range includes the Enumerable module, so it has a bunch of methods like each. In your example, each is iterating over the members of your range.
Ranges differ from arrays in a few important ways.
First, you can use Float values as endpoints. For example, 1.1..5 is a valid range:
(1.1..5).class # => Range

When you try to iterate over a range like that, it will raise an error:
(1.1..5).each { |a| puts a } # => TypeError: can't iterate from Float

This is because the elements of that range are not discrete. The range is continuous.
Ranges also differ from arrays in that you can define them in a way that excludes the second endpoint by using ... instead of ... For example, 'a'...'z' contains the letters 'a' through 'y'. 'z' is not in this range. You can try ('a'...'z').each { |a| puts a } to demonstrate this.

What kind of data type is ('a'..'z')?


Missing dropbox applet indicator. How do I get it back?

Question: Dropbox icons missing from top panel. Reinstalling doesn't fix this problem.
But Dropbox daemon is work perfectly and i can confirm it was running. How can I get an applet indicator for it?
Answer: All you have to do is install libappindicator1, use the following command :
sudo apt-get install libappindicator1

Restart may necessary.
Comment: require a restart ? And thanks for fast response
Comment: Yeah somehow it need to restart for the effect


SQL - Generate bi-weekly end date on custom start date

Question: I want to get a custom Fort Night period based on a given start date.
I have a table that looks like this:
IF OBJECT_ID('tempdb..#tbl1') IS NOT NULL DROP TABLE #tbl1
SET DATEFIRST 1
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME

SET @StartDateTime = '2016-09-03'
SET @EndDateTime = '2017-01-28';

WITH DateRange(DateData) AS
(
    SELECT @StartDateTime as Date
    UNION ALL
    SELECT DATEADD(d,1,DateData)
    FROM DateRange
    WHERE DateData < @EndDateTime
)
SELECT ROW_NUMBER() OVER(ORDER BY DateData ASC) As ROWNum,DateData AS Date1
into  #tbl1
FROM DateRange
OPTION (MAXRECURSION 0)
GO

SELECT top 10 * FROM #tbl1

         Date1
        2016-09-09 00:00:00.000
        2016-09-10 00:00:00.000
        2016-09-11 00:00:00.000
        2016-09-12 00:00:00.000
        2016-09-13 00:00:00.000
        2016-09-14 00:00:00.000
        2016-09-15 00:00:00.000
        2016-09-16 00:00:00.000
        2016-09-17 00:00:00.000
        2016-09-18 00:00:00.000
        2016-09-19 00:00:00.000
        2016-09-20 00:00:00.000
        2016-09-21 00:00:00.000
        2016-09-22 00:00:00.000

I want to say the the first date of my bi-weekly period is 2016-09-09 and it ends 2016-09-22. How do I get bi-weekly end date for each of those dates.
So I want it to look like
         Date1                           FortNightEndDate
        2016-09-09 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-10 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-11 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-12 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-13 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-14 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-15 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-16 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-17 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-18 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-19 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-20 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-21 00:00:00.000       2016-09-22 00:00:00.000
        2016-09-22 00:00:00.000       2016-09-22 00:00:00.000

I'm using SQL Server 2005.
ANSWER:
I was able to solve it using the following code. Essentially I just created 3 tables:
StartDates
EndDates
InbetweenDates
The Start/EndDates tables had just the start and End of my 2 week period and an ID (Row Number)
The InbetweenDates table had all the dates between the 2 dates and also had a ID column but instead of going up 1 every row, it went up 1 every 14 rows.
Then I just joined the 3 tables. Essentially, the Start/EndDates tables were lookup tables.
I got the RowNumber on every 14 days code from here.
-- BEtween Dates
IF OBJECT_ID('tempdb..#BetweenDates') IS NOT NULL DROP TABLE #BetweenDates
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME

SET @StartDateTime = '2016-09-09'
SET @EndDateTime = '2017-04-30';

WITH DateRange(DateData) AS
(
    SELECT @StartDateTime as Date
    UNION ALL
    SELECT DATEADD(d,1,DateData)
    FROM DateRange
    WHERE DateData < @EndDateTime
)
SELECT
    DateData
into  #BetweenDates
FROM DateRange
OPTION (MAXRECURSION 0)
GO

select
    (case when convert(int, (ROW_NUMBER() OVER (Order by (select 0)) % 14))=0 then 0 else 1 end)
    + convert(int, (ROW_NUMBER() OVER (Order by (select 0)) / 14)) as ID
    ,DateData
INTO #BetweenDates_ID
from #BetweenDates

-- Start Dates

IF OBJECT_ID('tempdb..#StartDates') IS NOT NULL DROP TABLE #StartDates
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME

SET @StartDateTime = '2016-09-09'
SET @EndDateTime = '2017-04-30';

WITH DateRange(DateData) AS
(
    SELECT @StartDateTime as Date
    UNION ALL
    SELECT DATEADD(d,14,DateData)
    FROM DateRange
    WHERE DateData < @EndDateTime
)
SELECT ROW_NUMBER() OVER(ORDER BY DateData ASC) As ID,DateData
into  #StartDates
FROM DateRange
OPTION (MAXRECURSION 0)
GO

-- End Dates

IF OBJECT_ID('tempdb..#EndDates') IS NOT NULL DROP TABLE #EndDates
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME

SET @StartDateTime = '2016-09-22'
SET @EndDateTime = '2017-04-30';

WITH DateRange(DateData) AS
(
    SELECT @StartDateTime as Date
    UNION ALL
    SELECT DATEADD(d,14,DateData)
    FROM DateRange
    WHERE DateData < @EndDateTime
)
SELECT ROW_NUMBER() OVER(ORDER BY DateData ASC) As ID,DateData
into  #EndDates
FROM DateRange
OPTION (MAXRECURSION 0)
GO

--SELECT * FROM #StartDates
--SELECT * FROM #EndDates
--SELECT * FROM #BetweenDates_ID

SELECT
    st.DateData AS StartDate
    ,ed.DateData AS EndDate
    ,bd.DateData AS BetweenDate
FROM
    #StartDates st
    JOIN
    #EndDates ed
    ON st.ID = ed.ID
    LEFT JOIN
    #BetweenDates_ID bd
    ON st.ID = bd.ID

Comment: What is bi-weekly end date? How do you compute it?
Comment: Essentially I need fortnight end date from Wed to Thur (2 weeks). In the example, all dates from 2016-09-09 to 2016-09-22 belong to fortnight end date 2016-09-22
Answer: Try this:
SELECT Date1,
       DATEADD(DD, -1, DATEADD(WW,2,Date1)) AS FortNightEndDate
FROM #tbl1

Comment: That doesn't work. It adds 2 weeks to each date. I need to get fort night end date. Same as you would get a week end date or month end date. For example it would know that 2016-09-05 to 2016-09-011 (y/m/d) all belong to week ending 2016-09-11 (week starts Mon). I need the same thing but for 2 weeks starting on a Thur


Netplan not updating vlan

Question: I have configured multiple Vlan under a single interface. For operations need we have to change two Vlan, so i have just changed the Vlan id and name only other all information like IP address, route all are unchanged. After applying the configuration now i am seeing four Vlan. Two old vlan and two new vlan.
N.B. I have just changed the Vlan ID 244,242 with 254,252
ifconfig output
netplan config
Answer: When you remove an interface completely from your netplan config, netplan (or specifically, networkd) can no longer distinguish between a removed config and an interface that you have manually configured outside of netplan.  You can remove the no-longer-used vlans manually at runtime from the command line after applying the netplan config, or you can reboot the system to get a clean network state.
Comment: Can you please help at https://askubuntu.com/questions/1201815/vlan-over-netplan-in-18-04-lts/1201864?noredirect=1#comment2016401_1201864
Comment: Dear @slangasek, Thank you very much for your answer. I have resolved the issue by restarting the server. But i would like to know how can i remove unused vlan manually at runtime.
Comment: @MasudRana You need to run a command like `ip address delete dev en0.999` as shown at http://manpages.ubuntu.com/manpages/trusty/man8/ip-address.8.html . Unfortunately, you cannot do this *and* activate interfaces via `netplan` at the same time, so you may get locked out of the node one way or another.
Comment: I found that `ip address delete dev en0.999` gave back `RTNETLINK answers: Operation not supported` Using `ip link delete en0.999` worked for me.

Netplan not updating vlan


Change number on graph if certain condition occurs

Question: The code below generates a graph with a few points and a "prediction" line, so to speak. Notice that the number is tending towards a negative number, which in this case is -1.6. Therefore, I would like to do the following: when it happens that the number tends to a negative number, instead of showing that certain negative number in the graph, the value that would appear would be 0. So, for this case, instead of showing -1.6, the number displayed there would be 0.
Executable code below.
library(dplyr)
library(tidyverse)
library(lubridate)

dmda<-"2021-07-07"

datas <- structure(
  list(Code = c("CDE","CDE","CDE","CDE"),
       Days = c(41,42,43,44),
       Numbers = c(5.5,5.5,6,6.5)),
  class = "data.frame", row.names = c(NA, -4L))

f1 <- function(dat, code_nm) {
  dat <- subset(dat,  Code == code_nm)

  plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),
       xaxs='i',data = dat,main = paste0(dmda, "-", code_nm))
  if (var(dat$Numbers)>0){

    model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = dat, algorithm = "port")

    new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))
    new.data <- rbind(0, new.data)
    lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
    coef<-coef(model)[2]
    points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
    text(.99,coef + 1,round(coef,1), cex=1.1,pos=4,offset =1,col="black")} else {
      yz <- unique(dat$Numbers)
      lines(c(0,dat$Days), c(yz, dat$Numbers), lwd = 2)
      points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
      text(.1,yz+ .5,round(yz,1), cex=1.1,pos=4,offset =1,col="black")
    }

}

f1(datas, "CDE")

Answer: We may use max
f1 <- function(dat, code_nm) {
  dat <- subset(dat,  Code == code_nm)

  plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),
       xaxs='i',data = dat,main = paste0(dmda, "-", code_nm))
  if (var(dat$Numbers)>0){

    model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = dat, algorithm = "port")

    new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))
    new.data <- rbind(0, new.data)
    lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
    coef<-coef(model)[2]
    points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
    text(.99,coef + 1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")} else {
      yz <- unique(dat$Numbers)
      lines(c(0,dat$Days), c(yz, dat$Numbers), lwd = 2)
      points(0, yz, col = "red", pch = 19, cex = 2, xpd = TRUE)
      text(.1,yz+ .5, round(yz,1), cex=1.1,pos=4,offset =1,col="black")
    }

}

-testing
f1(datas, "CDE")

-output
Comment: Thanks akrun =)
Comment: Akrun, can you look? https://stackoverflow.com/questions/69489270/make-condition-for-graph-generation-when-there-are-two-points Another thing: Sorry, I sometimes send questions for you to see, if you don't like this, please let me know and I'll stop immediately.
Comment: @JVieira it is deleted.  I was offline earlier.  The SO removed the last seen from profile so nobody knows who is online or offline