text:
Q: Can I re-sign an .apk with a different certificate than what it came with? If I have an apk can I remove the current signing and some how re-sign it with a different .keystore file and still have the application install?
Update: I managed to get it to work with Jorgesys' solution and where I messed up before was that I unzipped the .apk then rezipped it after removing the META-INF folder and changed the file extension back into .apk. What I should have done is simply opened it with winzip and delete the folder inside of winzip.

A: zip -d my_application.apk META-INF/\*
keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name
zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

A: try this

1) Change the extension of your .apk to .zip
2) Open and remove the folder META-INF
3) Change the extension to .apk
4) Use the jarsigner and zipalign with your new keystore.

hope it helps

A: Signing for release: $1.apk -> $1_release.apk"
GeneralMills&GoogleApps#2012
Step 1: Removing any previous signing
Change the extension of your .apk to .zip
Open and delete the folder META-INF
Change the extension to .apk
    Or
Command:
•   zip [originalapk]
Example:
•   zip "$1".apk -d
Step 2: Signing with release.keystore..
Command:
•   jarsigner –verbose –keystore [keystorefile] –signedjar [unalignedapk] [originalapk] alias_name
Example:
•   C:\Program Files\Java\jdk1.6.0_43\bin> jarsigner -verbose -keystore release.keystore -signedjar "$1"_unaligned.apk "$1".apk release
Step 3: Aligning
Command:
•   zipalign -f 4 [unalignedapk] [releaseapk]
Example:
•   C:\Users\G535940\Downloads\adt-bundle-windows-x86\adt-bundle-windows-x86\sdk\too
ls>zipalign -f 4 "$1"_unaligned.apk "$1"_release.apk
Step 4: Cleaning up
Command:
•   rm 4 [unalignedapk]
Example:
•   rm "$1"_unaligned.apk
Additional Commands might help:

*

*To generate new key with keytool
keytool -genkey -alias  -keystore

*To list keys
keytool -list -keystore
Command to generate a keyhash for the Facebook features
Command:
•   keytool -exportcert -alias alias_name -keystore [keystorefile] | openssl sha1 -binary | openssl base64
Example:
•   C:\Program Files\Java\jdk1.6.0_43\bin>keytool -exportcert -alias release -keyst
ore release.keystore |opens l sha1 -binary | openssl base64
Note:
To sign our apks we have downgraded JDK from 1.7 to 1.6.0_43 update.
Reason:
As of JDK 7, the default signing algorithim has changed, requiring you to specify the signature and digest algorithims (-sigalg and -digestalg) when you sign an APK.
Command:
jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore [keystorefile]
[originalapk] alias_name

A: If you are looking for a quick simple solution, you can use Google's apksigner command line tool which is available in revision 24.0.3 and higher.

apksigner sign --ks release.jks application.apk

You can find more information about apksigner tool, at the developer Android site.
https://developer.android.com/studio/command-line/apksigner.html
Or, alternatively, you may use an open-source apk-resigner script
Open Source apk-resigner script https://github.com/onbiron/apk-resigner
All you have to do is, download the script and just type:

   ./signapk.sh application.apk keystore key-pass alias

A: All the solutions above work. Just a note why it didn't work for you when you re-zipped:
Some of the files inside the .apk need to remain stored (compression at 0%). This is because Android will use memory mapping (mmap) to read the contents without unpacking into memory. Such files are .ogg and some of the icons.

A: Assuming your keys are stored in keys.keystore, you can run:
$ keytool -list -keystore keys.keystore
Your keystore contains 1 entry

your_key_alias, Jan 3, 2013, PrivateKeyEntry,
Certificate fingerprint (SHA1): 8C:C3:6A:DC:7E:B6:12:F1:4C:D5:EE:F1:AE:17:FB:90:89:73:50:53

to determine the alias of your key. Then run:
zip -d your_app.apk "META-INF/*"
jarsigner -verbose -keystore keys.keystore \
   -sigalg MD5withRSA -digestalg SHA1 -sigfile CERT \
   your_app.apk your_key_alias

to re-sign your_app.apk with the key named your_key_alias.
The extra -sigfile CERT option seems to be necessary as of JDK 8.

A: Note if you use v2 signing schema (which you will automatically if you use build-tools 24.0.3+ in AS) you cannot just remove the META-INF folder from the APK since v2 adds its signing data to a zip meta block.
Google's new apksigner introduced in build-tools 24.03 (Android 7) is however able to resign APKs. You can just repeat the signing command to sign with a new keystore/cert (the old ones will be removed).
apksigner sign --ks keystore.jks signed_app.apk

Shameless plug: if you want a easier tool that can sign multiple apks and has better log output use: https://github.com/patrickfav/uber-apk-signer (uses Google's apksigner.jar in the background)


text:
Q: Purpose of Thread.Sleep(1)? I was reading over some threading basics and on the msdn website I found this snippet of code.
    // Put the main thread to sleep for 1 millisecond to
    // allow the worker thread to do some work:
    Thread.Sleep(1);

Here is a link to the the page: http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.80).aspx.
Why does the main thread have sleep for 1 millisecond? Will the secondary thread not start its tasks if the main thread is continuously running? Or is the example meant for a task that takes 1 millisecond to do? As in if the task generally takes 5 seconds to complete the main thread should sleep for 5000 milliseconds?
If this is solely regarding CPU usage, here is a similar Question about Thread.Sleep.
Any comments would be appreciated.
Thanks.

A: The 1 in that code is not terribly special; it will always end up sleeping longer than that, as things aren't so precise, and giving up your time slice does not equal any guarantee from the OS when you will get it back.
The purpose of the time parameter in Thread.Sleep() is that your thread will yield for at least that amount of time, roughly.
So that code is just explicitly giving up its time slot. Generally speaking, such a bit of code should not be needed, as the OS will manage your threads for you, preemptively interrupting them to work on other threads.
This kind of code is often used in "threading examples", where the writer wants to force some artificial occurrence to prove some race condition, or the like (that appears to be the case in your example)

As noted in Jon Hanna's answer to this same question, there is a subtle but important difference between Sleep(0) and Sleep(1) (or any other non-zero number), and as ChrisF alludes to, this can be important in some threading situations.
Both of those involve thread priorities; Threads can be given higher/lower priorities, such that lower priority threads will never execute as long as there are higher priority threads that have any work to do. In such a case, Sleep(1) can be required... However...
Low-priority threads are also subject to what other processes are doing on the same system; so while your process might have no higher-priority threads running, if any others do, yours still won't run.
This isn't usually something you ever need to worry about, though; the default priority is the 'normal' priority, and under most circumstances, you should not change it. Raising or lowering it has numerous implications.

A: Thread.Sleep(0) will give up the rest of a thread's time-slice if a thread of equal priority is ready to schedule.
Thread.Sleep(1) (or any other value, but 1 is the lowest to have this effect) will give up the rest of the thread's time-slice unconditionally. If it wants to make sure that even threads with lower priority have a chance to run (and such a thread could be doing something that is blocking this thread, it has to), then it's the one to go for.
http://www.bluebytesoftware.com/blog/PermaLink,guid,1c013d42-c983-4102-9233-ca54b8f3d1a1.aspx has more on this.

A: If the main thread doesn't sleep at all then the other threads will not be able to run at all.
Inserting a Sleep of any length allows the other threads some processing time. Using a small value (of 1 millisecond in this case) means that the main thread doesn't appear to lock up. You can use Sleep(0), but as Jon Hanna points out that has a different meaning to Sleep(1) (or indeed any positive value) as it only allows threads of equal priority to run.
If the task takes 5 seconds then the main thread will sleep for a total of 5,000 milliseconds, but spread out over a longer period.

A: It's only for the sake of the example- they want to make sure that the worker thread has the chance to print "worker thread: working..." at least once before the main thread kills it.
As Andrew implied, this is important in the example especially because if you were running on a single-processor machine, the main thread may not give up the processor, killing the background thread before it has a chance to iterate even once.

A: Interesting thing I noticed today. Interrupting a thread throws a ThreadInterruptedException. I was trying to catch the exception but could not for some reason. My coworker recommended that I put Thread.Sleep(1) prior to the catch statement and that allowed me to catch the ThreadInterruptedException.
        // Start the listener
        tcpListener_ = new TcpListener(ipAddress[0], int.Parse(portNumber_));
        tcpListener_.Start();
        try
        {
            // Wait for client connection
            while (true)
            {
                // Wait for the new connection from the client
                if (tcpListener_.Pending())
                {
                    socket_ = tcpListener_.AcceptSocket();
                    changeState(InstrumentState.Connected);

                    readSocket();
                }
                Thread.Sleep(1);
            }
        }

        catch (ThreadInterruptedException) { }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Contineo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Console.WriteLine(ex.StackTrace);
        }

