This amazingly worked.
/etc/init.d/mysql stop
service mysql stop
killall -KILL mysql mysqld_safe mysqld
/etc/init.d/mysql start
service mysql start
Use the below Steps to reset the password.
$ sudo systemctl start mysqld
Reset the MySql server root password.
$sudo grep 'temporary password' /var/log/mysqld.log
Output Something like-:
10.744785Z 1 [Note] A temporary password is generated for root@localhost: o!5y,oJGALQa
Use the above password during reset mysql_secure_installation process.
<pre>
$ sudo mysql_secure_installation
</pre>
Securing the MySQL server deployment.
Enter password for user root:
You have successfully reset the root password of MySql Server. Use the below command to check the mysql server connecting or not.
$ mysql -u root -p
http://gotechnies.com/install-latest-mysql-5-7-rhelcentos-7/
mysql -u root -P 4406 -h localhost --protocol=tcp -p
Remember to change the user, port and host so that it matches your configurations. The -p flag is required if your database user is configured with a password
Go to system preferences, then "MySQL". Click on "Start MySQL Server".
Just to add my configuration to the mix, I'm using MySQL 5.7.8 which has the same strict sql_mode rules by default.
I finally figured the following working in my /etc/mysql/my.conf:
[mysqld]
sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"
i.e. dash, not underscore and quotes around the value.
I have NO other my.conf files other than /etc/mysql/my.conf
There are some extra config includes being loaded from /etc/mysql/conf.d/ but they are blank.
And that seems to work for me.
Bind-address XXX.XX.XX.XXX in /etc/my.cnf
comment line:
or
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
quit;
add firewall rule:
iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT
On my CentOS 6 I have two openssl.cnf :
/openvpn/easy-rsa/
/pki/tls/
just remove:
Alias /phpmyadmin "C:/xampp2/phpMyAdmin/"
<Directory "C:/xampp2/phpMyAdmin">
AllowOverride AuthConfig
Require all granted
</Directory>
and remove phpmyadmin from:
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|server-status|server-info))">
If you get this when using DevDesktop - just restart DevDesktop!
First I created the user using :
CREATE user user@localhost IDENTIFIED BY 'password_txt';
After Googling and seeing this, I updated user's password using :
SET PASSWORD FOR 'user'@'localhost' = PASSWORD('password_txt');
and I could connect afterward.
$mysql -u root --host=127.0.0.1 -p
mysql>use mysql
mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';
mysql>FLUSH PRIVILEGES;
mysql> SELECT host FROM mysql.user WHERE User = 'root';
When you use Apache with mod_php apache is enforced in prefork
mode, and not worker
. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).
So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :
StartServers 20
MinSpareServers 5
MaxSpareServers 10
MaxClients 1024
MaxRequestsPerChild 0
This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.
See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.
Now you set 1024
MaxClients
. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.
So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:
<IfModule prefork.c>
StartServers 12
MinSpareServers 12
MaxSpareServers 12
MaxClients 12
MaxRequestsPerChild 300
</IfModule>
That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300
means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).ListenBacklog
queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe
And yes, that means you cannot handle more than 12 parallel requests.
If you want to handle more requests:
If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?
And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.
Update: About internal dummy connections (if it's your problem, but maybe not).
Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.
If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]
Update:
Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.
Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l
or apache2 -l
on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:
<IfModule worker.c>
StartServers 3
MaxClients 500
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:
<IfModule worker.c>
StartServers 2
MaxClients 250
MinSpareThreads 50
MaxSpareThreads 150
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
Step 1 : Close Xampp controller completely
Step 2 : Open C:\xampp\mysql\backup
Step 3 : Copy all the files from backup folder
Step 4 : Open C:\xampp\mysql\data
Step 5 : Paste the all the files in data folder
Step 6 : Re-start the Xampp controller
give the read / write permission to the IIS user or group users
Start -> run -> inetmgr
enable the ASP.NET authentication for your default website
3. For 64-bit (x64), create this folder: C:\Windows\SysWOW64\config\systemprofile\Desktop
For 32-bit (x86), create this folder: C:\Windows\System32\config\systemprofile\Desktop
The windows service, if running under the systemprofile, needs the Desktop folder. This folder was automatically created on XP and older Windows Server versions, but not for Vista and Windows 2008 Server.
Not sure what is the difference between .cfg & .cnf
In my server I couldn't find .cfg or .cnf
I had created a new file for the same and placed it in the following folder /usr/local/ssl/bin
executed the
.\openssl genrsa -des3 -out <key name>.key 2048
went great..
You use ttk.Frame
, bg
option does not work for it. You should create style and apply it to the frame.
from tkinter import *
from tkinter.ttk import *
root = Tk()
s = Style()
s.configure('My.TFrame', background='red')
mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()
In my case I was using MySql Server version: 8.0.22
I had to add
bind-address = 0.0.0.0
and change this line to be
mysqlx-bind-address = 0.0.0.0
in file at /etc/mysql/mysql.conf.d
then restart MySQL by running
sudo service mysql restart
1.Right click on your java project.
2.Select "RUN AS".
3.Select "RUN CONFIGURATIOS...".
4.Here select your server at left side of the page and then u would see "CLASS PATH" tab at riht side,just click on it.
5.Here clilck on "USER ENTRIES" and select "ADD EXTERNAL JARS".
6.Select "ojdbc14.jar" file.
7.Click on Apply.
8.Click on Run.
9.Finally Restart your server then it would be execute.
i did solved it using jQuery migrate link specified below:
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>
Open your run console type: services.msc look for: mysql right click properties where is written "path to executable", click and move the cursor to the right until you see the directory of my.ini, it's written "defaults-file-". to reach it manually on your explore folders you have to enable the visualization of hidden elements (explore folder>top menu>visualize>visualize hidden elements)
as explained by this video
On Windows Powershell:
$env:OPENSSL_CONF = "${env:ProgramFiles}\OpenSSL-Win64\bin\openssl.cfg"
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
Sometimes when you have special characters in password you need to wrap it in ''
characters, so to connect to db you could use:
mysql -uUSER -p'pa$$w0rd'
I had the same error and this solution solved it.
I tried this tool and it gave me good results.
Just a little addition to the answer of @dAm2k :
In addition to sudo apt-get remove --purge mysql\*
I've done a sudo apt-get remove --purge mariadb\*
.
I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.
Hope it helps.
Ok, something odd is happening here. To make this work, do NOT need to make any configuration changes in /etc/mysql/my.cnf . All you need to do is to restart the current mysql service in terminal:
sudo service mysql restart
Then if I want to "recreate" the bug, I simply restart the apache service:
sudo service apache2 restart
Which can then be fixed again by entering the following command:
sudo service mysql restart
So, it appears that the apache2 is doing something to not allow this feature when it starts up (which is then reversed/corrected if restart the mysql service).
Valid in Debian based distributions.
service mysqld restart
service httpd restart
Valid in RedHat based distributions
In general, on Unix and Unix-like systems, MySQL/MariaDB programs read config/startup files in the following locations (in the specified order):
/etc/my.cnf
- Global/etc/mysql/my.cnf
- GlobalSYSCONFDIR/my.cnf
- Global
SYSCONFDIR
represents the directory specified with theSYSCONFDIR
option toCMake
when MySQL was built. By default, this is the etc directory located under the compiled-in installation directory.
$MYSQL_HOME/my.cnf
- Server-specific (server only)
MYSQL_HOME
is an environment variable containing the path to the directory in which the server-specificmy.cnf
file resides. IfMYSQL_HOME
is not set and you start the server using themysqld_safe
program,mysqld_safe
sets it toBASEDIR
, the MySQL base installation directory.
file specified with --defaults-extra-file=path
if any
~/.my.cnf
- User-specific~/.mylogin.cnf
- User-specific (clients only)Source: Using Option Files.
Note: On Unix platforms, MySQL ignores configuration files that are world-writable. This is intentional as a security measure.
Additionally on Mac there is a simple way to check it.
Run: sudo fs_usage | grep my.cnf
This will report any filesystem activity in real-time related to that file.
In another Terminal, restart your MySQL/MariaDB, e.g.
brew services restart mysql
or:
brew services restart mariadb
On terminal with fs_usage
, the proper location should be shown, e.g.
15:52:22 access /usr/local/Cellar/mariadb/10.1.14/my.cnf 0.000002 sh
So if the file doesn't exist, create one.
The error I was experiencing was that my database network settings allowed outbound traffic to the web – but inbound only from select IP addresses.
I added an inbound rule to allow traffic from my ec2's private IP and it worked.
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
I saw this answer and it worked for me. https://msdn.microsoft.com/en-us/library/ms712362%28v=vs.85%29.aspx
After you have installed an ODBC driver from the driver's setup program, you can define one or more data sources for it. The data source name (DSN) should provide a unique description of the data; for example, Payroll or Accounts Payable. The user and system data sources that are defined for all currently installed drivers are listed in the User DSN or System DSN tabs of the ODBC Data Source Administrator dialog box. The file data sources in a given directory are listed in the File DSN tab; the directory to be shown is entered in the Look in box in the File DSN tab. System_CAPS_noteNote
To manage a data source that connects to a 32-bit driver under 64-bit platform, use c:\windows\sysWOW64\odbcad32.exe. To manage a data source that connects to a 64-bit driver, use c:\windows\system32\odbcad32.exe. In Administrative Tools on a 64-bit Windows 8 operating system, there are icons for both the 32-bit and 64-bit ODBC Data Source Administrator dialog box.
If you use the 64-bit odbcad32.exe to configure or remove a DSN that connects to a 32-bit driver, for example, Driver do Microsoft Access (*.mdb), you will receive the following error message:
The specified DSN contains an architecture mismatch between the Driver and Application
To resolve this error, use the 32-bit odbcad32.exe to configure or remove the DSN.
A data source associates a particular ODBC driver with the data you want to access through that driver. For example, you might create a data source to use the ODBC dBASE driver to access one or more dBASE files found in a specific directory on your hard disk or a network drive. Using the ODBC Data Source Administrator, you can add, modify, and delete data sources, as described in the following table.
The subtle difference is that 3NF makes a distinction between key and non-key attributes (also called non-prime attributes) whereas BCNF does not.
This is best explained using Zaniolo's definition of 3NF, which is equivalent to Codd's:
A relation, R, is in 3NF iff for every nontrivial FD (X->A) satisfied by R at least ONE of the following conditions is true:
(a) X is a superkey for R, or
(b) A is a key attribute for R
BCNF requires (a) but doesn't treat (b) as a special case of its own. In other words BCNF requires that every nontrivial determinant is a superkey even its dependent attributes happen to be part of a key.
A relation, R, is in BCNF iff for every nontrivial FD (X->A) satisfied by R the following condition is true:
(a) X is a superkey for R
BCNF is therefore more strict.
The difference is so subtle that what many people informally describe as 3NF is actually BCNF. For example, you stated here that 3NF means "data depends on the key[s]... and nothing but the key[s]", but that is really an informal description of BCNF and not 3NF. 3NF could more accurately be described as "non-key data depends on the keys... and nothing but the keys".
You also stated:
the 3NF quote explicitly says "nothing but the key" meaning that all attributes depend solely on the primary key.
That's an oversimplification. 3NF and BCNF and all the Normal Forms are concerned with all candidate keys and/or superkeys, not just one "primary" key.
Check the charset encoding of the file. Make sure that it is in ASCII.
Use the od
command to see if there is a UTF-8 BOM at the beginning, for example.
One way to find out:
sudo /usr/libexec/locate.updatedb
# wait a few minutes for it to finish
locate my.cnf
Found it! I forgot to hash the password when I changed it. I used this query to solve my problem:
update user set password=PASSWORD('NEW PASSWORD') where user='root';
I forgot the PASSWORD('NEW PASSWORD')
and just put in the new password in plain text
I was also facing same issue. Below are the steps to resolve it.
openssl version
OpenSSL 1.1.1h 22 Sep 2020
I was experiencing similar problem and the solution for my case was
the thing i felt is we should never give up, i tried every options from this post and from other forums as well...happy it works @saurab
add this to your my.cnf
innodb_buffer_pool_size=1G
restart your mysql to make it effect
I had this socket error and it basically came down to the fact that MySQL was not running. If you run a fresh install, make sure that you install 1) the system package and 2) the panel installer (mysql.prefPane). The panel installer will allow you to goto your System Preferences and open MySQL, and then get an instance running.
Note that, on a fresh install, I needed to reset my computer for the changes to properly take effect. Following a reboot, I got a new instance running and was able to open up a connection to localhost with no problem.
Also of note, I apparently had previous versions of MySQL installed but had removed the panel, which makes it easy to get an instance of MySQL running for mac users.
A good link for this process of reinstalling: http://www.coolestguyplanettech.com/how-to-install-php-mysql-apache-on-os-x-10-6/
This worked for me...
Check all of the MySQL processes running:
$ ps aux | grep mysql
USER PID %CPU %MEM
_mysql 5970 0.0 0.4 ...
Then kill all the processes listed from the above command using the following:
$ sudo kill -9 [PID]
Replace [PID]
with the individual PID from the list above, e.g. 5970
.
Do that for all of the lines you see with the first command.
Then you can startup your MySQL server again:
mysql.server start
1- Open file:
C:\wamp\bin\mysql\mysql5.5.24\my.ini
2- Look for [mysqld] entry and append:
character-set-server = utf8
skip-character-set-client-handshake
The whole view should look like:
[mysqld]
port=3306
character-set-server = utf8
skip-character-set-client-handshake
3- Restart MySQL service!
If you're on Cygwin this command will show you the locations:
mysql --help |grep -A1 Default|grep my
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
On Fedora 21
$ vi /etc/my.cnf
Add follow:
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
Save and exit.
Final remember restart service mysqld with service mysqld restart
.
You can use :
locate my.cnf
whereis my.cnf
find . -name my.cnf
The above solutions like run a query
SET session wait_timeout=600;
Will only work until mysql is restarted. For a persistant solution, edit mysql.conf and add after [mysqld]:
wait_timeout=300
interactive_timeout = 300
Where 300 is the number of seconds you want.
if you still need to use the double-colon then make sure your on PHP 5.3+
You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)
SHOW VARIABLES
As an alternative you can also query the information_schema
database and retrieve the data from the global_variables
(and global_status
of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.
For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size
in bytes and megabytes:
SELECT
variable_name,
variable_value AS innodb_log_buffer_size_bytes,
ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE 'innodb_log_buffer_size';
As a result you get:
+------------------------+------------------------------+---------------------------+
| variable_name | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456 | 256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)
another way to enable dirty read in mysql is add hint: LOCK IN SHARE MODE
SELECT * FROM TABLE_NAME LOCK IN SHARE MODE;
The simplest way is to make String
conform to Error
:
extension String: Error {}
Then you can just throw a string:
throw "Some Error"
To make the string itself be the localizedString
of the error you can instead extend LocalizedError
:
extension String: LocalizedError {
public var errorDescription: String? { return self }
}
Why don't you examine System.getProperty("os.arch")
value in your code?
on success: function (response) { alert(response.d); }
Edit: my bad, you wanted the select to show results after the update, not update from a select.
Have you tried a sub-select?
update mytable set mydate = sysdate
where mydate in (select mydate from mytable where mydate is null);
if you are using anaconda, python 3.7 is installed by default, so you have to downgrade it to 3.6:
conda install python=3.6
then:
pip install tensorflow
it worked for me in Ubuntu.
Another thing that people may find useful when using the develop
method is the --user
option to install without sudo. Ex:
python setup.py develop --user
instead of
sudo python setup.py develop
If you want to sum
all values of one column, it's more efficient to use DataFrame
's internal RDD
and reduce
.
import sqlContext.implicits._
import org.apache.spark.sql.functions._
val df = sc.parallelize(Array(10,2,3,4)).toDF("steps")
df.select(col("steps")).rdd.map(_(0).asInstanceOf[Int]).reduce(_+_)
//res1 Int = 19
Try this:
$str = htmlentities($str,ENT_QUOTES,'UTF-8');
So, after filtering your data using htmlentities()
function, you can use the data in XML tag like:
<mytag>$str</mytag>
Here is a Swift 3 version:
private func getHtmlLabel(text: String) -> UILabel {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedString = stringFromHtml(string: text)
return label
}
private func stringFromHtml(string: String) -> NSAttributedString? {
do {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return str
}
} catch {
}
return nil
}
I found issues with some of the other answers here and it took me a bit to get this right. I set the line break mode and number of lines so that the label sized appropriately when the HTML spanned multiple lines.
Bear in mind you may have to do pip install --upgrade Distribute
if you have it installed already and your pip
may be called pip2
for Python2 on some systems (it is on mine).
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mouse.OverrideCursor = null;
}
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
I don't think robomongo have such a feature. So you better use mongodb function as mongoexport for a specific Collection.
http://docs.mongodb.org/manual/reference/program/mongoexport/#export-in-json-format
But if you are looking for a backup solution is better to use
mongodump / mongorestore
Sample Json
{
"per_page": 3,
"total": 12,
"data": [{
"last_name": "Bluth",
"id": 1,
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
"first_name": "George"
},
{
"last_name": "Weaver",
"id": 2,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
"first_name": "Janet"
},
{
"last_name": "Wong",
"id": 3,
//"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
"first_name": "Emma"
}
],
"page": 1,
"total_pages": 4
}
First If statement will convert the single data from the body Second if statement will differentiate the JsonArray object
public static String getvalueJpath(JSONObject responseJson, String Jpath ) {
Object obj = responseJson;
for(String s : Jpath.split("/"))
if (s.isEmpty())
if(!(s.contains("[") || s.contains("]")))
obj = ((JSONObject) obj).get(s);
else
if(s.contains("[") || s.contains("]"))
obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", "")));
return obj.toString();
}
}
Use:
git log --graph --abbrev-commit --decorate --first-parent <branch_name>
It is only for the target branch (of course --graph, --abbrev-commit --decorate are more polishing).
The key option is --first-parent
: "Follow only the first parent commit upon seeing a merge commit" (https://git-scm.com/docs/git-log)
It prevents the commit forks from being displayed.
Another way of doing the same but with dplyr
library(dplyr)
subdf <- df %>% filter(numbers <= 3) %>% droplevels()
str(subdf)
Edit:
Also Works ! Thanks to agenis
subdf <- df %>% filter(numbers <= 3) %>% droplevels
levels(subdf$letters)
I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.
From Ansible 2.5
when: variable1 is search("value")
Just set targetSdkVersion to 19. The notification icon will be colored. Then wait for Firebase to fix this issue.
Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r
.
So here in your case it'd be something like
local> scp -r [email protected]:/path/to/dir local/path
If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
This may be possible by using the refs attribute.
In the example of wanting to to reach a <div>
what you would want to do is use is <div ref="myExample">
. Then you would be able to get that DOM node by using React.findDOMNode(this.refs.myExample)
.
From there getting the correct DOM node of each child may be as simple as mapping over this.refs.myExample.children
(I haven't tested that yet) but you'll at least be able to grab any specific mounted child node by using the ref attribute.
Here's the official react documentation on refs for more info.
Warnings are annoying. As mentioned in other answers, you can suppress them using:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:
import warnings
warnings.filterwarnings("error")
But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:
import warnings
warnings.simplefilter(action='error', category=FutureWarning)
You could simply define a series of const ints
in a header file:
// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1
const int a = 100;
const int b = 0x7f;
#endif
This works because in C++ a name at namespace scope (including the global namespace) that is explicitly declared const and not explicitly declared extern has internal linkage, so these variables would not cause duplicate symbols when you link together translation units. Alternatively you could explicitly declare the constants as static.
static const int a = 100;
static const int b = 0x7f;
This is more compatible with C and more readable for people that may not be familiar with C++ linkage rules.
If all the constants are ints then another method you could use is to declare the identifiers as enums.
enum mylib_constants {
a = 100;
b = 0x7f;
};
All of these methods use only a header and allow the declared names to be used as compile time constants. Using extern const int
and a separate implementation file prevents the names from being used as compile time constants.
Note that the rule that makes certain constants implicitly internal linkage does apply to pointers, exactly like constants of other types. The tricky thing though is that marking a pointer as const
requires syntax a little different that most people use to make variables of other types const. You need to do:
int * const ptr;
to make a constant pointer, so that the rule will apply to it.
Also note that this is one reason I prefer to consistently put const
after the type: int const
instead of const int
. I also put the *
next to the variable: i.e. int *ptr;
instead of int* ptr;
(compare also this discussion).
I like to do these sorts of things because they reflect the general case of how C++ really works. The alternatives (const int
, int* p
) are just special cased to make some simple things more readable. The problem is that when you step out of those simple cases, the special cased alternatives become actively misleading.
So although the earlier examples show the common usage of const
, I would actually recommend people write them like this:
int const a = 100;
int const b = 0x7f;
and
static int const a = 100;
static int const b = 0x7f;
Fill the include
property in the first level of the JSON-object in the tsconfig.editor.json
like here:
"include": [
"src/**/*.ts"
]
It works for me well.
Also you can add another Typescript file extensions if it's needed, like here:
"include": [
"src/**/*.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
select ...
from ...
where YourDateColumn >= getdate()-1
Another way this might fail is if the account running the service doesn't have write permission into the data directory.
In that case the service will be unable to create a lock file.
The mongod service behaves badly in this situation and goes into a loop starting a process, which immediately throws an unhandled exception, crashes, etc. the log file gets recreated every time the process starts up, so you have to grab it quick if you want to see the error.
the default user for windows services would be localhost\system. so the fix is to ensure this user can write into your db directory, or start the service as another user who can.
This worked for me
EditText etname = (EditText) findViewById(R.id.etname);
if(etname.length() == 0){
etname.setError("Required field");
}else{
Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_LONG).show();
}
or Use this for strings
String DEP_DATE;
if (DEP_DATE.equals("") || DEP_DATE.length() == 0 || DEP_DATE.isEmpty() || DEP_DATE == null){
}
Strange behaviour which I was experienced also. So for me "return false" did the trick.
$( '#selector' ).on( 'click', function() {
//code
return false;
});
You can also try and use the caching built into ASP MVC:
Add the following attribute to the controller method you'd like to cache:
[OutputCache(Duration=10)]
In this case the ActionResult of this will be cached for 10 seconds.
You mean Selenium WebDriver? Huh....
Prerequisite: Install Python based on your OS
Install with following command
pip install -U selenium
And use this module in your code
from selenium import webdriver
You can also use many of the following as required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
I would recommend you to run script without IDE... Here is my approach
An example below shows login page automation
#ScriptName : Login.py
#---------------------
from selenium import webdriver
#Following are optional required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
baseurl = "http://www.mywebsite.com/login.php"
username = "admin"
password = "admin"
xpaths = { 'usernameTxtBox' : "//input[@name='username']",
'passwordTxtBox' : "//input[@name='password']",
'submitButton' : "//input[@name='login']"
}
mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.maximize_window()
#Clear Username TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()
#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)
#Clear Password TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()
#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()
There is an another way that you can find xpath of any object -
Run script -
python Login.py
You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn't an ID attribute on the elements you're interacting with).
Firepath can also capture the object's locator as a CSS selector if you move your cursor to the object. You'll have to update your code to use the equivalent find by CSS selector method instead -
find_element_by_css_selector(css_selector)
Try the following:
SELECT DISTINCT(ip), name, COUNT(name) nameCnt,
time, price, SUM(price) priceSum
FROM tablename
WHERE time >= $yesterday AND time <$today
GROUP BY ip, name
Offering another potential solution to this error.
If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.
e.g.
https://example.com/api/etc
and not
https://123.4.5.6/api/etc
In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE
.
in Bitbucket go to branches in left hand side menu.
Try specifying the actual index of the item you want erase the text from and set it's Text equal to "".
myComboBox[this.SelectedIndex].Text = ""
or
myComboBox.selectedIndex.Text = ""
I don't remember the exact syntax but it's something along those lines.
With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.
In [1]: import pandas as pd
In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])
In [3]: df
Out[3]:
0
0 a
1 b
2 c
3 d
4 a
5 b
In [4]: df[df.duplicated(keep=False)]
Out[4]:
0
0 a
1 b
4 a
5 b
For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.
I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:
When no input has been given yet, I would advise:
touchUi = true
on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.
My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.
Edit: Result
<div fxLayout="row">
<div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
<mat-form-field>
<input matInput [ngxTimepicker]="endTime" [format]="24" placeholder="{{placeholderTime}}" formControlName="endTime" />
</mat-form-field>
<ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
</div>
<div>
<mat-form-field>
<input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
[min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
<mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
<mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
</mat-form-field>
</div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';
import * as moment_ from 'moment';
const moment = moment_;
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
class DateConfig {
startView: 'month' | 'year' | 'multi-year';
touchUi: boolean;
minDate: moment_.Moment;
maxDate: moment_.Moment;
}
@Component({
selector: 'cb-datetimepicker',
templateUrl: './cb-datetimepicker.component.html',
styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {
@Input() disabled: boolean;
@Input() placeholderDate: string;
@Input() placeholderTime: string;
@Input() model: Date;
@Input() purpose: string;
@Input() dateOnly: boolean;
@Output() dateUpdate = new EventEmitter<Date>();
public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);
public dateForm: FormControl;
public timeFormGroup: FormGroup;
public endTime: FormControl;
public momentDate: moment_.Moment;
public config: DateConfig;
//myGroup: FormGroup;
constructor(private adapter : DateAdapter<any>) { }
ngOnInit() {
this.adapter.setLocale("nl-NL");//todo: configurable
this.config = new DateConfig();
if (this.purpose === "birthday") {
this.config.startView = 'multi-year';
this.config.maxDate = moment().add('year', -15);
this.config.minDate = moment().add('year', -90);
this.dateOnly = true;
} //add more configurations
else {
this.config.startView = 'month';
this.config.maxDate = moment().add('year', 100);
this.config.minDate = moment().add('year', -100);
}
if (window.screen.width < 767) {
this.config.touchUi = true;
}
if (this.model) {
var mom = moment(this.model);
if (mom.isBefore(moment('1900-01-01'))) {
this.momentDate = moment();
} else {
this.momentDate = mom;
}
} else {
this.momentDate = moment();
}
this.dateForm = new FormControl(this.momentDate);
if (this.disabled) {
this.dateForm.disable();
}
this.endTime = new FormControl(this.momentDate.format("HH:mm"));
this.timeFormGroup = new FormGroup({
endTime: this.endTime
});
}
public dateChange(date: MatDatepickerInputEvent<any>) {
if (moment.isMoment(date.value)) {
this.momentDate = moment(date.value);
if (this.dateOnly) {
this.momentDate = this.momentDate.utc(true);
}
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
console.log("datechange",date);
}
public timeChange(time: string) {
var splitted = time.split(':');
var hour = splitted[0];
var minute = splitted[1];
console.log("time change", time);
this.momentDate = this.momentDate.set('hour', parseInt(hour));
this.momentDate = this.momentDate.set('minute', parseInt(minute));
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
}
One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126
I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).
If you're using AMD modules, the other answers won't work in TypeScript 1.0 (the newest at the time of writing.)
You have different approaches available to you, depending upon how many things you wish to export from each .ts
file.
Foo.ts
export class Foo {}
export interface IFoo {}
Bar.ts
import fooModule = require("Foo");
var foo1 = new fooModule.Foo();
var foo2: fooModule.IFoo = {};
Foo.ts
class Foo
{}
export = Foo;
Bar.ts
import Foo = require("Foo");
var foo = new Foo();
Quote from the documentation:
The "standard" and "singleTop" modes differ from each other in just one respect: Every time there's new intent for a "standard" activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created.
I'm not 100% sure what "already has an existing instance of the activity at the top of its stack" means, but perhaps your activity isn't meeting this condition.
Would singleTask
or singleInstance
work for you? Or perhaps you could try setting FLAG_ACTIVITY_SINGLE_TOP
on the intent you are creating to see if that makes a difference, although I don't think it will.
You need to wrap the table inside another element and set the height of that element. Example with inline css:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
You can also open a required file through a prompt, This helps when you want to select file from different path and different file.
Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant
NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")
If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub
torch.Tensor.view()
Simply put, torch.Tensor.view()
which is inspired by numpy.ndarray.reshape()
or numpy.reshape()
, creates a new view of the tensor, as long as the new shape is compatible with the shape of the original tensor.
Let's understand this in detail using a concrete example.
In [43]: t = torch.arange(18)
In [44]: t
Out[44]:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
With this tensor t
of shape (18,)
, new views can only be created for the following shapes:
(1, 18)
or equivalently (1, -1)
or (-1, 18)
(2, 9)
or equivalently (2, -1)
or (-1, 9)
(3, 6)
or equivalently (3, -1)
or (-1, 6)
(6, 3)
or equivalently (6, -1)
or (-1, 3)
(9, 2)
or equivalently (9, -1)
or (-1, 2)
(18, 1)
or equivalently (18, -1)
or (-1, 1)
As we can already observe from the above shape tuples, the multiplication of the elements of the shape tuple (e.g. 2*9
, 3*6
etc.) must always be equal to the total number of elements in the original tensor (18
in our example).
Another thing to observe is that we used a -1
in one of the places in each of the shape tuples. By using a -1
, we are being lazy in doing the computation ourselves and rather delegate the task to PyTorch to do calculation of that value for the shape when it creates the new view. One important thing to note is that we can only use a single -1
in the shape tuple. The remaining values should be explicitly supplied by us. Else PyTorch will complain by throwing a RuntimeError
:
RuntimeError: only one dimension can be inferred
So, with all of the above mentioned shapes, PyTorch will always return a new view of the original tensor t
. This basically means that it just changes the stride information of the tensor for each of the new views that are requested.
Below are some examples illustrating how the strides of the tensors are changed with each new view.
# stride of our original tensor `t`
In [53]: t.stride()
Out[53]: (1,)
Now, we will see the strides for the new views:
# shape (1, 18)
In [54]: t1 = t.view(1, -1)
# stride tensor `t1` with shape (1, 18)
In [55]: t1.stride()
Out[55]: (18, 1)
# shape (2, 9)
In [56]: t2 = t.view(2, -1)
# stride of tensor `t2` with shape (2, 9)
In [57]: t2.stride()
Out[57]: (9, 1)
# shape (3, 6)
In [59]: t3 = t.view(3, -1)
# stride of tensor `t3` with shape (3, 6)
In [60]: t3.stride()
Out[60]: (6, 1)
# shape (6, 3)
In [62]: t4 = t.view(6,-1)
# stride of tensor `t4` with shape (6, 3)
In [63]: t4.stride()
Out[63]: (3, 1)
# shape (9, 2)
In [65]: t5 = t.view(9, -1)
# stride of tensor `t5` with shape (9, 2)
In [66]: t5.stride()
Out[66]: (2, 1)
# shape (18, 1)
In [68]: t6 = t.view(18, -1)
# stride of tensor `t6` with shape (18, 1)
In [69]: t6.stride()
Out[69]: (1, 1)
So that's the magic of the view()
function. It just changes the strides of the (original) tensor for each of the new views, as long as the shape of the new view is compatible with the original shape.
Another interesting thing one might observe from the strides tuples is that the value of the element in the 0th position is equal to the value of the element in the 1st position of the shape tuple.
In [74]: t3.shape
Out[74]: torch.Size([3, 6])
|
In [75]: t3.stride() |
Out[75]: (6, 1) |
|_____________|
This is because:
In [76]: t3
Out[76]:
tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])
the stride (6, 1)
says that to go from one element to the next element along the 0th dimension, we have to jump or take 6 steps. (i.e. to go from 0
to 6
, one has to take 6 steps.) But to go from one element to the next element in the 1st dimension, we just need only one step (for e.g. to go from 2
to 3
).
Thus, the strides information is at the heart of how the elements are accessed from memory for performing the computation.
This function would return a view and is exactly the same as using torch.Tensor.view()
as long as the new shape is compatible with the shape of the original tensor. Otherwise, it will return a copy.
However, the notes of torch.reshape()
warns that:
contiguous inputs and inputs with compatible strides can be reshaped without copying, but one should not depend on the copying vs. viewing behavior.
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
As @Nick said, the results you see when you console.log
a JavaScript Error
object depend on the exact implementation of console.log
, which varies and (imo) makes checking errors incredibly annoying.
If you'd like to see the full Error
object and all the information it carries bypassing the toString()
method, you could just use JSON.stringify:
axios.get('/foo')
.catch(function (error) {
console.log(JSON.stringify(error))
});
I have also seen:
if(length(obj)) {
# do this if object has length
# NULL has no length
}
I don't think it's great though. Because some vectors can be of length 0. character(0)
, logical(0)
, integer(0)
and that might be treated as a NULL instead of an error.
How to use a clock and do assertions
This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.
The key idea is that the process
blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.
library ieee;
use ieee.std_logic_1164.all;
entity counter_tb is
end counter_tb;
architecture behav of counter_tb is
constant width : natural := 2;
constant clk_period : time := 1 ns;
signal clk : std_logic := '0';
signal data : std_logic_vector(width-1 downto 0);
signal count : std_logic_vector(width-1 downto 0);
type io_t is record
load : std_logic;
data : std_logic_vector(width-1 downto 0);
count : std_logic_vector(width-1 downto 0);
end record;
type ios_t is array (natural range <>) of io_t;
constant ios : ios_t := (
('1', "00", "00"),
('0', "UU", "01"),
('0', "UU", "10"),
('0', "UU", "11"),
('1', "10", "10"),
('0', "UU", "11"),
('0', "UU", "00"),
('0', "UU", "01")
);
begin
counter_0: entity work.counter port map (clk, load, data, count);
process
begin
for i in ios'range loop
load <= ios(i).load;
data <= ios(i).data;
wait until falling_edge(clk);
assert count = ios(i).count;
end loop;
wait;
end process;
process
begin
for i in 1 to 2 * ios'length loop
wait for clk_period / 2;
clk <= not clk;
end loop;
wait;
end process;
end behav;
The counter would look like this:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned
entity counter is
generic (
width : in natural := 2
);
port (
clk, load : in std_logic;
data : in std_logic_vector(width-1 downto 0);
count : out std_logic_vector(width-1 downto 0)
);
end entity counter;
architecture rtl of counter is
signal cnt : unsigned(width-1 downto 0);
begin
process(clk) is
begin
if rising_edge(clk) then
if load = '1' then
cnt <= unsigned(data);
else
cnt <= cnt + 1;
end if;
end if;
end process;
count <= std_logic_vector(cnt);
end architecture rtl;
Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
Edit Since version 26 of the support library (or androidx) you no longer need to implement a custom OnLongClickListener
to display the tooltip. Simply call this:
TooltipCompat.setTooltipText(menu_hotlist, getString(R.string.hint_show_hot_message));
I'll just share my code in case someone wants something like this:
layout/menu/menu_actionbar.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
...
<item android:id="@+id/menu_hotlist"
android:actionLayout="@layout/action_bar_notifitcation_icon"
android:showAsAction="always"
android:icon="@drawable/ic_bell"
android:title="@string/hotlist" />
...
</menu>
layout/action_bar_notifitcation_icon.xml
Note style and android:clickable properties. these make the layout the size of a button and make the background gray when touched.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center"
android:clickable="true"
style="@android:style/Widget.ActionButton">
<ImageView
android:id="@+id/hotlist_bell"
android:src="@drawable/ic_bell"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_margin="0dp"
android:contentDescription="bell"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hotlist_hot"
android:layout_width="wrap_content"
android:minWidth="17sp"
android:textSize="12sp"
android:textColor="#ffffffff"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@null"
android:layout_alignTop="@id/hotlist_bell"
android:layout_alignRight="@id/hotlist_bell"
android:layout_marginRight="0dp"
android:layout_marginTop="3dp"
android:paddingBottom="1dp"
android:paddingRight="4dp"
android:paddingLeft="4dp"
android:background="@drawable/rounded_square"/>
</RelativeLayout>
drawable-xhdpi/ic_bell.png
A 64x64 pixel image with 10 pixel wide paddings from all sides. You are supposed to have 8 pixel wide paddings, but I find most default items being slightly smaller than that. Of course, you'll want to use different sizes for different densities.
drawable/rounded_square.xml
Here, #ff222222 (color #222222 with alpha #ff (fully visible)) is the background color of my Action Bar.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="2dp" />
<solid android:color="#ffff0000" />
<stroke android:color="#ff222222" android:width="2dp"/>
</shape>
com/ubergeek42/WeechatAndroid/WeechatActivity.java
Here we make it clickable and updatable! I created an abstract listener that provides Toast creation on onLongClick, the code was taken from from the sources of ActionBarSherlock.
private int hot_number = 0;
private TextView ui_hot = null;
@Override public boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater menuInflater = getSupportMenuInflater();
menuInflater.inflate(R.menu.menu_actionbar, menu);
final View menu_hotlist = menu.findItem(R.id.menu_hotlist).getActionView();
ui_hot = (TextView) menu_hotlist.findViewById(R.id.hotlist_hot);
updateHotCount(hot_number);
new MyMenuItemStuffListener(menu_hotlist, "Show hot message") {
@Override
public void onClick(View v) {
onHotlistSelected();
}
};
return super.onCreateOptionsMenu(menu);
}
// call the updating code on the main thread,
// so we can call this asynchronously
public void updateHotCount(final int new_hot_number) {
hot_number = new_hot_number;
if (ui_hot == null) return;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (new_hot_number == 0)
ui_hot.setVisibility(View.INVISIBLE);
else {
ui_hot.setVisibility(View.VISIBLE);
ui_hot.setText(Integer.toString(new_hot_number));
}
}
});
}
static abstract class MyMenuItemStuffListener implements View.OnClickListener, View.OnLongClickListener {
private String hint;
private View view;
MyMenuItemStuffListener(View view, String hint) {
this.view = view;
this.hint = hint;
view.setOnClickListener(this);
view.setOnLongClickListener(this);
}
@Override abstract public void onClick(View v);
@Override public boolean onLongClick(View v) {
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
view.getLocationOnScreen(screenPos);
view.getWindowVisibleDisplayFrame(displayFrame);
final Context context = view.getContext();
final int width = view.getWidth();
final int height = view.getHeight();
final int midy = screenPos[1] + height / 2;
final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
Toast cheatSheet = Toast.makeText(context, hint, Toast.LENGTH_SHORT);
if (midy < displayFrame.height()) {
cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT,
screenWidth - screenPos[0] - width / 2, height);
} else {
cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
}
cheatSheet.show();
return true;
}
}
Actually for Bootstrap 3 you also need to override the .modal-open class on body.
body.modal-open,
.modal-open
.navbar-fixed-top,
.modal-open
.navbar-fixed-bottom {
margin-right: 15px; /*<-- to margin-right: 0px;*/
}
Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.
Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.
If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.
You can determine that the connection is lost by making failed XHR requests.
The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.
Sidenote: To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.
Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.
Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping
google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.
If you're using Node.js:
> var ObjectId = require('mongodb').ObjectId;
> var id = req.params.gonderi_id;
> var o_id = new ObjectId(id);
> db.test.find({_id:o_id})
Edit: corrected to new ObjectId(id), not new ObjectID(id)
log in as root user:
sudo su
password:
then go and do what you want to do in var/www
The problem is that the directory you created, /data/db
is owned by and only writable by the root user, but you are running mongod as yourself. There are several ways to resolve this, but ultimately, you must give the directory in question the right permissions. If this is for production, I would advise you to check the docs and think this over carefully -- you probably want to take special care.
However, if this is just for testing and you just need this to work and get on with it, you could try this, which will make the directory writable by everyone:
> sudo chmod -R go+w /data/db
or this, which will make the directory owned by you:
> sudo chown -R $USER /data/db
Simple and another way to solve :
function stringInsert($str,$insertstr,$pos)
{
$count_str=strlen($str);
for($i=0;$i<$pos;$i++)
{
$new_str .= $str[$i];
}
$new_str .="$insertstr";
for($i=$pos;$i<$count_str;$i++)
{
$new_str .= $str[$i];
}
return $new_str;
}
In Ruby, 0 evaluates as true in conditional expressions.
I've found that the parent of a UserControl is always null in the constructor, but in any event handlers the parent is set correctly. I guess it must have something to do with the way the control tree is loaded. So to get around this you can just get the parent in the controls Loaded event.
For an example checkout this question WPF User Control's DataContext is Null
I disagree with the popular answer, that having public implies that there are other options and so it shouldn't be there. The fact is that now with Java 9 and beyond there ARE other options.
I think instead Java should enforce/require 'public' to be specified. Why? Because the absence of a modifier means 'package' access everywhere else, and having this as a special case is what leads to the confusion. If you simply made it a compile error with a clear message (e.g. "Package access is not allowed in an interface.") we would get rid of the apparent ambiguity that having the option to leave out 'public' introduces.
Note the current wording at: https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
"A method in the body of an interface may be declared public or private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface."
See that 'private' IS allowed now. I think that last sentence should have been removed from the JLS. It is unfortunate that the "implicitly public" behaviour was ever allowed as it will now likely remain for backward compatibilty and lead to the confusion that the absence of the access modifier means 'public' in interfaces and 'package' elsewhere.
Just right click on your terminal icon, and select open a new window. Now you'll have two terminal windows open. In the new window, type, mongo and hit enter. Boom, that'll work like it's supposed to.
Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
HashMap has a putAll
method.
http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html
There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.
The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.
string & replace(string & subj, string old, string neu)
{
size_t uiui = subj.find(old);
if (uiui != string::npos)
{
subj.erase(uiui, old.size());
subj.insert(uiui, neu);
}
return subj;
}
I think this fits your requirement with few code!
The reasons why (including the data in the leaf level of the index) have been nicely explained. The reason that you give two shakes about this, is that when you run your query, if you don't have the additional columns included (new feature in SQL 2005) the SQL Server has to go to the clustered index to get the additional columns which takes more time, and adds more load to the SQL Server service, the disks, and the memory (buffer cache to be specific) as new data pages are loaded into memory, potentially pushing other more often needed data out of the buffer cache.
button {_x000D_
background: none!important;_x000D_
border: none;_x000D_
padding: 0!important;_x000D_
/*optional*/_x000D_
font-family: arial, sans-serif;_x000D_
/*input has OS specific font-family*/_x000D_
color: #069;_x000D_
text-decoration: underline;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<button> your button that looks like a link</button>
_x000D_
You need to add position:relative
to #wrap element.
When you add this, all child elements will be positioned in this element, not browser window.
Eclipse -> Preferences -> Java -> Build Path -> User Libraries -> New(Name it) -> Add external Jars
(I recommend dragging your new libraries into the eclipse folder before any of these steps to keep everything together, that way if you reinstall Eclipse or your OS you won't have to rwlink anything except the JDK) Now select the jar files you want. Click OK.
Right click on your project and choose Build Path -> Add Library
FYI just code and then right click and Source->Organize Imports
It doesn't because the href value is not sign_up
.It is #sign_up
. Try like below,
You need to add "#" to indicate the id of the href value.
$('a[href="#sign_up"]').click(function(){
alert('Sign new href executed.');
});
to use parameters in aliases, i use this method:
alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'
its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions... which i hate, oh yeah and if you need that return value, you'll have to store it before calling unset, and then return the value using the "return" keyword in that self destructive function there:
alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'
so..
you could, if you need to have that variable in there
alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'
of course...
alias mongodb='./path/to/mongodb/'
would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).
I hope that helps you out :)
You can prepare the text in notepad, and paste it into SSMS. SSMS will not display the newlines, but they are there, as you can verify with a select:
select *
from YourTable
where Col1 like '%' + char(10) + '%'
(array1 + array2).uniq
This way you get array1 elements first. You will get no duplicates.
I know it's old post, but I thought this is a good addition:
You can use List<T>.ConvertAll<TOutput>
List<int> integers = strings.ConvertAll(s => Int32.Parse(s));
Something throws an exception of type std::bad_alloc
, indicating that you ran out of memory. This exception is propagated through until main
, where it "falls off" your program and causes the error message you see.
Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h
looks like a syntax error.
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.
To truly force maven to only use your local repo, you can run with mvn <goals> -o
. The -o
tells maven to let you work "offline", and it will stay off the network.
There are 2 steps to resolve this:
Add UseAccessibleHeader="true"
to Gridview tag:
<asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
Add the following Code to the PreRender
event:
Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
Try
MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
Catch ex As Exception
End Try
End Sub
Note setting Header Row in DataBound()
works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.
Douglas Crockford has some very good explanations of inheritance in JavaScript:
simplify the whole thing a bit, fix some issues with commas which will blow up some browsers:
$(document).ready(function () {
$("#register").validate({
debug: true,
rules: {
year: {
required: function () {
return ($("#year option:selected").val() == "0");
}
}
},
messages: {
year: "Year Required"
}
});
});
Jumping to an assumption, should your select not have this attribute validate="required:true"
?
[ ]
defines a character class. So every character you set there, will match. [012]
will match 0
or 1
or 2
and [0-2]
behaves the same.
What you want is groupings to define a or-statement. Use (s|season)
for your issue.
Btw. you have to watch out. Metacharacters in normal regex (or inside a grouping) are different from character class. A character class is like a sub-language. [$A]
will only match $
or A
, nothing else. No escaping here for the dollar.
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
A space may only be encoded to "+" in the "application/x-www-form-urlencoded" content-type key-value pairs query part of an URL. In my opinion, this is a MAY, not a MUST. In the rest of URLs, it is encoded as %20.
In my opinion, it's better to always encode spaces as %20, not as "+", even in the query part of an URL, because it is the HTML specification (RFC-1866) that specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs (see paragraph 8.2.1. subparagraph 1.)
This way of encoding form data is also given in later HTML specifications. For example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
Here is a sample string in URL where the HTML specification allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses. In other cases, spaces should be encoded to %20. But since it's hard to correctly determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
The implementation depends on the programming language that you chose.
If your URL contains national characters, first encode them to UTF-8 and then percent-encode the result.
You can use the below code to submit the form using JavaScript:
document.getElementById('FormID').submit();
You can use the following
/*eslint-disable */
//suppress all warnings between comments
alert('foo');
/*eslint-enable */
Which is slightly buried the "configuring rules" section of the docs;
To disable a warning for an entire file, you can include a comment at the top of the file e.g.
/*eslint eqeqeq:0*/
ESlint has now been updated with a better way disable a single line, see @goofballLogic's excellent answer.
Instead of copy/paste a unicode character or setting it in the code-behind you could also change the properties of the TextBox. Simply set "UseSystemPasswordChar" to True and everytghing will be done for you by the Framework. Or in code-behind:
this.txtPassword.UseSystemPasswordChar = true;
val === false || val === true
.typeof variable == typeof true
.The shortest, but not readable at all: !!val === val
.
Explanation:
Tests:
I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.
With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:
this.options.map(option => {
// New properties to be added
const newPropsObj = {
newkey1:value1,
newkey2:value2
};
// Assign new properties and return
return Object.assign(option, newPropsObj);
});
For the parent div,use following CSS:
style="display: flex;align-items: center;"
#include <stdio.h>
void main()
{
int countch=0;
int countwd=1;
printf("Enter your sentence in lowercase: ");
char ch='a';
while(ch!='\r')
{
ch=getche();
if(ch==' ')
countwd++;
else
countch++;
}
printf("\n Words = ",countwd);
printf("Characters = ",countch-1);
getch();
}
lets take this example try putting \n in place of \r it will not work and try to guess why?
Use PHP's json methods to create the json then write it to a file with fwrite.
PyCharm cell mode
Run Cell
and Run Cell and go to next
A cell is delimited by ##
Ref https://plugins.jetbrains.com/plugin/7858-pycharm-cell-mode
Think more about what you are installing and navigate Gemfile folder, then try using sudo bundle install
Setting Clickable to false does not work on the first double click but subsequent double clicks are blocked. It is as though the loading click delegate the first time is slower and the second click is captured before the first completes.
Button button = contentView.FindViewById<Button>(Resource.Id.buttonIssue);
button.Clickable = false;
IssueSelectedItems();
button.Clickable = true;
People are saying that the symbol doesn't mean addition. This is true, but doesn't explain why a plus-like symbol is used for something that isn't addition.
The answer is that for modulo addition of 1-bit values, 0+0 == 1+1 == 0, and 0+1 == 1+0 == 1. Those are the same values as XOR.
So, plus in a circle in this context means "bitwise addition modulo-2". Which is, as everyone says, XOR for integers. It's common in mathematics to use plus in a circle for an operation which is a sort of addition, but isn't regular integer addition.
Use Concat
or Union
extension methods. You have to make sure that you have this direction using System.Linq;
in order to use LINQ extensions methods.
Use the AddRange
method.
In my case I had to add FormsModule
and ReactiveFormsModule
to the shared.module.ts
too:
(thanks to @Undrium for the code example):
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ CommonModule, ReactiveFormsModule ], declarations: [], exports: [ CommonModule, FormsModule, ReactiveFormsModule ] }) export class SharedModule { }
public static void main(String[] args) {
String test = "something hear - to - find some to or tows";
System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
if(fromIndex != null && fromIndex < text.length())
return Pattern.compile(pattern).matcher(text).find();
return Pattern.compile(pattern).matcher(text).find();
}
1.result: true
2.result: true
I just found out, that by using asset_url
helper you solve that problem.
asset_url("backgrounds/pattern.png", image)
Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters
By using this on bootstrap 3:
#carousel-example-generic{
margin:auto;
}
I tried a number of the suggestions above without success.
I use the NuGeT packages. The are (for some reason) multiple named version (font-awesome, fontawesome, font.awesome, etc.)
For what it's worth: I removed all the version installed and then only installed the latest version of font.awesome. font.awesome just worked without the need to tweak or configure anything.
I assume there are a number of things are missing from the other named versions.
Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0
One solution is to define a simple recursive function:
u0 = ...
def f(x):
...
def u(n):
if n==0: return u0
return f(u(n-1))
Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.
Another solution is a simple loop:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
return ux
But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
yield ux
for val in u(1000):
print val
There are many other options, but I guess these are the main ones.
Some of my dynamic SOAP requests have been getting out of control recently. With the uncompressed SOAP being about 14MB and compressed 3MB.
I noticed that in Fiddler when I compressed my request under Transformer
it came to about 470KB instead of the 3MB - so I figured there must be some way to get better compression.
Eventually found this very informative blog post
http://weblogs.asp.net/owscott/iis-7-compression-good-bad-how-much
I went ahead and ran this commnd (followed by iisreset):
C:\Windows\System32\Inetsrv\Appcmd.exe set config -section:httpCompression -[name='gzip'].staticCompressionLevel:9 -[name='gzip'].dynamicCompressionLevel:9
Changed dynamic level up to 9 and now my compressed soap matches what Fiddler gave me - and it about 1/7th the size of the existing compressed file.
Milage will vary, but for SOAP this is a massive massive improvement.
Change the following to the file
/usr/local/mysql/support-files/mysql.server
the follow lines:
basedir="/usr/local/mysql"
datadir="/usr/local/mysql/data"
and save it.
/etc/rc.common
add the follow line at end:
/usr/local/mysql/bin/mysqld_safe --user=mysql &
git reset 'HEAD@{1}'
Git keeps a log of all ref updates (e.g., checkout, reset, commit, merge). You can view it by typing:
git reflog
Somewhere in this list is the commit that you lost. Let's say you just typed git reset HEAD~
and want to undo it. My reflog looks like this:
$ git reflog
3f6db14 HEAD@{0}: HEAD~: updating HEAD
d27924e HEAD@{1}: checkout: moving from d27924e0fe16776f0d0f1ee2933a0334a4787b4c
[...]
The first line says that HEAD
0 positions ago (in other words, the current position) is 3f6db14; it was obtained by resetting to HEAD~
. The second line says that HEAD
1 position ago (in other words, the state before the reset) is d27924e. It was obtained by checking out a particular commit (though that's not important right now). So, to undo the reset, run git reset HEAD@{1}
(or git reset d27924e
).
If, on the other hand, you've run some other commands since then that update HEAD, the commit you want won't be at the top of the list, and you'll need to search through the reflog
.
One final note: It may be easier to look at the reflog
for the specific branch you want to un-reset, say master, rather than HEAD
:
$ git reflog show master
c24138b master@{0}: merge origin/master: Fast-forward
90a2bf9 master@{1}: merge origin/master: Fast-forward
[...]
This should have less noise it in than the general HEAD reflog
.
If, like me, you use Spyder IDE, you have to disable the interactive mode with :
plt.ioff()
(this command is automatically launched with the scientific startup)
If you want to enable it again, use :
plt.ion()
A No Framework JavaScript Approach, checks for both vertical and horizontal
/*
* hasScrollBars
*
* Checks to see if an element has scrollbars
*
* @returns {object}
*/
Element.prototype.hasScrollBars = function() {
return {"vertical": this.scrollHeight > this.style.height, "horizontal": this.scrollWidth > this.style.width};
}
Use it like this
if(document.getElementsByTagName("body")[0].hasScrollBars().vertical){
alert("vertical");
}
if(document.getElementsByTagName("body")[0].hasScrollBars().horizontal){
alert("horizontal");
}
Are you familiar with numpy.nan
?
You can create your own method such as:
def nans(shape, dtype=float):
a = numpy.empty(shape, dtype)
a.fill(numpy.nan)
return a
Then
nans([3,4])
would output
array([[ NaN, NaN, NaN, NaN],
[ NaN, NaN, NaN, NaN],
[ NaN, NaN, NaN, NaN]])
I found this code in a mailing list thread.
If triangle.lborderA
is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.
However, if triangle.lborderA
is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300)
does return true.
public static boolean isBiggerThanMaxLong(double in){
return in > Long.MAX_VALUE;
}
ptomato's code can also be written in a cleaner manner like:
ifeq ($(TARGET_CPU),x86) TARGET_CPU_IS_X86 := 1 else ifeq ($(TARGET_CPU),x86_64) TARGET_CPU_IS_X86 := 1 else TARGET_CPU_IS_X86 := 0 endif
This doesn't answer OP's question but as it's the top result on google, I'm adding it here in case it's useful to anyone else.
Try this (LINQ method syntax):
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
or in LINQ Query syntax:
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
Cast
is required, because Columns is of type DataColumnCollection which is a IEnumerable
, not IEnumerable<DataColumn>
. The other parts should be obvious.
This can be a solution .
[Test]
public void TestForOutParameterInMoq()
{
//Arrange
_mockParameterManager= new Mock<IParameterManager>();
Mock<IParameter > mockParameter= new Mock<IParameter >();
//Parameter affectation should be useless but is not. It's really used by Moq
IParameter parameter= mockParameter.Object;
//Mock method used in UpperParameterManager
_mockParameterManager.Setup(x => x.OutMethod(out parameter));
//Act with the real instance
_UpperParameterManager.UpperOutMethod(out parameter);
//Assert that method used on the out parameter of inner out method are really called
mockParameter.Verify(x => x.FunctionCalledInOutMethodAfterInnerOutMethod(),Times.Once());
}
Linear search also referred to as sequential search looks at each element in sequence from the start to see if the desired element is present in the data structure. When the amount of data is small, this search is fast.Its easy but work needed is in proportion to the amount of data to be searched.Doubling the number of elements will double the time to search if the desired element is not present.
Binary search is efficient for larger array. In this we check the middle element.If the value is bigger that what we are looking for, then look in the first half;otherwise,look in the second half. Repeat this until the desired item is found. The table must be sorted for binary search. It eliminates half the data at each iteration.Its logarithmic.
If we have 1000 elements to search, binary search takes about 10 steps, linear search 1000 steps.
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
This has worked for me. I have tried different methods but this was my best solution.
Open command prompt and type the following;
pip install opencv-python
.
(make sure your internet is on).
after that try importing it again.
Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window
and document
objects.
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
If you're interested in an implementation that will also deal with selections in <textarea>
and texty <input>
elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.
function getSelectionText() {_x000D_
var text = "";_x000D_
var activeEl = document.activeElement;_x000D_
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;_x000D_
if (_x000D_
(activeElTagName == "textarea") || (activeElTagName == "input" &&_x000D_
/^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&_x000D_
(typeof activeEl.selectionStart == "number")_x000D_
) {_x000D_
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);_x000D_
} else if (window.getSelection) {_x000D_
text = window.getSelection().toString();_x000D_
}_x000D_
return text;_x000D_
}_x000D_
_x000D_
document.onmouseup = document.onkeyup = document.onselectionchange = function() {_x000D_
document.getElementById("sel").value = getSelectionText();_x000D_
};
_x000D_
Selection:_x000D_
<br>_x000D_
<textarea id="sel" rows="3" cols="50"></textarea>_x000D_
<p>Please select some text.</p>_x000D_
<input value="Some text in a text input">_x000D_
<br>_x000D_
<input type="search" value="Some text in a search input">_x000D_
<br>_x000D_
<input type="tel" value="4872349749823">_x000D_
<br>_x000D_
<textarea>Some text in a textarea</textarea>
_x000D_
There is probably a way (or three) to do this... however, I see one issue with your goal: how do you know when all the files have been uploaded? To rephrase in a way that makes more sense... how do you know what "all" means? According to the documentation, init
gets called at the initialization of the Dropzone itself, and then you set up the complete
event handler to do something when each file that's uploaded is complete. But, what mechanism is the user given to allow the program to know when he's dropped all the files he's intended to drop? If you are assuming that he/she will do a batch drop (i.e., drop onto the Dropzone 2-whatever number of files, at once, in one drop action), then the following code could/possibly should work:
Dropzone.options.filedrop = {
maxFilesize: 4096,
init: function () {
var totalFiles = 0,
completeFiles = 0;
this.on("addedfile", function (file) {
totalFiles += 1;
});
this.on("removed file", function (file) {
totalFiles -= 1;
});
this.on("complete", function (file) {
completeFiles += 1;
if (completeFiles === totalFiles) {
doSomething();
}
});
}
};
Basically, you watch any time someone adds/removes files from the Dropzone, and keep a count in closure variables. Then, when each file download is complete, you increment the completeFiles
progress counter var, and see if it now equals the totalCount you'd been watching and updating as the user placed things in the Dropzone. (Note: never used the plug-in/JS lib., so this is best guess as to what you could do to get what you want.)
docker inspect -f '{{ json .Mounts }}' containerid | jq '.[]'
I know this is kinda late answer but another way besides yannick's answer https://stackoverflow.com/a/57062363/6603342 to use ! is to cast it as string thus telling TypeScript i am sure this is a string thus converting
let name1:string = person.name;//<<<Error here
to
let name1:string = person.name as string;
This will make the error go away but if by any chance this is not a string you will get a run-time error which is one of the reassons we are using TypeScript to ensure that the type matches and avoid such errors at compile time.
Objective-C code for copy Table from a Database to another Database
-(void) createCopyDatabase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;
NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *error;
if ([fileManager fileExistsAtPath:newdbPath]) {
[fileManager removeItemAtPath:newdbPath error:nil];
}
sqlite3 *database;
//open database
if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
NSLog(@"Error to open database");
}
NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];
sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to Attach = %s",error);
}
//Query for copy Table
NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
//Query for copy Table with Where Clause
sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
}
Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?
Something like request.Credentials = new NetworkCredential("UserName", "PassWord");
Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;
The voted answer (and also the swift version) has a small issue: there will be a big spacing on the right.
This is because the flow layout is customised to make the cell spacing exact, with a float left behaviour.
My solution is to manipulate the section inset, so that the section is align center, yet the spacing is exactly as specified.
In screenshot below, the item/line spacing is exactly 8pt, while the section left & right inset will be bigger than 8pt (to make it center aligned):
Swift code as such:
private let minItemSpacing: CGFloat = 8
private let itemWidth: CGFloat = 100
private let headerHeight: CGFloat = 32
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Create our custom flow layout that evenly space out the items, and have them in the center
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
layout.minimumInteritemSpacing = minItemSpacing
layout.minimumLineSpacing = minItemSpacing
layout.headerReferenceSize = CGSize(width: 0, height: headerHeight)
// Find n, where n is the number of item that can fit into the collection view
var n: CGFloat = 1
let containerWidth = collectionView.bounds.width
while true {
let nextN = n + 1
let totalWidth = (nextN*itemWidth) + (nextN-1)*minItemSpacing
if totalWidth > containerWidth {
break
} else {
n = nextN
}
}
// Calculate the section inset for left and right.
// Setting this section inset will manipulate the items such that they will all be aligned horizontally center.
let inset = max(minItemSpacing, floor( (containerWidth - (n*itemWidth) - (n-1)*minItemSpacing) / 2 ) )
layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)
collectionView.collectionViewLayout = layout
}
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
When using the official PHP images of Docker, use docker-php-ext-install bcmath
.
Source: https://hub.docker.com/_/php?tab=description#php-core-extensions
grep
and printf
Format each array member on a new line, then grep
the lines.
if printf '%s\n' "${array[@]}" | grep -x -q "search string"; then echo true; else echo false; fi
example:
$ array=("word", "two words")
$ if printf '%s\n' "${array[@]}" | grep -x -q "two words"; then echo true; else echo false; fi
true
Note that this has no problems with delimeters and spaces.
Here is an SSCCE,
package experiment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class KeyListenerTester extends JFrame implements KeyListener {
JLabel label;
public KeyListenerTester(String s) {
super(s);
JPanel p = new JPanel();
label = new JLabel("Key Listener!");
p.add(label);
add(p);
addKeyListener(this);
setSize(200, 100);
setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key typed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key typed");
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key pressed");
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key Released");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key Released");
}
}
public static void main(String[] args) {
new KeyListenerTester("Key Listener Tester");
}
}
Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings
My Net 5 solution that also handles null characters at the end:
hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );
static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
int realLength = 0;
for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
{
byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
if ( b != 0 ) //not NULL character
{
realLength = i + 2;
break;
}
}
var bytes = new byte[realLength / 2];
for ( var i = 0; i < bytes.Length; i++ )
{
bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
}
return encoding.GetString( bytes );
}
I was struggling with this for ages. What I finally did was go into the .npmrc file (which can be found in the user's directory followed by the user's name, ie. C:\Users\erikj/.npmrc), opened it with a text editor, manually removed any proxy settings and changed the http:// setting to https://. In this case, it is a matter of experimenting whether http or https will work for you. In my case, https worked. Go figure.
Check this thread out: read and write image file.
Also, have a look at this other question at Stackoverflow.
This is because the Python exec are not in the search path of your operating system. In windows, start CMD. Type in
setx PATH PythonPath
where PythonPath is usually C:\Python27
or C:\Python33
or C:\Users\<Your User Name>\AppData\Local\Programs\Python\Python37
depending on your Python version. After restarting the CMD, you should get see outcomes when typing
Python --version
As mentioned in this comment, the standard suggestions for re-ordering columns in a data.frame
are generally cumbersome and error-prone, especially if you have a lot of columns.
This function allows to re-arrange columns by position: specify a variable name and the desired position, and don't worry about the other columns.
##arrange df vars by position
##'vars' must be a named vector, e.g. c("var.name"=1)
arrange.vars <- function(data, vars){
##stop if not a data.frame (but should work for matrices as well)
stopifnot(is.data.frame(data))
##sort out inputs
data.nms <- names(data)
var.nr <- length(data.nms)
var.nms <- names(vars)
var.pos <- vars
##sanity checks
stopifnot( !any(duplicated(var.nms)),
!any(duplicated(var.pos)) )
stopifnot( is.character(var.nms),
is.numeric(var.pos) )
stopifnot( all(var.nms %in% data.nms) )
stopifnot( all(var.pos > 0),
all(var.pos <= var.nr) )
##prepare output
out.vec <- character(var.nr)
out.vec[var.pos] <- var.nms
out.vec[-var.pos] <- data.nms[ !(data.nms %in% var.nms) ]
stopifnot( length(out.vec)==var.nr )
##re-arrange vars by position
data <- data[ , out.vec]
return(data)
}
Now the OP's request becomes as simple as this:
table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
table
## Time In Out Files
##1 1 2 3 4
##2 2 3 4 5
arrange.vars(table, c("Out"=2))
## Time Out In Files
##1 1 3 2 4
##2 2 4 3 5
To additionally swap Time
and Files
columns you can do this:
arrange.vars(table, c("Out"=2, "Files"=1, "Time"=4))
## Files Out In Time
##1 4 3 2 1
##2 5 4 3 2
First, open a file:
with open("filename") as fileobj:
for line in fileobj:
for ch in line:
print(ch)
This goes through every line in the file and then every character in that line.
As wizzard pointed out, the correct method is,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
If you wanted to make a time stamp without milliseconds you can use,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s
on a Unix terminal.
Sometimes Your rake tasks doesn't get loaded in console, In that case you can try the following commands
require "rake"
YourApp::Application.load_tasks
Rake::Task["Namespace:task"].invoke
For those running in such issues right now, just try to put an alias for the table, this should the trick, e.g:
SELECT myvalue
INTO myvar
FROM mytable x
WHERE x.anothervalue = 1;
It worked for me.
Cheers.
Better yet use a oneliner:
Dump remoteDB to localDB:
mysqldump -uroot -pMypsw -h remoteHost remoteDB | mysql -u root -pMypsw localDB
Dump localDB to remoteDB:
mysqldump -uroot -pmyPsw localDB | mysql -uroot -pMypsw -h remoteHost remoteDB
You could write a method that takes an instance of an interface which defines a check(Cat)
method, where that method can be implemented with whatever property-checking you want.
Better yet, make it generic:
public interface Checker<T> {
public boolean check(T obj);
}
public class CatChecker implements Checker<Cat> {
public boolean check(Cat cat) {
return (cat.age == 3); // or whatever, implement your comparison here
}
}
// put this in some class
public static <T> Collection<T> findAll(Collection<T> coll, Checker<T> chk) {
LinkedList<T> l = new LinkedList<T>();
for (T obj : coll) {
if (chk.check(obj))
l.add(obj);
}
return l;
}
Of course, like other people are saying, this is what relational databases were made for...
Override the OnFormClosing method.
CAUTION: You need to check the CloseReason and only alter the behaviour if it is UserClosing. You should not put anything in here that would stall the Windows shutdown routine.
Application Shutdown Changes in Windows Vista
This is from the Windows 7 logo program requirements.
Check the configurations in {M2_HOME}\conf\setting.xml as mentioned in the following link.
http://www.mkyong.com/maven/where-is-maven-local-repository/
Hope this helps.
git revert
is less dangerous than some of the approaches suggested here:
prompt> git revert 35f6af6f77f116ef922e3d75bc80a4a466f92650
[master 71738a9] Revert "Issue #482 - Fixed bug."
4 files changed, 30 insertions(+), 42 deletions(-)
prompt> git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
prompt>
Replace 35f6af6f77f116ef922e3d75bc80a4a466f92650 with your own commit.
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
Here a simple one liners to check if only one parameter is given otherwise exit the script:
[ "$#" -ne 1 ] && echo "USAGE $0 <PARAMETER>" && exit
Definitely not the most correct way, but if you just need a quick solution to get the date without the time and you do not wish to use a third party library this should do
Date db = db.substring(0, 10) + db.substring(23,28);
I only needed the date for visual purposes and couldn't Joda so I substringed.
Instant i = Instant.ofEpochSecond(cal.getTime);
Read more here and here
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException
because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
The author asked for explode, to you can use explode like this
$resultArray = explode("\t", $inputString);
Note: you must used double quote, not single.
I often find myself utilizing the --build-arg
option for this purpose. For example after putting the following in the Dockerfile:
ARG SSH_KEY
RUN echo "$SSH_KEY" > /root/.ssh/id_rsa
You can just do:
docker build -t some-app --build-arg SSH_KEY="$(cat ~/file/outside/build/context/id_rsa)" .
But note the following warning from the Docker documentation:
Warning: It is not recommended to use build-time variables for passing secrets like github keys, user credentials etc. Build-time variable values are visible to any user of the image with the docker history command.
I ran into this challenge today in OSX El Capitan with Chrome v51. The page in question worked fine in Safari. I tried nearly every suggestion on this page - none worked right - all had side-effects... I ended up implementing the code below - super simple - no side-effects (still works as before in Safari).
Solution: Toggle a class on the problematic element as needed. Each toggle will force a redraw. (I used jQuery for convenience, but vanilla JavaScript should be no problem...)
jQuery Class Toggle
$('.slide.force').toggleClass('force-redraw');
CSS Class
.force-redraw::before { content: "" }
And that's it...
NOTE: You have to run the snippet below "Full Page" in order to see the effect.
$(window).resize(function() {_x000D_
$('.slide.force').toggleClass('force-redraw');_x000D_
});
_x000D_
.force-redraw::before {_x000D_
content: "";_x000D_
}_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
overflow: hidden;_x000D_
}_x000D_
.slide-container {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow-x: scroll;_x000D_
overflow-y: hidden;_x000D_
white-space: nowrap;_x000D_
padding-left: 10%;_x000D_
padding-right: 5%;_x000D_
}_x000D_
.slide {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
height: 30%;_x000D_
border: 1px solid green;_x000D_
}_x000D_
.slide-sizer {_x000D_
height: 160%;_x000D_
pointer-events: none;_x000D_
//border: 1px solid red;_x000D_
_x000D_
}_x000D_
.slide-contents {_x000D_
position: absolute;_x000D_
top: 10%;_x000D_
left: 10%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>_x000D_
This sample code is a simple style-based solution to maintain aspect ratio of an element based on a dynamic height. As you increase and decrease the window height, the elements should follow and the width should follow in turn to maintain the aspect ratio. You will notice that in Chrome on OSX (at least), the "Not Forced" element does not maintain a proper ratio._x000D_
</p>_x000D_
<div class="slide-container">_x000D_
<div class="slide">_x000D_
<img class="slide-sizer" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">_x000D_
<div class="slide-contents">_x000D_
Not Forced_x000D_
</div>_x000D_
</div>_x000D_
<div class="slide force">_x000D_
<img class="slide-sizer" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">_x000D_
<div class="slide-contents">_x000D_
Forced_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
A simple fix could be Content-Type: application/json
You are probably making a REST API call to get the response.
Mostly you are not setting Content-Type: application/json
when you the request.
Content-Type: application/x-www-form-urlencoded
will be chosen which might be causing this exception.
Simply alter your table, no need to any thing. just run this query on database.
ALTER TABLE table_name
CONVERT TO CHARACTER SET utf8
it will definately work.
A sidenote to consider, you can store arrays in Postgres.
This is because your Image name contains "-" symbol . the only allowed characters are [a-zA-Z0-9_.]
Thanks
For Mac/Linux debug keystore, the Android docs have:
keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore
But there is something that may not be obvious: If you put the backslash, make sure to do a shift + return
in terminal after the backslash so that the second that starts with -alias
is on a new line. Simply pasting as-is will not work.
Your terminal (if successful) will look something like this:
$ keytool -exportcert -list -v \
? -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password:
The default debug password is: android
Side note: In Android Studio you can manage signing in:
File > Project Structure > Modules - (Your App) > Signing
Update your code to assign your prototype to the Error.prototype and the instanceof and your asserts work.
function NotImplementedError(message = "") {
this.name = "NotImplementedError";
this.message = message;
}
NotImplementedError.prototype = Error.prototype;
However, I would just throw your own object and just check the name property.
throw {name : "NotImplementedError", message : "too lazy to implement"};
Edit based on comments
After looking at the comments and trying to remember why I would assign prototype to Error.prototype
instead of new Error()
like Nicholas Zakas did in his article, I created a jsFiddle with the code below:
function NotImplementedError(message = "") {
this.name = "NotImplementedError";
this.message = message;
}
NotImplementedError.prototype = Error.prototype;
function NotImplementedError2(message = "") {
this.message = message;
}
NotImplementedError2.prototype = new Error();
try {
var e = new NotImplementedError("NotImplementedError message");
throw e;
} catch (ex1) {
console.log(ex1.stack);
console.log("ex1 instanceof NotImplementedError = " + (ex1 instanceof NotImplementedError));
console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
console.log("ex1.name = " + ex1.name);
console.log("ex1.message = " + ex1.message);
}
try {
var e = new NotImplementedError2("NotImplementedError2 message");
throw e;
} catch (ex1) {
console.log(ex1.stack);
console.log("ex1 instanceof NotImplementedError2 = " + (ex1 instanceof NotImplementedError2));
console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
console.log("ex1.name = " + ex1.name);
console.log("ex1.message = " + ex1.message);
}
_x000D_
The console output was this.
undefined
ex1 instanceof NotImplementedError = true
ex1 instanceof Error = true
ex1.name = NotImplementedError
ex1.message = NotImplementedError message
Error
at window.onload (http://fiddle.jshell.net/MwMEJ/show/:29:34)
ex1 instanceof NotImplementedError2 = true
ex1 instanceof Error = true
ex1.name = Error
ex1.message = NotImplementedError2 message
This confirmes the "problem" I ran into was the stack property of the error was the line number where new Error()
was created, and not where the throw e
occurred. However, that may be better that having the side effect of a NotImplementedError.prototype.name = "NotImplementedError"
line affecting the Error object.
Also, notice with NotImplementedError2
, when I don't set the .name
explicitly, it is equal to "Error". However, as mentioned in the comments, because that version sets prototype to new Error()
, I could set NotImplementedError2.prototype.name = "NotImplementedError2"
and be OK.
UPDATE
Here it is assumed that your media (Image/Video) is already added to content media provider. If not then you will not able to get the content URL as exact what you want. Instead there will be file Uri.
I had same question for my file explorer activity. You should know that the contenturi for file only supports mediastore data like image, audio and video. I am giving you the code for getting image content uri from selecting an image from sdcard. Try this code, maybe it will work for you...
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
For support android Q
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
Uri picCollection = MediaStore.Images.Media
.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentValues picDetail = new ContentValues();
picDetail.put(MediaStore.Images.Media.DISPLAY_NAME, imageFile.getName());
picDetail.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
picDetail.put(MediaStore.Images.Media.RELATIVE_PATH,"DCIM/" + UUID.randomUUID().toString());
picDetail.put(MediaStore.Images.Media.IS_PENDING,1);
Uri finaluri = resolver.insert(picCollection, picDetail);
picDetail.clear();
picDetail.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(picCollection, picDetail, null, null);
return finaluri;
}else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
} else {
return null;
}
}
}
Try dragging a UIView
onto the screen in IB. From there you can drag a UIImageView
and UILabel
into the view you just created. Set the image of the UIImageView
in the properties inspector as the custom bullet image (which you will have to add to your project by dragging it into the navigation pane) and you can write some text in the label.
I think you want SYSDATE
, not GETDATE()
. Try it:
UPDATE TableName SET LastModifiedDate = (SELECT SYSDATE FROM DUAL);
There can be many possible reasons for this failure.
Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.
I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again
This following program can handle large numbers ( number of digits greater than 20 )
package com.isEven.java;
import java.util.Scanner;
public class isEvenValuate{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String digit = in.next();
int y = Character.getNumericValue(digit.charAt(digit.length()-1));
boolean isEven = (y&1)==0;
if(isEven)
System.out.println("Even");
else
System.out.println("Odd");
}
}
Here is the output ::
122873215981652362153862153872138721637272
Even
Here is a Hand Made Solution:
function iterationForObject() {
let base = 0,
Keys= Object.keys(this);
return {
next: () => {
return {
value: {
"key": Keys[base],
"value": this[Keys[base]]
},
done: !(base++ < Keys.length)
};
}
};
}
Object.prototype[Symbol.iterator] = iterationForObject;
And Then You Can Loop Any Object:
for ( let keyAndValuePair of (Object Here) ) {
console.log(`${keyAndValuePair.key} => ${keyAndValuePair.value}`);
}
youll need to use the latest http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js in conjunction with one of the Microsoft's CDN for getting your validation file.
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
prevent arrow only available for any object else SELECT, well actually i haven't tes on another object LOL. but it can stop arrow event on page and input type.
i already try to block arrow left and right to change the value of SELECT object using "e.preventDefault()" or "return false" on "kepress" "keydown" and "keyup" event but it still change the object value. but the event still tell you that arrow was pressed.
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);
Here's some advice from someone with an environment where we have folders containing tens of millions of files.
To answer your question more directly: If you're looking at 100K entries, no worries. Go knock yourself out. If you're looking at tens of millions of entries, then either:
a) Make plans to sub-divide them into sub-folders (e.g., lets say you have 100M files. It's better to store them in 1000 folders so that you only have 100,000 files per folder than to store them into 1 big folder. This will create 1000 folder indices instead of a single big one that's more likely to hit the max # of fragments limit or
b) Make plans to run contig.exe on a regular basis to keep your big folder's index defragmented.
Read below only if you're bored.
The actual limit isn't on the # of fragment, but on the number of records of the data segment that stores the pointers to the fragment.
So what you have is a data segment that stores pointers to the fragments of the directory data. The directory data stores information about the sub-directories & sub-files that the directory supposedly stored. Actually, a directory doesn't "store" anything. It's just a tracking and presentation feature that presents the illusion of hierarchy to the user since the storage medium itself is linear.
I have implemented MultipartReader NuGet package for ASP.NET 4 for reading multipart form data. It is based on Multipart Form Data Parser, but it supports more than one file.
Asynchronous function in line 38:
$( ".class#id" ).hover(function() {
Your javascript
});
Please make sure your gradle build your compileSdkVersion has its sdk installed in your project. Then just reload your project everything should be fine.
Since there is no way to determine the lenght of all lines without reading them, you have no choice but to iterate over all lines before your starting line. All you can do is to make it look nice. If the file is really huge then you might want to use a generator based approach:
from itertools import dropwhile
def iterate_from_line(f, start_from_line):
return (l for i, l in dropwhile(lambda x: x[0] < start_from_line, enumerate(f)))
for line in iterate_from_line(open(filename, "r", 0), 141978):
DoSomethingWithThisLine(line)
Note: the index is zero based in this approach.
Let's say your script is called my_script.py
and you have put it in your Downloads folder.
There are many ways of installing Python, but homebrew is the easiest.
0) Open Terminal.app
1) Install homebrew (by pasting the following text into Terminal.app and pressing the Enter key)
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
2) Install Python using homebrew
brew install python
3) cd
into the directory that contains your Python script (as an example I'm using the Downloads (Downloads
) folder in your home (~
) folder):
cd ~/Downloads
4) Run the script using the python3
executable
python3 my_script.py
You can also skip step 3 and give python3
an absolute path instead
python3 ~/Downloads/my_script.py
Instead of typing out that whole thing (~/Downloads/my_script.py
), you can find the .py
file in Finder.app and just drag it into the Terminal.app window which should type out the path for you.
If you have spaces or certain other symbols somewhere in your filename you need to enclose the file name in quotes:
python3 "~/Downloads/some directory with spaces/and a filename with a | character.py"
Note that you need to install it as brew install python
but later use the command python3
(with a 3
at the end).
I solved this by delaying the mRecycler.setAdapter(itemsAdapter)
till after adding all the items to the adapter with mRecycler.addAll(items)
and it worked. No idea why i did that to begin with, it was from a library's code that I looked over and saw those lines in the "wrong order", I'm pretty sure this is it though, please if someone can confirm it explain why it's so? Not sure if this is a valid answer even
If else condition, also called alternatives in UML terms can indeed be represented in sequence diagrams. Here is a link where you can find some nice resources on the subject http://www.ibm.com/developerworks/rational/library/3101.html
It causes the error when you access $(this).val()
when it called by change event this
points to the invoker i.e. CourseSelect
so it is working and and will get the value of CourseSelect
. but when you manually call it this
points to document. so either you will have to pass the CourseSelect
object or access directly like $("#CourseSelect").val()
instead of $(this).val()
.
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
In the book written by Charles Petzold titled "Code" he says there are 6 gates. There is the AND logical gate, the OR gate, the NOR gate, the NAND gate, and the XOR gate. He also mentions the 6th gate briefly calling it the "coincidence gate" and implies it's not used very often. He says it has the opposite output of a XOR gate because a XOR gate has the output of "false" when it has two true or two false sides of the equation and the only way for a XOR gate to have its output be true is for one of the sides of the equation to be true and the other to be false, it doesn't matter which. The coincidence is the exact opposite of this because with the coincidence gate if one is true and the other is false (doesn't matter which is which) then it will have its output be "false" in both those cases. And the way for a coincidence gate to have its output be "true" is for both sides to be either false or true. If both are false the coincidence gate will evaluate as true. If both are true then the coincidence gate will also output "true" in that case as well.
So in the cases where the XOR gate outputs "false", the coincidence gate will output "true". And in the cases where the XOR gate will output "true", the coincidence gate will output "false".
It is often preferable to avoid loops and use vectorized functions. If that is not possible there are two approaches:
data.frame
. This is not recommended because indexing is slow for data.frames
.data.frame
afterwards. A list
is very useful here.Example to illustrate the general approach:
mylist <- list() #create an empty list
for (i in 1:5) {
vec <- numeric(5) #preallocate a numeric vector
for (j in 1:5) { #fill the vector
vec[j] <- i^j
}
mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix
In this example it is not necessary to use a list
, you could preallocate a matrix
. However, if you do not know how many iterations your loop will need, you should use a list
.
Finally here is a vectorized alternative to the example loop:
outer(1:5,1:5,function(i,j) i^j)
As you see it's simpler and also more efficient.
You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do
pip install -U scikit-learn
If you are on windows you might want to check out these pages.
better use timer:
Sub wait (sec)
dim temp
temp=timer
do while timer-temp<sec
loop
end Sub
you can use display:flex
to do this : http://codepen.io/anon/pen/yCKuz
html,body {
height:100%;
width:100%;
margin:0;
}
body {
display:flex;
}
form {
margin:auto;/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
}
or display:table
http://codepen.io/anon/pen/LACnF/
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
display:table;
}
body {
display:table-cell;
vertical-align:middle;
}
form {
display:table;/* shrinks to fit content */
margin:auto;
}
PARTITION BY
segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.
In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER
But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency
newid()
produces GUID, so what shall you expect by this expression?
select
hi,ho,
row_number() over(partition by newid() order by hi,ho)
from tbl;
...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1
Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1
An example, this is your data:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');
Then this is analogous to your query:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho)
from tbl;
What will be the output of that?
HI HO COLUMN_2
A X 1
A Y 1
A Z 1
B W 1
B W 2
C L 1
C L 2
You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.
Now, why is the ORDER BY
needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY
; whereas in Postgresql, ORDER BY
on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
Your ORDER BY
on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION
with no ORDER BY
, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
ORDER BY newid())
seq_no
FROM CUSTOMER_DETAILS cdt
You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid()
for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION
with no ORDER BY
Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table
It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.
Live test: http://www.sqlfiddle.com/#!3/27821/6
But as dbaseman have noticed also, it's useless to partition and order on same columns.
You have a set of data like this:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');
Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
Output:
HI HO ROW_QUERY_A
A X 1
A X 2
A X 3
B Y 1
B Y 2
C Z 1
C Z 2
See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)
You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');
select
hi,ho,
row_number() over(partition by hi order by ho) as nr
from tbl;
PARTITION BY hi
operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho
Output:
HI HO NR
A D 1
A E 2
A F 3
B E 1
B F 2
C D 1
C E 2
That data set makes more sense
Live test: http://www.sqlfiddle.com/#!3/d0b44/1
And this is similar to your query with same columns on both PARTITION BY and ORDER BY:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
And this is the ouput:
HI HO NR
A D 1
A E 1
A F 1
B E 1
B F 1
C D 1
C E 1
See? no sense?
Live test: http://www.sqlfiddle.com/#!3/d0b44/3
Finally this might be the right query:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
ORDER BY
-- removed: cdt.country_code, cdt.account,
cdt.currency) -- keep
seq_no
FROM CUSTOMER_DETAILS cdt
1. For MySQL:
SELECT FIND_IN_SET(5, columnname) AS result
FROM table
2.For Postgres SQL :
SELECT *
FROM TABLENAME f
WHERE 'searchvalue' = ANY (string_to_array(COLUMNNAME, ','))
Example
select *
from customer f
where '11' = ANY (string_to_array(customerids, ','))
URI is kind of the super class of URL's and URN's. Wikipedia has a fine article about them with links to the right set of RFCs.
On Windows 10, for me
ngrok http 80
behaves like this:
Try including the io.h
file. It seems to be the Visual Studio's equivalent of unistd.h
.
I hope this helps.
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
From my experience, I have the following methods to solved the famous LazyInitializationException:
(1) Use Hibernate.initialize
Hibernate.initialize(topics.getComments());
(2) Use JOIN FETCH
You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is some how like EAGER fetching.
(3) Use OpenSessionInViewFilter
LazyInitializationException often occur in view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to performance issue if not use correctly.
var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();
User can use this of like query in Linq and fill the student model.
Do the following steps to resolve the problem
Ensure that the JDK is already installed.
If the installer is on a CD, Copy the EXE file for the Netbeans 6.5.1 installer onto your hard disk.
Note the location of the installer.
Open a Command Prompt running as administrator: Go to Start button > All Programs > Accessories Right click Command Prompt Select Run as administrator
In the Command Prompt use the cd command to change to the directory containing the installer.
Execute the following command to extract the contents of the installer: [Note: You might need to change the name of the installer to match the one you have.]
netbeans-6.5.1-ml-java-windows.exe --extract
Execute the following command to manually execute the installer:
java -jar bundle.jar
You will see rapid scrolling output in the Command Prompt window for a few moments, then the installer window will appear to begin the installation process.
In Swift 3 / iOS 10+ this now looks like
if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
UIApplication.shared.open(url, completionHandler: .none)
}
And another version that returns the key value from the array element in which the value is found (no recursion, optimized for speed):
// if the array is
$arr['apples'] = array('id' => 1);
$arr['oranges'] = array('id' => 2);
//then
print_r(search_array($arr, 'id', 2);
// returns Array ( [oranges] => Array ( [id] => 2 ) )
// instead of Array ( [0] => Array ( [id] => 2 ) )
// search array for specific key = value
function search_array($array, $key, $value) {
$return = array();
foreach ($array as $k=>$subarray){
if (isset($subarray[$key]) && $subarray[$key] == $value) {
$return[$k] = $subarray;
return $return;
}
}
}
Thanks to all who posted here.
On .Net Core 3.1 just follow Microsoft Doc that it is pretty simple: kestrel-aspnetcore-3.1
To summarize:
Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs
:
// using Microsoft.Extensions.DependencyInjection;
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
services.Configure<KestrelServerOptions>(
context.Configuration.GetSection("Kestrel"));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Add the below basic config to appsettings.json
file (more config options on Microsoft article):
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://0.0.0.0:5002"
}
}
}
Open CMD or Console on your project Publish/Debug/Release binaries folder and run:
dotnet YourProject.dll
Enjoy exploring your site/api at your http://localhost:5002
PHP by itself has no SMS module or functions and doesn't allow you to send SMS.
SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.
Usually people in telecom business use Asterisk to handle calls and sms programming.
Try using this:
var x:Int!
var xTimesTwo:Int {
get {
return x * 2
}
set {
x = newValue / 2
}
}
This is basically Jack Wu's answer, but the difference is that in Jack Wu's answer his x variable is var x: Int
, in mine, my x variable is like this: var x: Int!
, so all I did was make it an optional type.
Have you used the variable sum
anywhere else? That would explain it.
>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
The name sum
doesn't point to the function anymore now, it points to an integer.
Solution: Don't call your variable sum
, call it total
or something similar.
Here's a two line code I found online that might be helpful for a beginner
# Absolute value of the 32/64
abs_image_in32_64 = np.absolute(image_in32_64)
image_8U = np.uint8(abs_image_in32_64)
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
I believe you need to specify "Option Infer On" for this to work.
Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.
Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.
Opinion incoming:
Also, you mention that you've got "Option Explicit Off". Please don't do this.
Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":
Dim X as Integer
Y = 3
This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.
The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call. i.e.
Please have a look at the below example for better understanding:
package com.stackoverflow.works;
public class ArithmeticOperations {
public static int add(int x, int y) { //x, y are parameters here
return x + y;
}
public static void main(String[] args) {
int x = 10;
int y = 20;
int sum = add(x, y); //x, y are arguments here
System.out.println("SUM IS: " +sum);
}
}
Thank you!