Some other class...
        if (instrumentThread_ != null)
        {
            instrumentThread_.Interrupt();
            instrumentThread_ = null;
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: JPA Native Query I am trying to execute a native query and pass run-time parameters and get the result as a List. When I try to process the Object [], one of the columns fetched is a String. But it comes out as java.lang.Character instead of String. Here is the query below:
SELECT CASE
         WHEN (TRUNC(abm.credit_card_expiration_date) BETWEEN trunc(SYSDATE) AND
              trunc(last_day(SYSDATE))) THEN
          'Expires'
         ELSE
          'Expired'
       END EXP_STATUS,
       TO_CHAR(abm.credit_card_expiration_date, 'MM/YY') EXP_DATE
  FROM account_billing_methods abm
 WHERE abm.account_id = 201103
   AND abm.billing_type_id = 1
   AND TRUNC(abm.credit_card_expiration_date) <= TRUNC(LAST_DAY(SYSDATE))

The EXP_STATUS column could not be typecasted into String as it is of type Character. Any ideas of why it does not work?
Regards,
-Anand

A: I had the same problem and changed the select clause of my query to:
EXP_STATUS || '' as EXP_STATUS
Then it is a VARCHAR instead of a CHAR and JPA will return it as a String instead of a Character.
If someone knows a better/more elegant solution, I would appreciate if you could share it.


text:
Q: UTF-8 : characters not recognized I am trying to parse a text file using HashMap. The problem is that I have special characters like Ș and Ț and my application didn't recognize them.
This is my code:
    Map<String, String> m = new LinkedHashMap<String, String>();
    FileInputStream fin = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    try {
      fin = new FileInputStream("inferredflexforms.txt");
      isr = new InputStreamReader(fin, "UTF-8");
      br = new BufferedReader(isr);
      String line = br.readLine();
      while (line != null) {

        String[] toks = line.split("\\s+");
        m.put(toks[0], toks[1]);
        line = br.readLine();
      }
    } finally {
      if (br != null)  { br.close();  }
      if (isr != null) { isr.close(); }
      if (fin != null) { fin.close(); }
    }

System.out.println(m);

My text file contains: dănțaseși    dansa
And my output is: dăn?ase?i=dansa
The "ș" and "ț" was replaced by "?".
What should I do?
Thank you.


text:
Q: Is there any Ubuntu 12.04-compatible, open-source 3D modeling software capable of creating a 2D cross-section? I've heard that Blender's boolean algorithm might do the trick, but was wondering if a CAD software had this functionality.  Would want an end result similar to a stratigraphic cross-section.

A: Take a look at OpenVSP (Open Vehicle Sketch Pad).  You can slice up your solid and get cross sections. Image is of a Cessna 182 with 21 slices, along with some control panels.

A: Try FreeCAD

FreeCAD is a parametric 3D modeler. Parametric modeling allows you to
  easily modify your design by going back into your model history and
  changing its parameters. FreeCAD is open source (LGPL license) and
  completely modular, allowing for very advanced extension and
  customization.

For more information, and to download FreeCAD, visit their website.
Source:FreeCAD

A: alongside softwares in the site that Mitch suggests(http://opensourceecology.org/wiki/CAD_tools), I suggest MEDUSA4. it is not opensource but have free personal version.


text:
Q: A4 Landscape Orientation Printing I have screens in Zeplin that I need to make with HTML, CSS so they are ready to print on A4 (Landscape orientation). Their dimension is 842px x 595px which seems like good dimension for the A4 format but when I tried to print it, it is not covering full screen.
This is my css:
page {
background: white;
display: block;
margin: 0 auto;
margin-bottom: 0.2cm;
}
page[size="A4"][layout="portrait"] {
box-sizing: border-box;
page-break-inside: avoid;
width: 842px;
height: 595px;
display: flex;
}
@media print{
@page {
  size: A4 landscape;
}
}


text:
Q: My SPA does not load in AngularJS using Routing I have just started getting into AngularJS and was following the guide AngularJS in 60 Minutes by Dan Wahlin up to page 79. However, I'm only presented with my homepage which is blank by default; it does not load my view1.html which it should, according to the guide. I've been trying to locate the problem but cannot find it.
Unlike this guide, though, I'm not running the program through localhost but through file:///Users/.../home.html.
My code so far in home.html:
<!DOCTYPE html>

<title>Lekstuga</title>

   //here it should load Partials/view1.html

Followed by my code in View1.html:

View 1

Name:

<input type="text" data-ng-model="filter.name" />

    {{ cust.name }} - {{ cust.city | uppercase }}

Customer Name:

<input type="text" data-ng-model="newCustomer.name" />

Customer City:

<input type="text" data-ng-model="newCustomer.city" />

<button data-ng-click="addCustomer()">Add Customer</button>

View 2

A: When you say:
templateUrl: 'Partials/View1.html'

Angular looks in the same place where your index.html is. You probably have placed 'Partials' folder in app/views or something like that. Just provide the full path relative to the folder where 'index.html' is located.
But in general – may I suggest you to run a local webserver with nginx or MAMP or just use Yeoman http://yeoman.io/. This will make your life much easier.

A: There has been a change as of version 1.2 : the routing functionality has been moduled out.
The fix however is simple enough :

*

*Load the new javascriptfile in your code :     You can download it here http://code.angularjs.org/1.2.9/  (other versions other paths of course)

*Indicate the  'ngRoute' dependency in your code : var demoApp = angular.module('demoApp', ['ngRoute']);


text:
Q: RHEL leapp upgrade inhibited by YUM i try to upgrade a RHEL 7.9 to 8.4 with leapp.
When i try the update, it stoppes cause it says that yum is missing the plugins

*

*product-id

*subscription-manager

But fun fact, when i start yum, it says that they are installed.
[root@hana2dev3 iteanova]# yum
Geladene Plugins: langpacks, product-id, search-disabled-repos, subscription-manager

I#m now stuck with the upgrade. Any suggestions?


text:
Q: Automatically add date to .gif Alright,
What Im looking for is a script that would automatically add a date to a .gif, which I can run daily as a cron job. I don't know perl very well, but It seems that Perl & Gimp might be a way to get the job done. Can anyone point me in the right direction so I can create such a script
thanks!

A: I once implemented something similar using just a shell script and the -draw option to ImageMagick's convert program.
For a slightly more advanced approach, I'd use Python and PIL, which should be a lot easier to work with than trying to script the Gimp.

A: Another option is php with the gd extension.  Have a look at the manual pages for imagestring here and imagegif here.


text:
Q: How can i use sed to replace a line of text containing a dollar sign? I am trying to use sed to replace a line of text in a configuration file.
Original text:
%prod.db=${DATABASE_URL}?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"

Desired text:
%prod.db=${DATABASE_URL}?ssl=true&sslmode=require&sslfactory=org.postgresql.ssl.NonValidatingFactory"

I tried the following:
old="%prod.db=\${DATABASE_URL}?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"
new="%prod.db=\${DATABASE_URL}?ssl=true&sslmode=require&sslfactory=org.postgresql.ssl.NonValidatingFactory"
sed  's/^'"$old"'.*/'"$new"'/g' filename

And somehow ended up with this result:
%prod.db=${DATABASE_URL}?ssl=true%prod.db=${DATABASE_URL}?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactorysslmode=require%prod.db=${DATABASE_URL}?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactorysslfactory=org.postgresql.ssl.NonValidatingFactory

I assume the dollar sign is causing the issue and that it needs to be escaped somehow, but i have tried multiple ways to escape the replacement text without success, for example this answer: Escape a string for a sed replace pattern
I would be really grateful if anyone could help me solve this issue.

A: Reason on using ampersand operator using stream editor(sed/vim/vi):
$ echo murugesan openssl | sed "s/./& /g;"
m u r u g e s a n   o p e n s s l

Here & refer to the search string/any given pattern.
Since I searched . (any character)
All characters(using /g where g referring global) all being replaced with
same character followed by a space character.
Sample output:
$ echo stackoverflow | sed "s/...../& /;s/ ..../ & /;"
stack  over flow

vi delete.txt
Press i
type any text and few lines.
Press Esc and type the following:
:%s/./& /g
After typing g press Enter
Same replaced will happen inside current editor (vim.exe/vi/vim) based on your OS.


text:
Q: Can't put a string in a 2d array I'm trying to create a function that takes a string as parameter and returns a table that contains in each compartments a word of the given string.
Here's my code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int     nb_words(char *str)
{
  int   i;
  int   nb;

  i = 0;
  nb = 1;
  while (str[i] != '\0')
    {
      if (str[i] == ' ')
        nb++;
      i++;
    }
  return (nb);
}

void    my_show_wordtab(char **tab)
{
   int  i;

   i = 0;
   while (tab[i] != NULL)
      {
        printf("%s\n", tab[i]);
        i++;
      }
}

char    **put_in_tab(char *str, char **tab)
{
  int   i;
  int   j;
  int   k;

  i = 0;
  j = 0;
  if ((tab = malloc(sizeof(char *) * (nb_words(str) + 1))) == NULL)
    return (NULL);
  while (str[i] != '\0')
    {
      if ((tab[j] = malloc(sizeof(char) * (strlen(str) + 1))) == NULL)
        return (NULL);
      k = 0;
      while (str[i] != ' ' && str[i] != '\0')
        {
          tab[j][k] = str[i];
          k++;
          i++;
        }
      tab[j][k] = '\0';
      j++;
      i++;
    }
  tab[j] = NULL;
  my_show_wordtab(tab);
  return (tab);
}

int     main(int ac, char **av)
{
  char  **tab;

  if (ac != 2)
    return (1);
  if ((tab = put_in_tab(av[1], tab)) == NULL)
    return (1);
    return (0);
 }

When I use av I have this result
��

��

��

��

��

��

��

��

��

��

��

��

��

��

USER=benoit.pingris
JRE_HOME=/usr/lib64/jvm/!
LS_COLORS=no=00:fi=00:di!
LD_LIBRARY_PATH=:/home/b!
XDG_SESSION_PATH=/org/fr!
XNLSPATH=/usr/share/X11/!
GLADE_MODULE_PATH=:/usr/!
XDG_SEAT_PATH=/org/freed!
HOSTTYPE=x86_64
QEMU_AUDIO_DRV=pa
CPATH=:/home/benoit.ping!
SSH_AUTH_SOCK=/tmp/ssh-a!
SESSION_MANAGER=local/pc!
FROM_HEADER=
CONFIG_SITE=/usr/share/s!
PAGER=more
CSHEDIT=emacs
XDG_CONFIG_DIRS=/etc/xdg!
MINICOM=-c
on

As you can see this is isn't the result I expect to have. However if I decide to call my function without av but a string like this
my_str_to_wordtab("this is an orignal test", tab)

it works fine.

A: What I understand from your code is that you want to put a text into tab. Then you should not allocate tab itself, but set the pointer into tab as value.
So you are allocating this:
tab = malloc(...)

This should be something along the lines of
*tab = malloc(...)

Otherwise, the actual tab value you send in as parameter gets overridden, causing the destination to be wrong.
If you'd declare tab to be a single, unallocated, pointer, then you can send it in using the ampersand:
...
char *tab;
...
tab = NULL;
...
my_str_to_wordtab(..., &tab);

Also, I would advice to use a const parameter to your source string, to keep you from modifying it incorrectly.
Also, I do not think you want to do it this way, as without free() calls, it is a lot of memory leakage.
What you are getting on the screen is the side effect of reading invalid memory, and you are lucky to get anything, a page/segmentation fault would be likely to occur and this way security breaches are created.


text:
Q: Use accents with Japanese keyboard layout in Kubuntu I would like to use french accents using the Japanese keyboard layout. Dead keys would be great, but I am willing to accept key combinations too. I just would not like to switch the layout, because that will confuse the location of other punctation symbols. So far I was unable to find the right key combinations in Kubuntu. Any ideas?
Kind regards,
Stéphane (which I wrote by googling my name and copy-pasting :P)

A: Since Japanese keyboards use a QWERTY layout just as in the US and UK layouts, it should be possible to use multiple key combinations to type French characters such as é (as used in your name). This was achieved using the key combination Compose then e then '.
Special Characters from Linux Keyboard
RightWindows key latches then press keys in sequence using shift where necessary for correct symbol.
A more complete list is reproduced below. I have assigned Right Win as the Compose key to achieve this.


text:
Q: Laravel 5.6 Unable to connect MS SQL Server 2008 R2 from PHP/Laravel I am using Laravel 5.6, and trying to connect with MS SQL Server 2008 R2, all running on local machine. I have a test database named "ItemMaster", which is working fine with my C#.Net application.
When I try to connect same database from Laravel, I am getting this error:
SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it. (SQL: select * from ITEM_CATEGORY)

Can anybody suggest how to fix this.
In config/database.php, I have setup sqlsrv driver as follows:
'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'MY-PC\MYSQL2008R2'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'ITEMMASTER'),
            'username' => env('DB_USERNAME', 'myuser'),
            'password' => env('DB_PASSWORD', 'mypassword'),
            'charset' => 'utf8',
            'prefix' => '',
        ],

Getting error on this line inside my controller:
$items = DB::connection('sqlsrv')->select('select * from ITEM_CATEGORY');

I installed Microsoft Drivers 4.3 for PHP for SQL Server and copied file php_pdo_sqlsrv_71_ts_x86.dll to php/ext folder.

A: I find solution for this problem, sharing might help someone else making same mistake.
Actually the mistake is how I defined SQL Connection parameters in config/database.php
'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', 'MY-PC\MYSQL2008R2'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'ITEMMASTER'),
            'username' => env('DB_USERNAME', 'myuser'),
            'password' => env('DB_PASSWORD', 'mypassword'),
            'charset' => 'utf8',
            'prefix' => '',
        ],

In this code segment, I actually defined my parameters as second parameter to env() which (be-definition) is not the real value but will be used as default value if that specific key is not found in .env file.
You can read more about Environment configuration here
So the final code segment should be like this:
'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => 'MY-PC\MYSQL2008R2',
            'port' => '1433',
            'database' => 'ITEMMASTER',
            'username' => 'myuser',
            'password' => 'mypassword',
            'charset' => 'utf8',
            'prefix' => '',
        ],

Or another alternative may be to define these parameters in .env file, in the root directory of your application .


text:
Q: Numpy: How to produce a specific array (an iterator would be even better) I need an array or an iterator to loop on, with the following characteristic :
1° I have a set of $d$ vectors of size $n$ (random, sorted), say x[0],...,x[d-1].
2° I want every iterated value to be a vector od size $d$, with all combinaisons of potential values from the above vector. Which means :
y[0]       : [x[0,0], x[1,0],....,x[d-1,0]]
y[1]       : [x[0,1], x[1,0],....,x[d-1,0]]
y[2]       : [x[0,0], x[1,1],....,x[d-1,0]]
...
y[-1]      : [x[0,n-1], x[1,n-1],...., x[d-1,n-1]]

How can i produce this array or this iterator ?
for exemple, for d=3 and n=3 this would produce the following vectors :
y[0]       : [x[0,0], x[1,0], x[2,0]]
y[1]       : [x[0,1], x[1,0], x[2,0]]
y[2]       : [x[0,2], x[1,0], x[2,0]]

y[3]       : [x[0,0], x[1,1], x[2,0]]
y[4]       : [x[0,1], x[1,1], x[2,0]]
y[5]       : [x[0,2], x[1,1], x[2,0]]

y[6]       : [x[0,0], x[1,2], x[2,0]]
y[7]       : [x[0,1], x[1,2], x[2,0]]
y[8]       : [x[0,2], x[1,2], x[2,0]]

y[9]       : [x[0,0], x[1,0], x[2,1]]
y[10]      : [x[0,1], x[1,0], x[2,1]]
y[11]      : [x[0,2], x[1,0], x[2,1]]

y[12]      : [x[0,0], x[1,1], x[2,1]]
y[13]      : [x[0,1], x[1,1], x[2,1]]
y[14]      : [x[0,2], x[1,1], x[2,1]]

y[15]      : [x[0,0], x[1,2], x[2,1]]
y[16]      : [x[0,1], x[1,2], x[2,1]]
y[17]      : [x[0,2], x[1,2], x[2,1]]

y[18]      : [x[0,0], x[1,0], x[2,2]]
y[19]      : [x[0,1], x[1,0], x[2,2]]
y[20]      : [x[0,2], x[1,0], x[2,2]]

y[21]      : [x[0,0], x[1,1], x[2,2]]
y[22]      : [x[0,1], x[1,1], x[2,2]]
y[23]      : [x[0,2], x[1,1], x[2,2]]

y[24]      : [x[0,0], x[1,2], x[2,2]]
y[25]      : [x[0,1], x[1,2], x[2,2]]
y[26]      : [x[0,2], x[1,2], x[2,2]]

I dont even know yet how much there should be depending on (n,d)...
Do you have an idea ?

A: There could be neater ways to do this but I think this does what's asked for.
import numpy as np

def rows( d, n ):
    """ Generates row indices. """
    arr = np.zeros( shape = d, dtype = np.int )

    def inc_row( arr ):
        for ix in range(0, len(arr)):
            arr[ ix ] += 1
            if arr[ ix ] < n:
                return arr   # If arr[ix] doesn't roll over return arr
            arr[ ix ] = 0      # Reset arr[ix] to zero if it rolls over
        return None   # Return None once all indices reset to zero.

    while not arr is None:
        yield arr
        arr = inc_row( arr )

def permutations( base, d, n ):
    """ Generate the required combinations of values from base. """
    cols = np.arange( d )
    res = []
    for row in rows( d, n ):
        res.append( base[ row, cols ] )
    return np.array(res)

d = 3
n = 2

base = np.fromfunction( lambda x,y : x+y/10, shape = (n,d))
# For testing 'base' array values indicate location r.c

print(base)
# [[0.  0.1 0.2]
#  [1.  1.1 1.2]]

print(permutations( base, d, n ))
# [[0.  0.1 0.2]
#  [1.  0.1 0.2]
#  [0.  1.1 0.2]
#  [1.  1.1 0.2]
#  [0.  0.1 1.2]
#  [1.  0.1 1.2]
#  [0.  1.1 1.2]
#  [1.  1.1 1.2]]

HTH


text:
Q: Can different bounded context (BC) leave in one WPF application? We are building a system for managing our intern production of electrical goods manufacturing.
Regarding the complexity of our model, we think that DDD would be a good fit for our project.
The system is composed of a distributed web based system but also a heavy desktop application coded in WPF (using MVVM as presentation pattern).
I've just read the book "implementing domain driven design" (http://www.amazon.com/dp/0321834577) from Vaughn Vernon (which is very good) and I'm quite confused because DDD seems to fit pretty well in web-based environments, but is is the case for a WPF Desktop application?
Being a rookie with DDD, I'm quite confused about the integration of DDD in a desktop application.
Given a lot of sources on DDD including the iDDD book, it is stated that BC should be decoupled from other BCs. The pattern for managing integration between different BC is often to create Open Host Service. OHS can be implement using REST, messaging or SOAP. I understand this for a distributed system with several web applications.
But what if I have different BC inside one desktop application (WPF for the case)?
The application has to cover a large set of context like "production monitoring", "production qualitiy", which for me sounds like different BC.
Is it OK to have several BC in the same windows application? Or 1 BC should be 1 application? (which seems to be often the case for distributed systems for
What would be a good pattern for integrating different BC in one single desktop application?
A solution seems to create a "event bus" inside my application and BC could communicate with each others by publishing / subscribing events on the bus. This implementation will look like Prism's EventAgreggator or mvvm light's Messenger, but dedicated to the model.
Udi Dahan proposes similar pattern in Domain Events Salvation http://www.udidahan.com/2009/06/14/domain-events-salvation/ but it seems to be limited to one BC

A: as you have read the DDD book by Vaughn Vernon, so know that DDD is all about tackling the complexity by understanding the problem first and solving it in Domain model.
it doesn't matter which technology or tools you are using (Note: it's recommended to use an object oriented language) to promote your application.
we had the similar issue a few years ago (different BC inside one desktop application) and we used windows application for presenting. WPF is more flexible because of it's powerful binding feature witch let's you use MVVM patter and dependency injection.
Is it OK to have several BC in the same windows application?
as I mentioned bounded contexts of DDD could be presented in one windows or web Application because they have their own service and repository implementation.
don't assume bounded contexts of DDD as separate project! BCs could be successfully used in other project's Domain and not a separate project.


text:
Q: How to determine if a AWS Lambda function exists I am new to AWS SDK for JavaScript. I need to check if a Lambda function exists before I trigger execute on it.
I tried the following:
Each time I make a lambda.getFunctionConfiguration() using Function name I have to execute. If it returns an Error, the function doesn't exist. If I get meta, I continue with execution.
I feel this is not a cleaner way to handle this. Is there any other way to check if Lambda exists with the name?
Thanks in advance.

A: You can use ListFunctions JavaScript API and check if the lambda function is in the output.
listFunctions(params = {}, callback) ⇒ AWS.Request

Returns a list of your Lambda functions. For each function, the
  response includes the function configuration information. You must use
  GetFunction to retrieve the code for your function.

Corresponding CLI: aws lambda list-functions

A: Here is how to check if function exists with listFunctions() SDK method (proposed by helloV) in more async way.
const {Lambda} = require('aws-sdk');
const lambda = new Lambda({apiVersion: '2015-03-31'});

const lambdaExists = async (fName, marker = null) => {
    try {
        const {Functions, NextMarker} = await lambda
            .listFunctions({
                Marker: marker || '',
                MaxItems: 50
            })
            .promise();

        const exists = Functions.map(({FunctionName}) => FunctionName).indexOf(fName) !== -1;

        return exists || NextMarker;
    } catch (e) {
        // Handle with care
        console.log(e.toString());
        return e;
    }
};

Function returns true if function name is found in current iteration or NextMarker (string) if not. Iterations end when there is no NextMarker provided in received response.

Note: This function is a generic representation of possible way of solving the issue. Not fully tested in real conditions and could need some corrections to be used in your code.


text:
Q: .htaccess redirect exact page to non existent subdomain in laravel I am building a website with laravel framework.
i'm logging users in panel.domainname.com, but they also have public profile link.
and i want to redirect exact link to public profile subdomain with htaccess file.
for example:
original link: http://panel.domainname.com/publicprofile/12-somename
redirected link: http://profile.domainname.com/publicprofile/12-somename

but profile subdomain is not defined.
Is it possible?
Thanks.


text:
Q: Как сделать вывод данных из массива? Как вывести данные displayname и l ?
есть массив данных из ldata  вот сделал вывод массива
$info = ldap_get_entries($adconn, $result);
 print $info["count"]." entries returned";
 foreach($info as $item) {
        echo "
";
         print_r($item);
        echo "
";
 }

пробовал так, но не выводит ничего
foreach ($info as $item)
    if (is_array($item)) foreach ($item as $v) {
        if (isset($v['displayname']))
            print_r($v['displayname']);
        if (isset($v['l']))
            print_r($v['l']);
    }

A: решил, сделал вот так
$filter = "(cn=*)";
$att = array( "displayname", "l", "accountexpires");

и цикл вот такой
 foreach ($info as $item){
         if (is_array($item)) {
            echo $item['l'][0];
            echo $item['displayname'][0];
            echo "
";
            echo date('d.m.y H:i:s', $item['accountexpires'][0]);
            echo "
";
            echo $item['accountexpires'][0];
            echo "
";
        }
    }

но поле accountexpires - это дата выводится вот так
 [accountexpires] => Array
                (
                    [count] => 1
                    [0] => 9223372036854775807
                )

при echo date('d.m.Y H:i:s', $item['accountexpires'][0]); выдает 27.01.-292277022657 11:29:51


text:
Q: Parcel Unmarshalling unknown type code We are getting this error in the Crash reports logged by play store. Cant replicate this in all our testing. Does anyone else have the same problem or solution ?
Thing is, we dont even know what to do to replicate this bug.
All Parcelable objects have CREATOR, writeToParcel() and contructor defined. All Lists and complex types are initialised and null checked.
java.lang.RuntimeException: Unable to start activity ComponentInfo{au.com.company/au.com.company.DetailsActivity}: java.lang.RuntimeException: Parcel android.os.Parcel@42d6e270: Unmarshalling unknown type code 6881381 at offset 11268
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2247)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297)
at android.app.ActivityThread.access$700(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5328)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@42d6e270: Unmarshalling unknown type code 6881381 at offset 11268
at android.os.Parcel.readValue(Parcel.java:2032)
at android.os.Parcel.readMapInternal(Parcel.java:2225)
at android.os.Bundle.unparcel(Bundle.java:223)
at android.os.Bundle.getSparseParcelableArray(Bundle.java:1240)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:861)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1104)
at android.support.v4.app.FragmentManagerImpl.moveToState(SourceFile:1086)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(SourceFile:1872)
at android.support.v4.app.FragmentActivity.onCreate(SourceFile:215)
at android.support.v7.app.ActionBarActivity.onCreate(SourceFile:97)
at au.com.company.DetailsActivity.onCreate(SourceFile:40)
at android.app.Activity.performCreate(Activity.java:5250)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
... 11 more

A: I also got this error but I found the problem. I had changed a variable from long to int but forgot to change the following:
I had parcel.writeLong(number) and then read it back as number=parcel.readInt(). The correct is parcel.writeInt(number).

A: Check the order of your read and write in your Parcelable classes and respective sub-classes.
The order in which you writeToParcel should be the same order as you read within your MyParcelable(Parcel in) method.

A: I was having the issue with a custom view having its own implementation of View.BaseSavedState. It turned out that the writeToParcel() method there had method calls in the wrong order.
It was annoying to find the problem and I needed to step debug the Android SDK all the way to the Bundle class, where unparcel() is called:
synchronized void unparcel() {
    if (mParcelledData == null) {
        return;
    }

    int N = mParcelledData.readInt();
    if (N < 0) {
        return;
    }
    if (mMap == null) {
        mMap = new HashMap<String, Object>(N);
    }
    mParcelledData.readMapInternal(mMap, N, mClassLoader);
    mParcelledData.recycle();
    mParcelledData = null;
}

Line 223 of your log is exactly the readMapInternal() call. There the Parcel object will iterate through its items, reading the values one by one. The problem usually occurs if something was written in the wrong order. The method Parcel.readValue(ClassLoader loader) will read them in the order they were written but if you have custom views or objects, if they were written in an order different than the one you are now reading them, something wrong will happen in the NEXT item to read.
So I found the problem by identifying the last item that was read successfully. You can usually identify that (if it's a custom view or object) by checking its creator class name. Check the Parcel class' method readParcelableCreator():
public final <T extends Parcelable> Parcelable.Creator<T> readParcelableCreator(
        ClassLoader loader) {
    String name = readString();
    if (name == null) {
        return null;
    }
...
}

You can inspect the name string for the class of the creator. If it's a custom one, you can immediately identify it. Then, if the next reading crashes your app, you can be almost sure that the culprit was the previous read.
Hope it helps.

A: I got this error when I was over reading the Parcel source, to save on a Map instead of checking the return value is null as:
String tag = in.readString();
Double value = in.readDouble();
while (tag != null && value != null) {
    this.observations.put(tag, value);
    tag = in.readString();
    value = in.readDouble();
};

One should store an int to use to iterate correctly on the Parcel:
int numObservations = in.readInt();
String key;
Double value;
for (int i = 0; i < numObservations; i++) {
    key = in.readString();
    value = in.readDouble();
    map.put(tag, value);
}

A: I occurred the same error when read parcel.
Check the order and count while read/write of your Parcelable classes and respective sub-classes.

A: If you have your own SavedState class, make sure that  it is not Proguarded and neither is it's CREATOR static attribute.
Use something like:
# Keeping *SavedState and *SavedState#CREATOR
-keep public final class * extends android.view.AbsSavedState
-keepclassmembers public final class * extends android.view.AbsSavedState { *; }

A: In my case I was trying to assign an arrayList to a List and that triggers that error


text:
Q: Difference between "with" and "of"
S is the set of 2 elements.
S is the set with 2 elements.

Is there any difference between them?

A: These sentences are a little confusing, because they seem to be very technical.  A set containing elements is usually only used when describing things mathematically - a set of prime numbers, for instance.  Technical fields will often have specific grammar expectations that may be unique, so it is important to provide context.
In terms of English language usage, "of" means the things that make up the set, while "with" means things that are contained within the set.  "Of" is the entire set, while "with" may be part of the set.
For instance, let's say that I have a basket containing puppies.
If I describe it as "a basket of puppies", you could infer that the only thing in the basket is puppies. The basket might contain other objects like a blanket or a chew toy, but as far as the speaker is concerned the only significant objects in the basket are the puppies.
If I describe it as "a basket with puppies", there is a possibility that the basket contains other important things that are being overlooked.  For instance, there could also be a sleeping cat.
If I hand my friend a basket with puppies (and also a cat), and she has an allergic reaction to the cat, I can claim to have been truthful.  If I tell her it is a basket of puppies and don't mention the cat, she can claim I misled her.


text:
Q: Angular 4 or 5 - how to get result of this function in my component? I work with Angular 5 (with TypeScript)
I just want to get width and height of an image file (whithout installing a package, I think it's not necessary). I want to get them in variables of my component.
I use in my .ts a function that I used when I worked in javascript and I get yes the width and the height in the function but How can I get them OUT of the function ?? My function doesn't recognize the variables of my component.
Thank you and sorry if you find my question a bit stupid... I work with Angular recently.
Here is my code :
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test-function',
  templateUrl: './test-function.component.html',
  styleUrls: ['./test-function.component.css']
})
export class TestFunctionComponent implements OnInit {

  url: string;
  ratio: number;

  constructor() { }

  ngOnInit() {}

  myFunction() {
    const photo = new Image();
    photo.onload = function() {
      console.log(photo.width + 'x' + photo.height); // here it's ok
      const ratioHere = photo.width % photo.height;
      // return ratioHere ???? because this.ratio of the Component is undefined here
    };
    photo.src = 'https://www.google.fr/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';

    // this.ratio = ratioHere;
  }

}

A: Set ratio in your callback. Note that you need an arrow function so this is preserved correctly:
 photo.onload = () => {
      console.log(photo.width + 'x' + photo.height);
      const ratioHere = photo.width % photo.height;
      this.ratio = ratioHere;
    };


text:
Q: Use Spray Json to convert 2D sequence of Any into Json I am trying to understand Spray Json and very new to Scala. I have Seq(Seq("abc", 123, false, null), Seq("def", 45, "1234", 'C')) so a Seq[Seq[Any]]. I am not sure how to go about this and I cannot find any examples online.
case class SeqFormat(Seq[Seq[Any]]) => {
    // something that would convert to Seq[Seq[String]]
    //which will would return a Json like this
    //[["abc", "123", "false", "null"],["def", "45", "1234", "C"]]
}

I tried
val someSeq = [["abc", "123", "false", "null"],["def", "45", "1234", "C"]]
val myObj = someSeq.toJson
// This gives me an error saying Any is not valid

I would appreciate any hints or snippets to help me understand this.

A: You could use an encoder such as:
import spray.json._
import DefaultJsonProtocol._

implicit object AnyJsonFormat extends JsonFormat[Any] {

  def write(x: Any) =
    try {
      x match {
        case n: Int    => JsNumber(n)
        case s: String => JsString(s)
        case c: Char   => JsString(c.toString)
        case _         => JsString("null")
      }
    } catch {
      case _: NullPointerException => JsString("null")
    }

  def read(value: JsValue) = ???
}

Which you can use as follow:
val input = Seq(Seq("abc", 123, false, null), Seq("def", 45, "1234", 'C'))
println(input.toJson)

In order to get:
[["abc",123,"null","null"],["def",45,"1234","C"]]

This is an adapted version of this post: Serialize Map[String, Any] with spray json

Notice the NullPointerException handling for the null case.


text:
Q: What do we call the argument (variable or its value) of a function in Javascript? OK lets take an example:
function student(name,age){
document.write("I am " + name + "and I am " + age + " years old." );
}
var student_name = "Divyansh";
var student_age = 17;
student(student_name,student_age);

// now my question is what do we call the arguments of the function student :
(a) is it the variable: student_name & student_age respectively,
(b) or is it the value contained by the variables: divyansh & 17 respectively
PS- I have also posted the same question on codechef, but it seems nobody is interested in giving answer to my stupid and childish question. But, what do i do i am trying to study Javascript myself by the book head first javascript programming and got strucked due to this doubt in one of the question, Please Help.

A: An argument of a function is an expression with which the function is called.
In this case, the function is called with two expressions as arguments: student_name and student_age.
These expressions yield a value when evaluated: the value of the variables.

A: The function is called with two parameters. These parameters are the variables. And the function get the values of those variables and assign it in its local variable namely 'name' and 'age'.

A: Have you used console.log() method? Have you ever wondered what's the maximum number of parameters it takes? Answer is as many as it can.
Lets take an example.
function print(x,y){
  console.log(x);
  console.log(y);
}

Well this is an easy function, takes 2 arguments and print them in the console.
Lets say I have 5 parameters passed to function print. a,b,c,d,e. How would you modify the print method? May be something like this. (Don't write programs like this. It ain't effective).
function print(a,b,c,d,e){
  console.log(a);
  console.log(b);
  console.log(c);
  console.log(d);
  console.log(e);
}

How about if I pass 100 parameters like, a1, a2, ... a100. What if I pass 1000 parameters. You can't write 1000 console.log statements to print them. So you would think of a for loop to print all the parameters.
But wait!
How do I access all the parameters inside a for loop unless if they are an array (use for-loop or for-in to iterate) or an object (use for-in to iterate)?
Now comes the object "arguments". This is a built-in object implicitly created by javascript for every function you declare.
What does this store? It stores all the parameters you passed to the function in the form of object.
arguments {
0: a,
1: b,
2: c,
3: d,
4: e
};
Now I have something like an object that holds all the parameters passed to the function, it will be easier to access them in a for-in loop. Now my print method will look like:
function print(a,b,c,d,e,f) {
  for (var prop in arguments) {
    console.log(arguments[prop]);
  }
}

This will loop through all the properties of the arguments object and prints the value stored in each property.
What is stored in each property of argument object?
fn parameter    object-property   value stored in property
a                  0             value of parameter a
b                  1             value of parameter b
c                  2             value of parameter c
d                  3             value of parameter d
e                  4             value of parameter e
f                  5             value of parameter f

A: If I understood your question correctly, you want to know whether you should say

I called student with student_name and student_age.

or

I called student with "Divyansh" and 17.

right?
Well, that depends on the whole context, and sometimes it's possible to use both.
And this is to some extent a question of opinion, but I'll try to justify my opinion as good as I can.
I believe you should refer to the arguments by their names (i.e. student_name and student_age if

*

*their value is of no significance for what you're saying.
Unnecessary information usually leads to confusion.

*their value is unknown.

*their value is long and you previously mentioned it.
Long values such as Math.pow((5*x+7*y-35*v*x*z)/(42*m/35*k+47*f+99*l), 35*22*88*k) tend to make written text messy and are really annoying to speak out many times in a row, so you'll want to refer to them by name.

You should refer to the arguments by their value when their value matters, e.g. when you have a bug that only occurs when certain values are passed to your function, but not some others.
Now there is a gap between those, where I believe you can use both.
For that case, I'd apply the golden rule
As short as possible, but as long as required.
If you had the following code:
var name = "Divyansh";
console.log(name);
var name = "Marc";
console.log(name);
var name = "Jon Skeet";
console.log(name);

Then I believe all of the following statements are perfectly valid:

I called console.log three times with name as argument.

or

I called console.log three times with "Divyansh", "Marc" and "Jon Skeet" as argument.

But it really depends on how much information you need or want to give.

A: In your case you are passing two arguments named student_name and student_age to student function which contains value Divyansh and 17 respectively.


text:
Q: Loop Cards Flutter I have been researching Flutter and a question arose --
I have an array with some information, and I need to add cards based on this array.
Currently, I create a loop and add the cards which follow the structure of my array and my program listed below. Note that when I call statement passing the parameters, the code runs without any problem, but the following code does not work for me:

import "package:acessorias/pages/global.variables.dart";
import "package:flutter/material.dart";

class Comunicados extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Center(
          child: SizedBox(
            width: 150,
            child: Image.asset("assets/image/logo.png"),
          ),
        ),
        actions: <Widget>[
          Container(
            width: 60,
            child: FlatButton(
              child: Icon(
                Icons.search,
                color: Color(0xFFBABABA),
              ),
              onPressed: () => {},
            ),
          ),
        ],
      ),
      body: Container(
        color: Color(0xFFF2F3F6),
        child: ListView(
          children: <Widget>[
            comunicado(comunicados[0]["LogNome"], comunicados[0]["EmComDTH"],
                comunicados[0]["EmComDesc"]),
            comunicado(comunicados[1]["LogNome"], comunicados[1]["EmComDTH"],
                comunicados[1]["EmComDesc"]),
            comunicado(comunicados[2]["LogNome"], comunicados[2]["EmComDTH"],
                comunicados[2]["EmComDesc"]),
            comunicado(comunicados[3]["LogNome"], comunicados[3]["EmComDTH"],
                comunicados[3]["EmComDesc"]),
            comunicado(comunicados[4]["LogNome"], comunicados[4]["EmComDTH"],
                comunicados[4]["EmComDesc"]),
            comunicado(comunicados[5]["LogNome"], comunicados[5]["EmComDTH"],
                comunicados[5]["EmComDesc"])
          ],
        ),
      ),
    );
  }
}

Widget comunicado(user, data, msg) {
  return Card(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        ListTile(
          leading: CircleAvatar(
            backgroundImage: AssetImage("assets/image/foto.png"),
          ),
          title: new Text(user),
          subtitle: Text(data),
          trailing: Icon(Icons.more_vert),
        ),
        /*Container(
          child: Image.asset("assets/image/post.png"),
        ),*/
        Container(
          padding: EdgeInsets.all(10),
          child: Text(msg),
        ),
        ButtonTheme.bar(
          child: ButtonBar(
            children: <Widget>[
              FlatButton(
                child: Icon(Icons.favorite),
                onPressed: () {},
              ),
              FlatButton(
                child: Icon(Icons.share),
                onPressed: () {},
              ),
            ],
          ),
        ),
      ],
    ),
  );
}

Solution

body: ListView.builder(
        itemCount: comunicados.length,
        itemBuilder: (context, index) {
          /*return ListTile(
            title: Text('${comunicados[index]}'),
          );*/
          return comunicado(comunicados[index]['LogNome'],
              comunicados[index]["EmComDTH"], comunicados[index]["EmComDesc"]);
        },
      ),

A: You can use data model in another dart file like Comunicado.dart
class Comunicado{
  String user;
  String data;
  String msg;

  Comunicado(
      {this.user, this.data, this.msg});
}

after that you can make list of data model with the static data or etc like
List getComunicado(){
 return[
    Comunicado(
     user: comunicados[0]["LogNome"],
     data: comunicados[0]["EmComDTH"],
     msg: comunicados[0]["EmComDesc"],
   ),
    Comunicado(
     user: comunicados[1]["LogNome"],
     data: comunicados[1]["EmComDTH"],
     msg: comunicados[1]["EmComDesc"],
   ),
 ]
}

in my case, i put it into initial state and don't forget to declare comm
@override
  void initState() {
    super.initState();
    comm= getComunicado();
  }

for custom card
   Card makeCard(Comunicado newComm) => Card(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        ListTile(
          leading: CircleAvatar(
            backgroundImage: AssetImage("assets/image/foto.png"),
          ),
          title: new Text("${newComm.user}"),
          subtitle: Text("${newComm.data}"),
          trailing: Icon(Icons.more_vert),
        ),
        /*Container(
          child: Image.asset("assets/image/post.png"),
        ),*/
        Container(
          padding: EdgeInsets.all(10),
          child: Text("${newComm.msg}"),
        ),
        ButtonTheme.bar(
          child: ButtonBar(
            children: <Widget>[
              FlatButton(
                child: Icon(Icons.favorite),
                onPressed: () {},
              ),
              FlatButton(
                child: Icon(Icons.share),
                onPressed: () {},
              ),
            ],
          ),
        ),
      ],
    ),
  );

and for last you can call make card on listview
ListView.builder(
          scrollDirection: Axis.vertical,
          itemCount: comm.length,
          itemBuilder: (BuildContext context, int index) {
           return makeCard(comm[index]);
         },
      ),


text:
Q: How to determine if control center is dragged up I'm creating an app that responds to up and down gesture recognizers.  I've noticed that when I accidentally drag the control center up, my methods that respond to an up swipe/drag also get called.
I have a BOOL named recordCalled that is true when an up swipe is detected, if the BOOL is true when the app goes into resign, certain methods are suppose to get called that put the app in its default state.  The problem is that when I drag the control center up, I enter resign before  recordCalled becomes true.  Once I swipe down the control center, my app comes back to the active state.  How can I prevent any methods from firing while the app is in resign?
EDIT:I'm able to get around this issue by creating another BOOL that becomes TRUE when resign is called and all the proceeding methods require the BOOL to be false in order to proceed. Is there a better way of knowing when the control center is present?

*

*When I drag up both the control center this method gets called first.  Since none of the parameters are true, nothing happens.
-(void) appDidEnterResign:(NSNotification *)notification
{
    if(viewIsUp || recordCalled)
    {
        [self.panedView.layer removeAllAnimations];
        viewIsUp = NO;
        waitingTrackToSave = NO;
        [self moveViewsDown];
        [self onlyStopRecorder];
    }
}

*This method gets called immediately after resign but I still haven't entered the Active state.
- (IBAction)handleUpSwipe:(UISwipeGestureRecognizer *)recognizer
{

     recordCalled = YES;
    [self beginRecord];

}

*Followed by the following which calls the animation block to move the view up:
-(void) beginRecord
{
    if(viewIsUp == NO)
    {

    [UIView animateWithDuration:.25 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{

        [self moveViewsUp];

    } completion:^(BOOL finished){

    }];
}

-(void) moveViewsUp
{
    if(!viewIsUp)
    {
        self.panedView.frame = CGRectOffset(self.panedView.frame, 0, -274);
    }
}


text:
Q: "RdlCompile" task was not found I'm trying to compile and project with rldc file, and i'm getting one of two errors, either:

The "Microsoft.Reporting.RdlCompile" task could not be loaded from the assembly Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.  Confirm that the  declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

or:

The "RdlCompile" task was not found. Check the following: 1.) The name of the task in the project file is the same as the name of the task class. 2.) The task class is "public" and implements the Microsoft.Build.Framework.ITask interface. 3.) The task is correctly declared with  in the project file, or in the *.tasks files located in the "C:\Windows\Microsoft.NET\Framework\v4.0.30319" directory.

I'm using VS2010, and I've re-installed Reporting Viewer, made sure the target files and the task definition are correct, and even tried to copy the dll from another computer, and nothing worked.
Did anyone encounter this?
Thanks

A: Solved by copying the content of the folder:

[Program Files]\Microsoft Visual Studio 10.0\ReportViewer\

and the task declaration in the file:

[Program Files] \MSBuild\Microsoft\VisualStudio\v10.0\ReportingServices\Microsoft.ReportingServices.targets

from another computer.
For some reason re-installing doesn't work, but copying from a working machine does.


text:
Q: What's the differences between "The Improper Princess" and "Dealing with Dragons"? Patricia C. Wrede's Enchanted Forest Chronicles started as "The Improper Princess" from Spaceships and Spells of 1987, before it was expanded into Dealing with Dragons three years later.
What changed between those versions, beyond just getting longer?


text:
Q: unable to set the onAction property of the button class error I am trying to assign a function to a button. This seems to work sometimes and sometimes I get the error "unable to set the onAction property of the button class"
Windows("MyFile.XLS").Activate
    Sheets("Sheet1").Select
    Range("G12").Select
    ActiveSheet.Buttons.Add(306, 36.6, 94.8, 21).Select
    Selection.OnAction = "'SomeFile.xls'!PrintWorkbook.PrintWorkbook"
    Selection.Characters.Text = "Print Workbook"
    With Selection.Characters(Start:=1, Length:=14).Font
        .Name = "Times New Roman"
        .FontStyle = "Bold"
        .Size = 10
    End With

I get the error on this line "Selection.OnAction = "'SomeFile.xls'!PrintWorkbook.PrintWorkbook"". Not sure why this only happens sometimes and works other times.

A: Your code assumes that the button is selected after a call to ActiveSheet.Buttons.Add and that the selection succeeded.
You should use the return value of the ActiveSheet.Buttons.Add as shown below:
Windows("MyFile.XLS").Activate
    Sheets("Sheet1").Select
        Range("G12").Select
        Set Button = ActiveSheet.Buttons.Add(306, 36.6, 94.8, 21)
        Button.OnAction = "'SomeFile.xls'!PrintWorkbook.PrintWorkbook"
        Button.Characters.Text = "Print Workbook"
        With Button.Characters(Start:=1, Length:=14).Font
            .Name = "Times New Roman"
            .FontStyle = "Bold"
            .Size = 10
        End With


text:
Q: In DDD are Value Object always at the leaves of a relationship tree? If I have a photo album where each Photo can be commented on, Should the Comments be Entities or Value Object in these cases:

*

*Comments can be added only anonymously (i.e. Comments have no relation to anything except the photo).

*Comments can be added by registered users (i.e. there will be a relation between the Comment and User entity).

*Comments can have comments (i.e. 1 user replying to another).

I think modeling a Comment as Value Object in the first case sounds reasonable as a Comment won't have any relationships with any other entities.
However, what about the 2nd and 3rd case? Does the need to identify which user Posted which Comment changes it from a Value Object into Entity?

A: Here are two excellent posts on how to identify what is a value object and what is an entity. I know that when I am stuck on which to use, I always give these articles a read.
To help you chose which one to use, think about the lifecycle of the Comments object.
Value Object

"An object that represents a descriptive aspect of the domain with no conceptual identity is called a VALUE OBJECT. VALUE OBJECTS are instantiated to represent elements of the design that we care about only for what they are, not who or which they are." [Evans 2003]

Entity

"An ENTITY is anything that has continuity through a life cycle and distinctions independent of attributes that are important to the application's user." [Evans 2003]

After reading the articles, in particular the Value Objects one, and the story about identifying a child, ask yourself:

*

*Can a comment exist without a Photo??

*If all entities are unique, what would make a unique Comment?

*Value Objects are immutable, if I change a comment, how does that impact a Value Object Comment?

A: Gibson's links are useful, but the short answer is:

Comments are not value objects, in any of the listed scenarios.

You might model comments on a photo in Scenario 1 as an attribute of a photo containing a collection of strings, in which case you don't need an 'object' for them at all.
In the other two scenarios, the relationships require an identity for a comment, which makes Comment an entity.

A: To elaborate on Steven's answer.
Comments are an entity in this case not value objects.
Two value objects are considered to be the same if their attributes can define their equality. In your case let say, If their are two comments with the exact same text in them and posted by the same user, Will those two comments be the same object? I think the answer is NO. It is possible for a user to add a new comment with the same text as the earlier comment.
Hence there must be some other identifier which distinguishes between these two comments other than their attributes making it an entity.
One other example would be if two different photos have similar text/user comments, Even then those comments should have two separate identities.
Hence ENTITY :)


text:
Q: Will I get leavers penalty, even after rejoining the same game? I usually play with my friends in a group, and it can happen that i'm either quickly afk or get a disconnect due to my router spasing out. My question is, does that "leave" still count as one if i rejoin the same game (through either a group invite from a friend or manually joining)?

A: Yes, as soon as you leave you get the penalty, regardless of if you rejoin.


text:
Q: Can an unpowered 2.4 GHz transceiver exist? I just read an internal presentation from the company I work for announcing the release of a small consumer device with an embedded RFID tag and 2.4 GHz transceiver. The presentation made note of the fact that the device does not need to be turned on or off. I am assuming that means the device is unpowered, but I'm wondering about the feasibility of an unpowered transceiver.
Does such a transceiver exist (I could be wrong about it not needing a battery)? How much data could such a low-powered/unpowered transceiver transmit? Could it be used to fix a location within a wifi network?

A: It's probably passively powered.  RFID tags can have processors that are powered entirely by the energy derived from the RF signal used to query the tag.  The tag/processor combo can only function when the RF signal is present or if it stores energy from the RF signal then as long as that lasts.  Otherwise it just shuts down.  Typically it transmits its unique ID and possibly a small amount of other data.


text:
Q: Как выделить активную ссылку в меню другим цветом при нажатии? Подскажите как выделить активную ссылку в меню другим цветом при нажатии? Есть меню в html на странице следующего вида:

$(document).ready(function() {
  $('#main_menu ul.menu_other_page li').on('click', function() {
    $('#main_menu ul.menu_other_page li a span').removeClass('parent'); //заберет актив у всех ссылок
    $(this).addClass('act'); //присвоит нужной
  });
});
.act {
  color: green !important;
}

      Двери

      Окна

      Освещение

      Мебель

Но js код не работает, активная ссылка должна быть зеленого цвета

A: Есть много способов.
Определять ссылку, передавать ссылку.. Что удобнее.
Я как-то делал вот такое:

$(document).ready(function(){
  let thisPage = location.href; // Получаем ссылку.
  thisPage = 'http://www.site.com/link3'; // Т.к. код работает в сниппете, то "эмулируем" ссылку.
  thisPage = thisPage.replace(/http:\/\/www.site.com/g, ''); // Удаляем домен, оставив только саму страницу.
  $('.nav a').each(function(){ // Пробегаем по всем ссылкам в меню
    let thisHref = $(this).attr('href'); // Получаем ссылку
    if(thisHref == thisPage) $(this).addClass('active'); // если совпадает с текущей ссылкой, то вешаем класс active
  });
});
ul {padding: 0; margin: 0;}
li {display: inline-block; background: #ddd;}
a.active {background: green; color: white;}

    Link 1

    Link 2

    Link 3

    Link 4

    Link 5


text:
Q: Using native C static libraries in Delphi Firemonkey iOS development I am interested in using Firemonkey for producing an iOS app. There are several native C libraries I would like to use in this application. I know that iOS does not allow for dynamic link libraries, but is there a way to use static libraries in this firemonkey iOS app?

A: Yes, you can use C static libraries to link with Firemonkey iOS appli using xcode.
I did it using Xcode outside RADStudio X2. With RADStudio I generated xcode project. On the mac I openned the xcode project and added :
function C_func(double :x):double; cdecl; external;

{$linklib my_c_lib.a}

I created static library project in xcode (named my_c_lib) with one C file containing :
double C_func(double x)
{
    return x+2.5;
}

I suppose that in the same manner you can use already compiled static libs.

A: Here is an iOS application I made:
Unit1.pas is generated by XE2:
unit Unit1;

interface

uses
  SysUtils, Types, UITypes, Classes, Variants, FMX_Types, FMX_Controls, FMX_Forms,
  FMX_Dialogs, FMXTee_Engine, FMXTee_Series, FMXTee_Procs, FMXTee_Chart,
  FMX_ExtCtrls;

type
  TForm1 = class(TForm)
    CornerButton1: TCornerButton;
    Chart1: TChart;
    Series1: TLineSeries;
    Label1: TLabel;

    procedure CornerButton1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    x : double; // I added this in Xcode Editor
  end;

// I added this declaration
function tst_function(x:double):double;cdecl;external;
var
  Form1: TForm1;

implementation

{$R *.lfm}
{$link tst1.o} // I added this

procedure TForm1.CornerButton1Click(Sender: TObject);
var      i: integer; x : double;
begin
for  i := 1  to  500  do
begin
x:=tst_function(i*3.14/250.0);
Series2.Add(x);

end

end;

end.

and the C file tst1.c is:
#include <stdio.h>
#include <math.h>

double tst_function(double x)
{
    return sin(x)+0.25;
}


text:
Q: Pymongo cannot connect to remote database when in virtual environment So I am trying to connect to remote MongoDB database using pymongo but it fails to connect when the script is run in virtual environment. It can connect to local db in venv, as well as it connects when its not run inside virtual enviroment. I wonder why it fails only in virutalenv. Both globally and on venv im using pymongo version 3.6.0.
My code:
from pymongo import MongoClient
from config import *

mongo=os.environ["mongodb"]
try:
    #local test
    #conn = MongoClient()
    #production
    conn = MongoClient(mongo)

    print("Connected successfully!!!")
except:
    print("Could not connect to MongoDB")


text:
Q: C# Format exception I have 2 tables Conturi and Persoana and I want to show every single item that Cont has(I can't use a ListView) while doing this I run into a little problem.
The table looks like this:
[Cont]:
        - id (cheie primara)
        - id_persoana (cheie externa in [Persoana])
        - Banca (sir de caractere maxim 64)
        - Sold (decimal)
        - Unitate (moneda, sir de caracatere de lungime 3)
        - Data_deschiderii (data)

I am having trouble figuring out where my format exception is this is the code :
namespace TarnaLucianFlorinGrupa333
{
    public partial class Conturi : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string query = GetQuery();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            conn.Open();
            SqlCommand cmd = new SqlCommand(query, conn);
            SqlDataReader reader = cmd.ExecuteReader();
            FillTable(reader);
            conn.Close();
        }

        private string GetQuery()
        {
            string query = string.Empty;
            if (string.IsNullOrEmpty(TextBox1.Text))
            {
                query = string.Format("select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where c.Sold>={0} and p.Id = c.id_persoana", Convert.ToInt32(TextBox1.Text));
            }

            else
            {
                query = "select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where p.Id = c.id_persoana";
            }

            return query;
        }

        private void FillTable(SqlDataReader reader)
        {
            TableRow th = Table1.Rows[0];
            Table1.Rows.Clear();
            Table1.Rows.Add(th);

            while (reader.Read())
            {
                TableRow row = new TableRow();

                TableCell nume = new TableCell();
                nume.Text = reader.GetValue(1).ToString();
                row.Cells.Add(nume);

                TableCell Banca = new TableCell();
                Banca.Text = reader.GetValue(2).ToString();
                row.Cells.Add(Banca);

                TableCell Sold = new TableCell();
                Sold.Text = reader.GetValue(3).ToString();
                row.Cells.Add(Sold);

                TableCell Unitate = new TableCell();
                Unitate.Text = reader.GetValue(4).ToString();
                row.Cells.Add(Unitate);

                TableCell Data_Deschiderii = new TableCell();
                Data_Deschiderii.Text = reader.GetValue(5).ToString();
                row.Cells.Add(Data_Deschiderii);

                TableCell Adauga = new TableCell();
                Adauga.Text = string.Format(" Adauga ", reader.GetValue(0).ToString());
                row.Cells.Add(Adauga);

                Table1.Rows.Add(row);
            }
        }
        protected void Button2_Click(object sender, EventArgs e) { }

    }
}

And this is the view:

         Soldul

            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

              <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Cauta" />

            <asp:Table ID="Table1" runat="server">
                <asp:TableHeaderRow BackColor=Aqua>
                    <asp:TableHeaderCell> nume </asp:TableHeaderCell>
                    <asp:TableHeaderCell> Banca </asp:TableHeaderCell>
                    <asp:TableHeaderCell> Sold </asp:TableHeaderCell>
                    <asp:TableHeaderCell> Unitate </asp:TableHeaderCell>
                    <asp:TableHeaderCell> Data_Deschidere</asp:TableHeaderCell>
                    <asp:TableHeaderCell> Adauga</asp:TableHeaderCell>
                </asp:TableHeaderRow>
            </asp:Table>

The error that it throws me is :

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: Input string was not in a correct format.

Could someone point me where this error is from ?

A: may be you have to to
 if (!string.IsNullOrEmpty(TextBox1.Text))
            {
                query = string.Format("select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where c.Sold>={0} and p.Id = c.id_persoana", Convert.ToInt32(TextBox1.Text));
            }

seems you trying to convert to int when the textbox is empty

A: Switch the string.IsNullOrEmtpy() with int.TryParse(string, out int) which returns true if the value was parsed. (or just stick to string.IsNullOrEmpty() if you don't want/need parsing)
    private string GetQuery()
    {
        string query = string.Empty;
        int value = -1;
        if (int.TryParse(TextBox1.Text, out value))
        {
            query = string.Format("select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where c.Sold>={0} and p.Id = c.id_persoana", value);
        }

        else
        {
            query = "select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where p.Id = c.id_persoana";
        }

        return query;
    }

As a side note you should look into parameterized queries rather than using string.Format() or even manual string concatenation.
Parameterized version:
protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        SqlCommand cmd = GetQuery();
        cmd.Connection = conn;
        cmd.Connection.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        FillTable(reader);
        cmd.Connection.Close();
    }

    private SqlCommand GetQuery()
    {
        SqlCommand cmd = new SqlCommand();

        int value = -1;
        if (int.TryParse(TextBox1.Text, out value))
        {
            cmd.CommandText = "select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where c.Sold>=@Sold and p.Id = c.id_persoana";
            cmd.Parameters.Add(new SqlParameter("@Sold", value));
        }

        else
        {
            cmd.CommandText = "select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where p.Id = c.id_persoana";
        }

        return cmd;
    }

A: Use TryParse instead of this line. If the text in textbox is not a number, you will get FormatException.
Convert.ToInt32(TextBox1.Text)

A:
You have placed wrong check for textbox. You are checking that if
  value of TextBox1 is NULL or Empty than convert it to int32 so how a
  null or empty value can be converted to int32.

Also make sure than integer value is being written in this textbox. Change it like this
if (!string.IsNullOrEmpty(TextBox1.Text))
{
query = string.Format("select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where c.Sold>={0} and p.Id = c.id_persoana", Convert.ToInt32(TextBox1.Text));

}
else
 {
query = "select c.id,p.Nume, c.Banca,c.Sold,c.Unitate,c.Data_Deschiderii from Cont c,Persoana p where p.Id = c.id_persoana";
}


text:
Q: How to pass custom data-attribute to styled component? I have this Styled component, where I'm trying to pass DATA-attribute which is coming from props to it. (This is the solution we have on Stack Overflow)
export const InlineEditReadViewErrorContainer = styled.div.attrs(props => ({
  'data-cy': props.dataCy
}))`
  border: 2px solid #de350b;
  border-radius: 3px;
`;

This is how I use this styled component in code
 <InlineEditReadViewErrorContainer dataCy='blabla'>
   {readView}
 </InlineEditReadViewErrorContainer>

But this is doesn't change anything

A: I think that we must use correctly the attributes that are added to a component in React and more if they are needed only to style a component.
We should use as many native properties as possible but without compromising the private data that would be exposed in the HTML that the client displays in broser, therefore:

*

*If you are going to use data-attributes:

Remember how to name these attributes:
The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
Note: I would just use the simplest possible, with booleans to give a set of properties as the first answer described, for example:
component.js
<Error data-active={true}>
   {readView}
</Error>

component.styles.js
export const Error = styled.div`
  &[data-active="true"] {
    border: 2px solid #de350b;
    border-radius: 3px;
  }
`;

*

*If you want to use custom props without them being displayed in the DOM as the second comment has described, using transient props:

For sample:
component.js
<Error $active={true}>
   {readView}
</Error>

component.styles.js
export const Error = styled.div`
  ${({$active}) => $active ? css`
     border: 2px solid #de350b;
     border-radius: 3px;
  `: null}
`;

A: The prop should already be "passed" in the sense that it will show up on the component for the purposes of using it in Cypress. If you want to use it internally you could also use transient props such as this
const Comp = styled.div`
  color: ${props =>
    props.$draggable || 'black'};
`;

render(
  <Comp $draggable="red" draggable="true">
    Drag me!
  </Comp>
);

A: It was much easier. You can pass the data attribute directly where you use the styled component and everything will be fine.
<InlineEditReadViewErrorContainer data-cy='dateInput'>
 {textValue}
</InlineEditReadViewErrorContainer>

A: Maybe it's related to your bundler, since you should be able to pass a data attribute to a styled-component directly. However, if you're extending an existing component, be aware that you need to pass it through props. Those two situations will attach the data attribute to the final HTML:
function Text(props) {
  return (

      {props.children}

  );
}

const StyledText = styled(Text)`
  color: blueviolet;
`;

const StyledHeading = styled.h1`
  color: gray;
`;

export default function App() {
  return (

  );
}


text:
Q: How to decode password save with md5() in mysql db I have very simple query .
I am fetching user name and password from a Mysql DB using php.
The password is in md5() encoded. Can any one help me out
script
while($rfg=mysql_fetch_array($rc)){
            //print_r($rfg);
              echo $_POST['im_password'] = $rfg['Password'];
              echo $_POST['im_user'] = $rfg['Nombre'];

        }

how I can decode the md5 password to real text in php ??
Thanks in Advance

A: The point of using md5 is that you CANT decrypt it that easely. You could for example use it to compare md5(user_input) with the hash in the database (login system).
If you really need to get a plain-text (which I dont support) you could try using dictionary-attacks. Everything beside that (bruteforcing) wouldnt be worth it according to the needed calculation power.

A: MD5 can't be decoded unless you are using rainbow tables.
The way to check if a user entered a correct password is to hash his entered password with md5 and check it with the password in the database.


text:
Q: Click vs Input vs Change for checkboxes? I have a form. I want to only allow form submit if the user checks precisely 4 out of 8 available checkboxes; and once the user checks 4 checkboxes I want to disable the remaining unchecked ones.
Should I add a hook to the click event? Or maybe the input event? Or perhaps the change event?
I'm overwhelemed by the amount of events that seem to duplicate each other's functionality.
I'm also confused by the documentation.
MDN docs about input:

For <input> elements with type=checkbox or type=radio, the input event should fire whenever a user toggles the control, per the HTML5 specification. However, historically this has not always been the case. Check compatibility, or use the change event instead for elements of these types.

MDN docs about change:

Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

And below:

Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

*

*When the element is :checked (by clicking or using the keyboard) for <input type="radio"> and <input type="checkbox">;

MDN docs about click:

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.

Practice:
The below JS fiddle seems to hint that all 3 events are equivalent. Clicking the checkbox, clicking the label, focusing the checkbox and pressing space on keyboard seem to all fire all three events.

const checkbox = document.querySelector('input[type=checkbox]');
for (const event of ['input', 'click', 'change']) {
  checkbox.addEventListener(event, () => {
    log.textContent = `${event}\n${log.textContent}`
  })
}
Toggle <input type="checkbox" name="" id="">

As per the docs change and input seem equivalent; click does not seem equivalent to the other 3 as per the docs but in practice it seems equivalent.
Do we really have 3 events that duplicate each other's functionality? Does it matter in any way which event I use?
Or am I missing something?

A: These 3 events duplicate each other's functionality because you are looking at a checkbox which happens to be a special case.
For example, if you were to take a text field

*

*The event input will fire whenever the text in an element is changed using the user interface.

*The event change will fire (on most browsers) whenever the text element loses focus. It would only be triggered once instead of after every keystroke.

*The event click will fire whenever a user clicks on the text field.

If we were to apply this to checkboxes (keeping in mind there is only one thing a checkbox can be changes into: either checked => unchecked orunchecked => checked)

*

*The event input will fire whenever the checked state is changed using user interface.

*The event change will fire whenever the checked state has changed
in an element (or when the checkbox loses focus in IE).

*The event click will fire after the check state has finished changing .

The 3 events have very similar functionality (almost duplicates) because they are all trying to do something different that functionally does the same thing on checkboxes. The only differences being subtle implementation details.
I would use click to avoid having issues from the user of diffrent browsers.

A: They are not duplicated.  There are subtle differences.
change happens once the value or state changes, and the element loses focus.

$('input').on('change', function(){
  console.log('changed');
});

<input type="checkbox" value="1">
<input type="text">

click happens once the element is clicked.
input happens IMMEDIATELY once the value or state changes, before it loses focus.  This happens regardless of if the state changes as per a mouse or keyboard event.  A checkbox can change state by clicking it, or focusing on it and hitting the spacebar.  A click event would not catch the spacebar state change.

$('input').on('change', function(){
  console.log('changed');
});

$('input').on('input', function(){
  console.log('input');
});

<input type="checkbox" value="1">
<input type="text">

To test the lack of focus change and the spacebar change on the checkbox, you can click the input box and then shift+tab to focus the checkbox to hit spacebar.  It appears from the fiddle that for checkboxes, the change and input events both happen any time it changes, even without the focus being lost.
This differs from how the text field behaves.  So there appears to be some behavioral differences between the two elements in when the events are generated.  The checkboxes appear to follow a less strict implementation of the pattern, as opposed to input boxes.


text:
Q: Python Getting job game I am currently working on a Python game influenced by DankMemer Bot on Discord! I am having trouble with getting jobs in the game. The job list is
au = 'Author'
de = 'Designer'
pr = 'Programmer'
do = 'Doctor'
job_list = [au, de, pr, do]

I made a getting job function so the way if the player typed !gj (short for getting a job) in the text game.
elif chat == '!gj':
    player_job = player_job_get(job_list, player_job, player_level)
    print(player_job)

I did
print(player_job)

To check if the command was running ok. The
player_job_get(job_list, player_job, player_level)

Function is defined as
def player_job_get(job_list, player_job, player_level):
    print('Available jobs :')
    for i,job in enumerate(job_list, 1):
        print(i, job)
    job_chose = input('What job number do you want? ("q" to exit)\n')
    if job_chose == 'q':
        return player_job
    try:
        job_chose = int(job_chose)
    except ValueError:
        print('Please use the number next to the job')
        return player_job

    if job_chose <= len(job_list):
        if player_job == None:
            player_job = job

            return player_job
        else:
            print('You already have a job!')
            retire = input('Would you like to retire from your current job?  y/n\n')
            if retire == 'y':
                player_job = None
                player_job = job
                return player_job
            elif retire == 'n':
                print('Sorry you can only have 1 job at a time!')
                return player_job
            else:
                print('y or n please!')
                return player_job
    else:
        print('Please use the number next to the job')
        return player_job

But when I run the function it works perfectly fine

until I type the number that is next to the job.

If I typed 1, it should print
Author

But No matter what I put in, It just says the doctor. Why does it do that?
The full code is below
import random
import sys
import time

player_total_work = 0
player_earn_work = 0
player_work_exp = 0
player_work_max = 100
player_job = None
au = 'Author'
de = 'Designer'
pr = 'Programmer'
do = 'Doctor'
job_list = [au, de, pr, do]

player_level = 1

command_list_ = ['!gj [Get a job]','!w [work]', '!f [fish (if you have a fishing rod in your inventory)]', '!h [hunt (if you have a hunting rifle in your inventory)]', '!bj [blackjack (gamble)]', '!sl [slots (gamble)]', '!ro [roll (gamble)]', '!sh [the shop]', '!cy [Company]', '!inv [inventory]', '!bal [currency]', '!profile [stats, money, name.. etc]', ]

def command_list(command_list_):
    for i,command in enumerate(command_list_, 1):
        print(i, command)

def player_job_get(job_list, player_job, player_level):
    print('Available jobs :')
    for i,job in enumerate(job_list, 1):
        print(i, job)
    job_chose = input('What job number do you want? ("q" to exit)\n')
    if job_chose == 'q':
        return player_job
    try:
        job_chose = int(job_chose)
    except ValueError:
        print('Please use the number next to the job')
        return player_job

    if job_chose <= len(job_list):
        if player_job == None:
            player_job = job

            return player_job
        else:
            print('You already have a job!')
            retire = input('Would you like to retire from your current job?  y/n\n')
            if retire == 'y':
                player_job = None
                player_job = job
                return player_job
            elif retire == 'n':
                print('Sorry you can only have 1 job at a time!')
                return player_job
            else:
                print('y or n please!')
                return player_job
    else:
        print('Please use the number next to the job')
        return player_job

def game(player_job):
    while True:
        chat = input('!c for commands list\n')
        if chat == '!c':
            command_list(command_list_)

        elif chat == '!gj':
            player_job = player_job_get(job_list, player_job, player_level)
            print(player_job)

        else:
            pass

game(player_job)

A: In this snippet:
if job_chose <= len(job_list):
        if player_job == None:
            player_job = job

What do you expect job to be when the flow of execution reaches player_job = job? What was the last value stored in job before you reached this line?


text:
Q: Summernote table with more styling Is there any workaround to get more styling - bordered,header,stripped for the bootstrap table that summernote use ?
I have seen a form from summernote named MaterialNote have the table that I am after.

I have figured how table classes can be passed as summernote option :
$('textarea').summernote({
        tableClassName: 'table table-striped '
    });

A: I guess that you need customise your template.
please open document summernote.js
and search this code:
    var $table = $('
' + trHTML + '
');

enter your css class in this point.
var $table = $('
' + trHTML + '
');

and edit your css file:
.teste
{

}

I hope it helped


text:
Q: Content not being found on my DEV web server when it is in fact actually there I'm having an issue trying to resolve references in my masterpage.
As you can see by the accompanying screen shot, the issues state that the files cannot be found.
But after checking the corresponding filepath that says where it can't be found, it is indeed physically there. I checked out the properties of the files to see if there was anything out of the ordinary, but is not.
Can someone please help me determine why these files cannot be found on my IIS server?


text:
Q: Combine two dataframes meeting conditional criteria in R I have dataframe A which have events in time and dataframe B with event ranges for patients.  I want to only include rows from dataframe A if the events in time are not between the date ranges of dataframe B.  If there is a patient from dataframe A that doesn't exist in dataframe B, then add the events to dataframe B.
Since the dataframes are not identical, rows added to dataframe B from dataframe A should add rows where date = start and date = end.
I was trying to figure out how to get this to work with dplyr but it seems complicated.  I managed to get it to work with a for-loop but for my education I was wondering how other people might accomplish the same task
dfa <- data.frame(
    date = c("2021-01-01", "2021-02-02", "2021-02-05"),
    patient = c("one", "two", "three"))
dfb <- data.frame(
    start = c("2020-12-31", "2021-02-01"),
    end = c("2021-01-02", "2021-02-03"),
    patient = c("one", "one"))

dfa$date <- as.Date(dfa$date, "%Y-%m-%d")
dfb$start <- as.Date(dfb$start, "%Y-%m-%d")
dfb$end <- as.Date(dfb$end, "%Y-%m-%d")

for (i in 1:nrow(dfa)) {
  date <- dfa[i, "date"]
  d_patient <- dfa[i, "patient"]
  res <- dfb[d_patient == dfb$patient &
            date >= dfb$start &
            date <= dfb$end,]

  if (nrow(res) == 0) {
    tf <- data.frame("start" = date,
                     "end" = date,
                     "patient" = d_patient)
    dfb <- rbind(dfb, tf)
  }
}

print(dfb)

Results:
       start        end patient
1 2020-12-31 2021-01-02     one
2 2021-02-01 2021-02-03     one
3 2021-02-02 2021-02-02     two
4 2021-02-05 2021-02-05   three

A: dfa <- data.frame(
  date = c("2021-01-01", "2021-02-02", "2021-02-05"),
  patient = c("one", "two", "three"))

dfb <- data.frame(
  start = c("2020-12-31", "2021-02-01"),
  end = c("2021-01-02", "2021-02-03"),
  patient = c("one", "one"))

dfa$date <- as.Date(dfa$date, "%Y-%m-%d")
dfb$start <- as.Date(dfb$start, "%Y-%m-%d")
dfb$end <- as.Date(dfb$end, "%Y-%m-%d")

dfa
#>         date patient
#> 1 2021-01-01     one
#> 2 2021-02-02     two
#> 3 2021-02-05   three
dfb
#>        start        end patient
#> 1 2020-12-31 2021-01-02     one
#> 2 2021-02-01 2021-02-03     one

library(tidyverse)
library(fuzzyjoin)

fuzzy_anti_join(
  x = dfa,
  y = dfb,
  by = c("patient", "date" = "start", "date" = "end"),
  match_fun = list(`==`, `>=`, `<=`)
  ) %>%
  transmute(patient, start = date, end = date) %>%
  bind_rows(dfb)
#>   patient      start        end
#> 1     two 2021-02-02 2021-02-02
#> 2   three 2021-02-05 2021-02-05
#> 3     one 2020-12-31 2021-01-02
#> 4     one 2021-02-01 2021-02-03

Created on 2022-01-22 by the reprex package (v2.0.1)
data.table
library(magrittr)
library(data.table)

setDT(dfa)
setDT(dfb)

tmp <- dfa[!dfb, on = list(patient, date >= start, date <= end)] %>%
  .[, `:=`(start = date, end = date, date = NULL)]

l <- list(tmp, dfb)

rbindlist(l = l, use.names = TRUE)
#>    patient      start        end
#> 1:     two 2021-02-02 2021-02-02
#> 2:   three 2021-02-05 2021-02-05
#> 3:     one 2020-12-31 2021-01-02
#> 4:     one 2021-02-01 2021-02-03

Created on 2022-01-22 by the reprex package (v2.0.1)


text:
Q: Keep business logic saving related models in Data Model using $beforeInsert or not? Let's assume i have two Models in Objection Books and Chapters . What i want to achieve is before inserting Book to DB to save 1 default entry on Chapters table and return the creates chapter.id and save it to Books.
What is the best approach  ?
What i do now is Using the $beforeInsert hooks and save first the Chapter record and then create the book (i describe it below on the code ).
But this i think may raise issues in the case of the last query fails and in general is a bad practise adding bussiness logic in the Data Model. i was thinking creating  BookServices which will include functions like CreateNewBook where i will have trasanctions doing all the inserts and logic to the Db. So then i can use those BookServices in whatever controller need that logic.
What do you think is the best approach on that ?
Should i couple this logic to the model Layer or move it on Services Layer ?
What i do right now is :
Controller -- createBook.js
const book = require('Book')

createBook : () => {

     const newBook = new Book({title: "My Title", chapters: [], author: "My Author"})
     newBook.save()

}

Model  --  Book.js
const Chapter = require('Chapter')
const { Model } = require('objection');

class Book extends Model {
  static get tableName() {
    return 'books';
  }

  $beforeInsert() {
    super.$beforeInsert()
    const newChapter = new Chapter({title: 'FrontMatter'})
    const savedChapter = newChapter.save()
    this.chapters.push(savedChapter.id)
  }

}

module.exports = Book;


text:
Q: Port forward on router logic After port forwarded in the router, does it mean that the port is opened even I didn't use it? From my current situation, the port is closed while I am not using it. But what can trigger the port to be open?
Shutdown my port forwarded PC will turn off the port too?
My actual problem now:
I port forwarded a port, and the port is closed when I did not open any application that uses the port. I want to know why.

A: Setting a piece of networking infrastructure (your router) cannot force a PC to open a port. Think about what opening a port actually means: There is some program (or OS) that opens the port and listens to it. How can the router force the PC to do this?


text:
Q: Will get_bloginfo('url') return URL with backslash? Based on my test, get_bloginfo('url') will not return backslash, so it will return URL like this:
https://www.example.com/blogs

In this post What is difference between get_bloginfo('url') and get_site_url()?, it is said get_bloginfo('url') calls home_url().
And, in this post https://stackoverflow.com/questions/31086865/why-does-the-trailing-slash-appear-after-url-when-using-home-url-in-wordpress, it is said home_url() will return URL with backslash.
So, I am confused. Anyway, I want to find a function to return URL with backslash.

A: The Codex example for home_url() says you want home_url( '/' ) to get the blog's URL with a trailing slash.
Alternatively you could use trailingslashit( home_url() ). That may be safer if your site's home option somehow ends up stored with a trailing slash, since it looks like get_home_url() assumes it isn't, but that ought not happen.

A:
it is said get_bloginfo('url') calls home_url().

Correct, as can be read in the source code:
    case 'url':
        $output = home_url();
        break;

it is said home_url() will return URL with backslash

Wrong. In the docu it says, that home_url() will return the "[h]ome URL link with optional path appended" (emphasis mine).

If you want the home URL to always have the trailing slash, you can use the home_url filter, because under the hood, home_url() will use get_home_url():
add_filter('home_url', function (string $url): string {
    // already has trailing slash
    if (substr($url, -1) === '/') {
        return $url;
    }

    // add trailing slash
    return $url . '/';
}, 10);

(or much less readable but a one-liner)
// force trailing slash
add_filter('home_url', fn (string $url): string => $url . (substr($url, -1) !== '/' ? '/' : ''), 10);

However, this might break some existing implementations, that rely on home_url() not returning the trailing slash, so use at your own risk!