See This Image and Add This line in your android AndroidManifest.xml
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
This can be solved by the following step:
Please ensure "Windows Hypervisor Platform" is installed. If it's not installed, install it, restart your computer and you will be good to go.
For me, the problem was passing in a larger than normally expected HTTP header. I resolved it by setting maxHttpHeaderSize="1048576" attribute on the Connector node in server.xml.
This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):
warning C4101: 'i': unreferenced local variable
After I commented this unused i
, and compiled it, the other error went away.
In my case, it was due to an IP address that Apache is listening to. Previously I have set it to 192.168.10.6 and recently Apache service is not running. I noticed that due to My laptop wifi changed recently and new IP is different. After fixing the wifi IP to laptop previous IP, Apache service is running again without any error.
Also if you don't want to change wifi IP then remove/comment that hardcode IP in httpd.conf file to resolve conflict.
Did you maybe use some <tab>
instead of spaces?
Try remove all the spaces before the code and readd them using <space>
characters, just to be sure it's not a <tab>
.
The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under
Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job
Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).
Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.
Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.
Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.
Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.
Check whether you are scheduling a task to trigger an executable (.exe) or a batch (.bat) file. If you have scheduled any other file to open (for example a .txt or .docx file), the file not open.
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
If you are running on an NGINX / PHP-FPM stack, your best bet is to probably just reload php-fpm
service php-fpm reload
(or whatever your reload command may be on your system)
You probably have a log4j.properties file somewhere in the project. In that file you can configure which level of debug output you want. See this example:
log4j.rootLogger=info, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.logger.com.example=debug
The first line sets the log level for the root logger to "info", i.e. only info, warn, error and fatal will be printed to the console (which is the appender defined a little below that).
The last line sets the logger for com.example.* (if you get your loggers via LogFactory.getLogger(getClass())
) will be at debug level, i.e. debug will also be printed.
The options for managing tablespaces have got a lot better over the versions starting with 8i. This is especially true if you are using the appropriate types of file for a temporary tablespace (i.e. locally managed tempfiles).
So, it could be as simple as this command, which will shrink your tablespace to 128 meg...
alter tablespace <your_temp_ts> shrink space keep 128M;
The Oracle online documentation is pretty good. Find out more.
edit
It would appear the OP has an earlier version of the database. With earlier versions we have to resize individual datafiles. So, first of all, find the file names. One or other of these queries should do it...
select file_name from dba_data_files where tablespace_name = '<your_temp_ts>'
/
select file_name from dba_temp_files where tablespace_name = '<your_temp_ts>'
/
Then use that path in this command:
alter database datafile '/full/file/path/temp01.dbf' resize 128m
/
Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
Then in the project Add Reference -> Browse. Push the browse button and go to the C:\Users\UserName\Documents\Visual Studio 2015\Projects\ProjectName\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45 and add the needed .dll file
To add to @Craig Schwarze answer,
Here are some related MSDN links:
Loading and Running a Local Package Programmatically:
Loading and Running a Remote Package Programmatically
Capturing Events from a Running Package:
using System;
using Microsoft.SqlServer.Dts.Runtime;
namespace RunFromClientAppWithEventsCS
{
class MyEventListener : DefaultEvents
{
public override bool OnError(DtsObject source, int errorCode, string subComponent,
string description, string helpFile, int helpContext, string idofInterfaceWithError)
{
// Add application-specific diagnostics here.
Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
return false;
}
}
class Program
{
static void Main(string[] args)
{
string pkgLocation;
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
pkgLocation =
@"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
@"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
app = new Application();
pkg = app.LoadPackage(pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
Console.WriteLine(pkgResults.ToString());
Console.ReadKey();
}
}
}
this should serve the purpose
android:textAlignment="textStart"
import os
import sys
Assuming test.sh is the shell script that you would want to execute
os.system("sh test.sh")
With Git 2.0, git add -A
is default: git add .
equals git add -A .
.
git add <path>
is the same as "git add -A <path>
" now, so that "git add dir/
" will notice paths you removed from the directory and record the removal.
In older versions of Git, "git add <path>
" ignored removals.You can say "
git add --ignore-removal <path>
" to add only added or modified paths in<path>
, if you really want to.
git add -A
is like git add :/
(add everything from top git repo folder).
Note that git 2.7 (Nov. 2015) will allow you to add a folder named ":
"!
See commit 29abb33 (25 Oct 2015) by Junio C Hamano (gitster
).
Note that starting git 2.0 (Q1 or Q2 2014), when talking about git add .
(current path within the working tree), you must use '.
' in the other git add
commands as well.
That means:
"
git add -A .
" is equivalent to "git add .; git add -u .
"
(Note the extra '.
' for git add -A
and git add -u
)
Because git add -A
or git add -u
would operate (starting git 2.0 only) on the entire working tree, and not just on the current path.
Those commands will operate on the entire tree in Git 2.0 for consistency with "
git commit -a
" and other commands. Because there will be no mechanism to make "git add -u
" behave as if "git add -u .
", it is important for those who are used to "git add -u
" (without pathspec) updating the index only for paths in the current subdirectory to start training their fingers to explicitly say "git add -u .
" when they mean it before Git 2.0 comes.A warning is issued when these commands are run without a pathspec and when you have local changes outside the current directory, because the behaviour in Git 2.0 will be different from today's version in such a situation.
$("#filetosend").prop('files')[0]
Should look like this:
UPDATE DHE.dbo.tblAccounts
SET DHE.dbo.tblAccounts.ControllingSalesRep =
DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
from DHE.dbo.tblAccounts
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink
ON DHE.dbo.tblAccounts.AccountCode =
DHE_Import.tblSalesRepsAccountsLink.AccountCode
Update table is repeated in FROM clause.
Content-Type: application/force-download
means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".
Use the correct mime type for whatever media you are using (e.g. audio/mpeg
for mp3).
Use the Content-Disposition: attachment; etc etc
header if you want to encourage the client to download it instead of following the default behaviour.
You can use the CSS property background-size
and set it to cover
or contain
, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).
Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.
body {
background-image: url(image.jpg); /* image */
background-position: center; /* center the image */
background-size: cover; /* cover the entire window */
}
Just follow this
idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))
OR
idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))
And forget all others, else the brain won't be able to map all the formats.
The easiest way is to not store the count, relying on the COUNT aggregate function to reflect the value as it is in the database:
SELECT c.category_name,
COUNT(p.post_id) AS num_posts
FROM CATEGORY c
LEFT JOIN POSTS p ON p.category_id = c.category_id
You can create a view to house the query mentioned above, so you can query the view just like you would a table...
But if you're set on storing the number, use:
UPDATE CATEGORY
SET count = count + 1
WHERE category_id = ?
..replacing "?" with the appropriate value.
I do not agree with the rules given in the original post. Here are my rules:
1) You use structs for performance when stored in arrays. (see also When are structs the answer?)
2) You need them in code passing structured data to/from C/C++
3) Do not use structs unless you need them:
ScheduledExecutorService
The Answer by Lee is close, but only runs once. The Question seems to be asking to run indefinitely until an external state changes (until the response from a web site/service changes).
The ScheduledExecutorService
interface is part of the java.util.concurrent
package built into Java 5 and later as a more modern replacement for the old Timer
class.
Here is a complete example. Call either scheduleAtFixedRate
or scheduleWithFixedDelay
.
ScheduledExecutorService executor = Executors.newScheduledThreadPool ( 1 );
Runnable r = new Runnable () {
@Override
public void run () {
try { // Always wrap your Runnable with a try-catch as any uncaught Exception causes the ScheduledExecutorService to silently terminate.
System.out.println ( "Now: " + Instant.now () ); // Our task at hand in this example: Capturing the current moment in UTC.
if ( Boolean.FALSE ) { // Add your Boolean test here to see if the external task is fonud to be completed, as described in this Question.
executor.shutdown (); // 'shutdown' politely asks ScheduledExecutorService to terminate after previously submitted tasks are executed.
}
} catch ( Exception e ) {
System.out.println ( "Oops, uncaught Exception surfaced at Runnable in ScheduledExecutorService." );
}
}
};
try {
executor.scheduleAtFixedRate ( r , 0L , 5L , TimeUnit.SECONDS ); // ( runnable , initialDelay , period , TimeUnit )
Thread.sleep ( TimeUnit.MINUTES.toMillis ( 1L ) ); // Let things run a minute to witness the background thread working.
} catch ( InterruptedException ex ) {
Logger.getLogger ( App.class.getName () ).log ( Level.SEVERE , null , ex );
} finally {
System.out.println ( "ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed." );
executor.shutdown ();
}
Expect output like this:
Now: 2016-12-27T02:52:14.951Z
Now: 2016-12-27T02:52:19.955Z
Now: 2016-12-27T02:52:24.951Z
Now: 2016-12-27T02:52:29.951Z
Now: 2016-12-27T02:52:34.953Z
Now: 2016-12-27T02:52:39.952Z
Now: 2016-12-27T02:52:44.951Z
Now: 2016-12-27T02:52:49.953Z
Now: 2016-12-27T02:52:54.953Z
Now: 2016-12-27T02:52:59.951Z
Now: 2016-12-27T02:53:04.952Z
Now: 2016-12-27T02:53:09.951Z
ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed.
Now: 2016-12-27T02:53:14.951Z
Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError
). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError
.
Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).
If that's not enough, consider converting to a sqlite3
database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.
You can read a group of txt files in a folder and echo the contents like this.
<?php
$directory = "folder/";
$dir = opendir($directory);
$filenames = [];
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if($type !== 'file') continue;
$filenames[] = $filename;
}
closedir($dir);
?>
In BIDS or SSDT-BI, do the following:
To render in PDF correctly Body Width + Left margin + Right margin must be less than or equal to Page width. When you see blank pages being rendered it is almost always because the body width plus margins is greater than the page width.
Remember: (Body Width + Left margin + Right margin) <= (Page width)
i just switched positions and worked for me (showing only mobile )
<style>_x000D_
.MobileContent {_x000D_
_x000D_
display: none;_x000D_
text-align:center;_x000D_
_x000D_
}_x000D_
_x000D_
@media screen and (max-width: 768px) {_x000D_
_x000D_
.MobileContent {_x000D_
_x000D_
display:block;_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
</style>_x000D_
<div class="MobileContent"> Something </div>
_x000D_
Late reply, but adding that Mongoose also has the concept of Subdocuments
With this syntax, you should be able to reference your userSchema
as a type in your postSchema
like so:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var postSchema = new Schema({
name: String,
postedBy: userSchema,
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Note the updated postedBy
field with type userSchema
.
This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.
You can try this also:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
That CSS property is all you need it works for me...When previewing in Chrome you have the option to see it BW and Color(Color: Options- Color or Black and white) so if you don't have that option, then I suggest to grab this Chrome extension and make your life easier:
The site you added on fiddle needs this in your media print css (you have it just need to add it...
media print CSS in the body:
@media print {
body {-webkit-print-color-adjust: exact;}
}
UPDATE OK so your issue is bootstrap.css...it has a media print css as well as you do....you remove that and that should give you color....you need to either do your own or stick with bootstraps print css.
When I click print on this I see color.... http://jsfiddle.net/rajkumart08/TbrtD/1/embedded/result/
I think the problem is given in the error message, although it is not very easy to spot:
IndexError: too many indices for array
xs = data[:, col["l1" ]]
'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data
is not 2D (it's either 1D or None).
This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None)
does not throw an Error
, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile
function.
I highly recommend in your for
loop inserting:
print(data)
This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1
list (i.e. one file) that is giving the issue.
Try something like
"Line 1" & Environment.NewLine & "Line 2"
I tried with this method and it significantly reduced my database insert execution time.
List<string> toinsert = new List<string>();
StringBuilder insertCmd = new StringBuilder("INSERT INTO tabblename (col1, col2, col3) VALUES ");
foreach (var row in rows)
{
// the point here is to keep values quoted and avoid SQL injection
var first = row.First.Replace("'", "''")
var second = row.Second.Replace("'", "''")
var third = row.Third.Replace("'", "''")
toinsert.Add(string.Format("( '{0}', '{1}', '{2}' )", first, second, third));
}
if (toinsert.Count != 0)
{
insertCmd.Append(string.Join(",", toinsert));
insertCmd.Append(";");
}
using (MySqlCommand myCmd = new MySqlCommand(insertCmd.ToString(), SQLconnectionObject))
{
myCmd.CommandType = CommandType.Text;
myCmd.ExecuteNonQuery();
}
*Create SQL connection object and replace it where I have written SQLconnectionObject.
To check a number is positive, negative or negative zero. Check its sign using Math.sign() method it will provide you -1,-0,0 and 1 on the basis of positive negative and negative zero or zero numbers
Math.sign(-3) // -1
Math.sign(3) // 1
Math.sign(-0) // -0
Math.sign(0) // 0
Just use the length filter on the whole array. It works on more than just strings:
{{ notcount|length }}
forward to nikobelia
For those who using jenkins to run the play book, I just added to my jenkins job before running the ansible-playbook the he environment variable ANSIBLE_HOST_KEY_CHECKING = False For instance this:
export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook 'playbook.yml' \
--extra-vars="some vars..." \
--tags="tags_name..." -vv
The optional key
parameter to sort
/sorted
is a function. The function is called for each item and the return values determine the ordering of the sort
>>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
>>> def my_key_func(item):
... print("The key for {} is {}".format(item, item[1]))
... return item[1]
...
>>> sorted(lst, key=my_key_func)
The key for ['John', 2] is 2
The key for ['Jim', 9] is 9
The key for ['Jason', 1] is 1
[['Jason', 1], ['John', 2], ['Jim', 9]]
taking the print
out of the function leaves
>>> def my_key_func(item):
... return item[1]
This function is simple enough to write "inline" as a lambda function
>>> sorted(lst, key=lambda item: item[1])
[['Jason', 1], ['John', 2], ['Jim', 9]]
class Holder
{
private $value;
public function __construct( $value )
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function setValue( $value )
{
return $this->value = $value;
}
}
class Swap
{
public function SwapObjects( Holder $x, Holder $y )
{
$tmp = $x;
$x = $y;
$y = $tmp;
}
public function SwapValues( Holder $x, Holder $y )
{
$tmp = $x->getValue();
$x->setValue($y->getValue());
$y->setValue($tmp);
}
}
$a1 = new Holder('a');
$b1 = new Holder('b');
$a2 = new Holder('a');
$b2 = new Holder('b');
Swap::SwapValues($a1, $b1);
Swap::SwapObjects($a2, $b2);
echo 'SwapValues: ' . $a2->getValue() . ", " . $b2->getValue() . "<br>";
echo 'SwapObjects: ' . $a1->getValue() . ", " . $b1->getValue() . "<br>";
Attributes are still modifiable when not passed by reference so beware.
Output:
SwapObjects: b, a SwapValues: a, b
Try:
String.Join("", test);
which should return a string joining the two elements together. ""
indicates that you want the strings joined together without any separators.
If you're running PHP, I recommend Minify because it does combines and minifies on the fly for both CSS and JS. Once you've configured it, just work as normal and it takes care of everything.
Please note, none of the methods seems to work now!
In Android Studio 1 one simple way is to add
android:screenOrientation="nosensor"
.
This effectively locks the screen orientation.
If you need to update the canvas by redrawing views after some change, you should call setNeedsDisplay.
Here we can use urllib's Legacy interface in Python3:
The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.
Example (2 lines code):
import urllib.request
url = 'https://www.python.org/static/img/python-logo.png'
urllib.request.urlretrieve(url, "logo.png")
Try this one:
$('body').tooltip({
selector: '[rel=tooltip]'
});
It's easy to copy a folder in a batch file.
@echo off
set src_folder = c:\whatever\*.*
set dst_folder = c:\foo
xcopy /S/E/U %src_folder% %dst_folder%
And you can add that batch file to your Windows login script pretty easily (assuming you have admin rights on the machine). Just go to the "User Manager" control panel, choose properties for your user, choose profile and set a logon script.
How you get to the user manager control panel depends on which version of Windows you run. But right clicking on My Computer and choosing manage and then choosing Local users and groups works for most versions.
The only sticky bit is "when the folder is updated". This sounds like a folder watcher, which you can't do in a batch file, but you can do pretty easily with .NET.
You can use map
, it can map vales from a dictonairy or even a custom function.
Suppose this is your df:
ID First_Name Last_Name
0 103 a b
1 104 c d
Create the dicts:
fnames = {103: "Matt", 104: "Mr"}
lnames = {103: "Jones", 104: "X"}
And map:
df['First_Name'] = df['ID'].map(fnames)
df['Last_Name'] = df['ID'].map(lnames)
The result will be:
ID First_Name Last_Name
0 103 Matt Jones
1 104 Mr X
Or use a custom function:
names = {103: ("Matt", "Jones"), 104: ("Mr", "X")}
df['First_Name'] = df['ID'].map(lambda x: names[x][0])
Use the following pattern.
^\d{10}$
Just found Light Bot. Program your robot to move around and perform tasks to complete a puzzle. Even includes subroutines. Program the bot by dragging tiles into slots. The game is very polished.
Update Lightbot is now the most recent version of the game, and has versions specifically designed for kids ages 4-8 or ages 9+ (with no upper limit) and also features kind of an if
screen of lightbot 1 http://www.lostateminor.com/wp-content/uploads/2008/10/light-bot.jpg
Others have posted some ways that you might be able to "coax" the Python interpreter into freeing the memory (or otherwise avoid having memory problems). Chances are you should try their ideas out first. However, I feel it important to give you a direct answer to your question.
There isn't really any way to directly tell Python to free memory. The fact of that matter is that if you want that low a level of control, you're going to have to write an extension in C or C++.
That said, there are some tools to help with this:
I found all of the answers to use too much code. Here is an easy way to do it:
function to_xml(SimpleXMLElement $object, array $data)
{
foreach ($data as $key => $value) {
if (is_array($value)) {
$new_object = $object->addChild($key);
to_xml($new_object, $value);
} else {
// if the key is an integer, it needs text with it to actually work.
if ($key != 0 && $key == (int) $key) {
$key = "key_$key";
}
$object->addChild($key, $value);
}
}
}
Then it's a simple matter of sending the array into the function, which uses recursion, so it will handle a multi-dimensional array:
$xml = new SimpleXMLElement('<rootTag/>');
to_xml($xml, $my_array);
Now $xml contains a beautiful XML object based on your array exactly how you wrote it.
print $xml->asXML();
I did not have enough reputation to comment and hence am adding a new answer.
Gasek answer is quite correct. Just one thing: if you are updating the .bash_profile
file or the /etc/profile
, those changes would be reflected only after you do a new login.
In case you want to set the env variable and then use it in subsequent tasks in the same playbook, consider adding those environment variables in the .bashrc
file.
I guess the reason behind this is the login and the non-login shells.
Ansible, while executing different tasks, reads the parameters from a .bashrc
file instead of the .bash_profile
or the /etc/profile
.
As an example, if I updated my path variable to include the custom binary in the .bash_profile
file of the respective user and then did a source of the file.
The next subsequent tasks won't recognize my command. However if you update in the .bashrc
file, the command would work.
- name: Adding the path in the bashrc files
lineinfile: dest=/root/.bashrc line='export PATH=$PATH:path-to-mysql/bin' insertafter='EOF' regexp='export PATH=\$PATH:path-to-mysql/bin' state=present
- - name: Source the bashrc file
shell: source /root/.bashrc
- name: Start the mysql client
shell: mysql -e "show databases";
This would work, but had I done it using profile files the mysql -e "show databases"
would have given an error.
- name: Adding the path in the Profile files
lineinfile: dest=/root/.bash_profile line='export PATH=$PATH:{{install_path}}/{{mysql_folder_name}}/bin' insertafter='EOF' regexp='export PATH=\$PATH:{{install_path}}/{{mysql_folder_name}}/bin' state=present
- name: Source the bash_profile file
shell: source /root/.bash_profile
- name: Start the mysql client
shell: mysql -e "show databases";
This one won't work, if we have all these tasks in the same playbook.
You're getting a linker error, so your extern is working (the compiler compiled a.c
without a problem), but when it went to link the object files together at the end it couldn't resolve your extern -- void doSomething(int);
wasn't actually found anywhere. Did you mess up the extern? Make sure there's actually a doSomething
defined in b.c
that takes an int
and returns void
, and make sure you remembered to include b.c
in your file list (i.e. you're doing something like gcc a.c b.c
, not just gcc a.c
)
Also you can check using Keras backend function:
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
I test this on Keras (2.1.1)
Using a 200MB dump file created on Linux to restore on Windows w/ mysql 5.5 , I had more success with the
source file.sql
approach from the mysql prompt than with the
mysql < file.sql
approach on the command line, that caused some Error 2006 "server has gone away" (on windows)
Weirdly, the service created during (mysql) install refers to a my.ini file that did not exist. I copied the "large" example file to my.ini which I already had modified with the advised increases.
My values are
[mysqld]
max_allowed_packet = 64M
interactive_timeout = 250
wait_timeout = 250
They just keep changing things – having just updated Visual Studio and had the whole project bomb, on the road to recovery and the new way looks like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
I kept missing this line!
.SetBasePath(env.ContentRootPath)
Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.
In short, you add the selector after the URL. For example:
$('#result').load('ajax/test.html #container');
select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno
If you want to get the result for all the records (irrespective of whether they report to anyone or not), append (+) on the second table's name
select e.ename as Employee, m.ename as Manager
from emp e, emp m
where e.mgr = m.empno(+)
Use ${__time(yyyy-MM-dd'T'hh:mm:ss)}
to convert time into a particular timeformat.
Here are other formats that you can use:
yyyy/MM/dd HH:mm:ss.SSS
yyyy/MM/dd HH:mm:ss
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
MM/dd/yy HH:mm:ss
You can use Z character to get milliseconds too. For example:
yyyy/MM/dd HH:mm:ssZ => 2017-01-25T10:29:00-0700
yyyy/MM/dd HH:mm:ss.SSS'Z' => 2017-01-25T10:28:49.549Z
Most of the time yyyy/MM/dd HH:mm:ss.SSS'Z'
is required in some APIs. It is better to know how to convert time into this format.
From the documentation (MySQL 8) :
Type | Maximum length -----------+------------------------------------- TINYTEXT | 255 (2 8−1) bytes TEXT | 65,535 (216−1) bytes = 64 KiB MEDIUMTEXT | 16,777,215 (224−1) bytes = 16 MiB LONGTEXT | 4,294,967,295 (232−1) bytes = 4 GiB
Note that the number of characters that can be stored in your column will depend on the character encoding.
You can use an empty <div>
that is styled exactly like you want the line to appear:
HTML:
<div class="vertical-line"></div>
With exact height (overriding style in-line):
div.vertical-line{_x000D_
width: 1px; /* Line width */_x000D_
background-color: black; /* Line color */_x000D_
height: 100%; /* Override in-line if you want specific height. */_x000D_
float: left; /* Causes the line to float to left of content. _x000D_
You can instead use position:absolute or display:inline-block_x000D_
if this fits better with your design */_x000D_
}
_x000D_
<div class="vertical-line" style="height: 45px;"></div>
_x000D_
Style the border if you want 3D look:
div.vertical-line{_x000D_
width: 0px; /* Use only border style */_x000D_
height: 100%;_x000D_
float: left; _x000D_
border: 1px inset; /* This is default border style for <hr> tag */_x000D_
}
_x000D_
<div class="vertical-line" style="height: 45px;"></div>
_x000D_
You can of course also experiment with advanced combinations:
div.vertical-line{_x000D_
width: 1px;_x000D_
background-color: silver;_x000D_
height: 100%;_x000D_
float: left;_x000D_
border: 2px ridge silver ;_x000D_
border-radius: 2px;_x000D_
}
_x000D_
<div class="vertical-line" style="height: 45px;"></div>
_x000D_
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
Try TypeFactory
. Here's the code for Jackson JSON (2.8.4).
Map<String, String> result;
ObjectMapper mapper;
TypeFactory factory;
MapType type;
factory = TypeFactory.defaultInstance();
type = factory.constructMapType(HashMap.class, String.class, String.class);
mapper = new ObjectMapper();
result = mapper.readValue(data, type);
Here's the code for an older version of Jackson JSON.
Map<String, String> result = new ObjectMapper().readValue(
data, TypeFactory.mapType(HashMap.class, String.class, String.class));
I liked @Sesquipedal 's suggestion but with modification (a special use case when both values are 0 returns False). In my case I was on Python 2.7 and just used a simple function:
if f1 ==0 and f2 == 0:
return True
else:
return abs(f1-f2) < tol*max(abs(f1),abs(f2))
you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.
This should help you.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(train_set)
print tfidf_matrix
cosine = cosine_similarity(tfidf_matrix[length-1], tfidf_matrix)
print cosine
and output will be:
[[ 0.34949812 0.81649658 1. ]]
Disclaimer: I'm the author of the mentioned package.
I was surprised how the top answers to this question in 2019 still use serialization or reflection.
BinaryFormatter
requires the Serializable
attribute, JsonConverter
requires a parameterless constructor or attributes, neither handle read only fields or interfaces very well and both are 10-30x slower than necessary.
You can instead use Expression Trees or Reflection.Emit to generate cloning code only once, then use that compiled code instead of slow reflection or serialization.
Having come across the problem myself and seeing no satisfactory solution, I decided to create a package that does just that and works with every type and is a almost as fast as custom written code.
You can find the project on GitHub: https://github.com/marcelltoth/ObjectCloner
You can install it from NuGet. Either get the ObjectCloner
package and use it as:
var clone = ObjectCloner.DeepClone(original);
or if you don't mind polluting your object type with extensions get ObjectCloner.Extensions
as well and write:
var clone = original.DeepClone();
A simple benchmark of cloning a class hierarchy showed performance ~3x faster than using Reflection, ~12x faster than Newtonsoft.Json serialization and ~36x faster than the highly suggested BinaryFormatter
.
TL;DR:
Modern way is to use COC for intellisense-like completion and one or more language servers (LS) for jump-to-definition (and way way more). For even more functionality (but it's not needed for jump-to-definition) you can install one or more debuggers and get a full blown IDE experience.
Quick-start:
~/.vimrc
:
call plug#begin()
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'puremourning/vimspector'
call plug#end()
" key mappings example
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gD <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" there's way more, see `:help coc-key-mappings@en'
:source $MYVIMRC | PlugInstall
to reload VIM config and download plug-insvim
and call :CocInstall coc-marketplace
to get easy access to COC extensions:CocList marketplace
and search for language servers, e.g.:python
to find coc-jedi
,php
to find coc-phpls
, etc.install_gadget.py --help
for available debuggers, e.g.:./install_gadget.py --enable-python
,./install_gadget.py --force-enable-php
, etc.You can jump to definition with gd
, to interface implementation with gD
, find all references with gr
. More keybindings in :help coc-key-mappings@en
.
Full answer:
Language server (LS) is a separate standalone application (one for each programming language) that runs in the background and analyses your whole project in real time exposing extra capabilities to your editor (any editor, not only vim
). You get things like:
Communication with language servers takes place via Language Server Protocol (LSP). Both nvim
and vim8
(or higher) support LSP through plug-ins, the most popular being Conquer of Completion (COC).
List of actively developed language servers and their capabilities is available on Lang Server website. Not all of those are provided by COC extensions. If you want to use one of those you can either write a COC extension yourself or install LS manually and use the combo of following VIM plug-ins as alternative to COC:
Communication with debuggers takes place via Debug Adapter Protocol (DAP). The most popular DAP plug-in for VIM is Vimspector.
Language Server Protocol (LSP) was created by Microsoft for Visual Studio Code and released as an open source project with a permissive MIT license (standardized by collaboration with Red Hat and Codenvy). Later on Microsoft released Debug Adapter Protocol (DAP) as well. Any language supported by VSCode is supported in VIM.
I personally recommend using COC + language servers provided by COC extensions + ALE for extra linting (but with LSP support disabled to avoid conflicts with COC) + Vimspector + debuggers provided by Vimspector (called "gadgets") + following VIM plug-ins:
call plug#begin()
Plug 'neoclide/coc.nvim'
Plug 'dense-analysis/ale'
Plug 'puremourning/vimspector'
Plug 'scrooloose/nerdtree'
Plug 'scrooloose/nerdcommenter'
Plug 'sheerun/vim-polyglot'
Plug 'yggdroot/indentline'
Plug 'tpope/vim-surround'
Plug 'kana/vim-textobj-user'
\| Plug 'glts/vim-textobj-comment'
Plug 'janko/vim-test'
Plug 'vim-scripts/vcscommand.vim'
Plug 'mhinz/vim-signify'
call plug#end()
You can google each to see what they do.
Also, pipe character |
separates VIM commands put in one line which makes it perfect to set up plug-in dependencies, i.e. vim-textobj-comment
doesn't work without vim-textobj-user
so if installation of vim-textobj-user
fails the rest of the line isn't executed. Here pipe is escaped with backslash \
because it's in a new line but for VIM it's still a one-liner.
It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.
Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?
The function name is removeChild()
, and how is it possible to remove the child when there's no parent? :)
On the other hand, you do not always have to call it as you have shown. element.parentNode
is only a helper to get the parent node of the given node. If you already know the parent node, you can just use it like this:
Ex:
// Removing a specified element when knowing its parent node
var d = document.getElementById("top");
var d_nested = document.getElementById("nested");
var throwawayNode = d.removeChild(d_nested);
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
=========================================================
To add something more:
Some answers have pointed out that instead of using parentNode.removeChild(child);
, you can use elem.remove();
. But as I have noticed, there is a difference between the two functions, and it's not mentioned in those answers.
If you use removeChild()
, it will return a reference to the removed node.
var removedChild = element.parentNode.removeChild(element);
console.log(removedChild); //will print the removed child.
But if you use elem.remove();
, it won't return you the reference.
var el = document.getElementById('Example');
var removedChild = el.remove(); //undefined
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
This behavior can be observed in Chrome and FF. I believe It's worth noticing :)
Hope my answer adds some value to the question and will be helpful!!
dinner = cage.getChicken();
if(dinner == null) dinner = getFreeRangeChicken();
or
if( (dinner = cage.getChicken() ) == null) dinner = getFreeRangeChicken();
Here's a simple example..
List<char> c = new List<char>() { 'A', 'B', 'C' };
List<string> s = c.Select(x => x.ToString()).ToList();
This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.
<asp:TemplateField HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>
I've tryied all answers of this topic, but just this below worked fine on my project.
Angular 7 and AGM Core 1.0.0-beta.7
<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
<agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
*ngFor="let localizacao of localizacoesTec">
</agm-marker>
</agm-map>
The properties [agmFitBounds]="true"
at agm-marker
and [fitBounds]="true"
at agm-map
does the job
I got the error above and after fixing it I got an error for lodash/merge, then I got an error for 'license-check-and-add' then I realized that according to https://accessibilityinsights.io if I ran the below command, it installs all the missing pacakages at once! Then running the yarn build command worked smoothly with a --force parameter with yarn build.
yarn install
yarn build --force
Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.
.mydiv {
...
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
...
}
Adapted from: MDN
I came across this error due to the improper closing of the statement,
@using (Html.BeginForm("DeleteSelected", "Employee", FormMethod.Post))
{
} //This curly bracket needed to be closed at the end.
In Index.cshtml view file.I didn't close the statement at the end of the program. instead, I ended up closing improperly and ran into this error.
I was sure there isn't a need of checking Controller ActionMethod code because I have returned the Controller method properly to the View. So It has to be the view that's not responding and met with similar Error.
A bit more elaborate version (to use from another window):
#!/bin/bash
DELAY=3
TERM_PID=$(echo `ps -C gnome-terminal -o pid= | head -1`) # get first gnome-terminal's PID
WID=$(wmctrl -lp | awk -v pid=$TERM_PID '$3==pid{print $1;exit;}') # get window id
xdotool windowfocus $WID
xdotool key alt+t # my key map
xdotool sleep $DELAY # it may take a while to start new shell :(
xdotool type --delay 1 --clearmodifiers "$@"
xdotool key Return
wmctrl -i -a $WID # go to that window (WID is numeric)
# vim:ai
# EOF #
If you are using Bootstrap 4 and higher try this to put borders around your empty divs use border border-primary
here is an example of my code:
<div class="row border border-primary">
<div class="col border border-primary">logo</div>
<div class="col border border-primary">navbar</div>
</div>
Here is the link to the border utility in Bootstrap 4: https://getbootstrap.com/docs/4.2/utilities/borders/
Assuming that your current primary key constraint is called pk_history, you can replace the following lines:
ALTER TABLE history ADD PRIMARY KEY (id)
ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name
with these:
ALTER TABLE history DROP CONSTRAINT pk_history
ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
If you don't know what the name of the PK is, you can find it with the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'history'
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
React is a declarative, efficient, and flexible JavaScript library for building user interfaces.Your components tell React what you want to render – then React will efficiently update and render just the right components when your data changes. Here, ShoppingList is a React component class, or React component type.
A React Native app is a real mobile app. With React Native, you don't build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that's indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps.
Best way to do is :
[self performSelector:@selector(YourFunctionName)
withObject:(can be Self or Object from other Classes)
afterDelay:(Time Of Delay)];
you can also pass nil as withObject parameter.
example :
[self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ];
np.newaxis
?The np.newaxis
is just an alias for the Python constant None
, which means that wherever you use np.newaxis
you could also use None
:
>>> np.newaxis is None
True
It's just more descriptive if you read code that uses np.newaxis
instead of None
.
np.newaxis
?The np.newaxis
is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis
represents where I want to add dimensions.
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)
In the first example I use all elements from the first dimension and add a second dimension:
>>> a[:, np.newaxis]
array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
>>> a[:, np.newaxis].shape
(10, 1)
The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:
>>> a[np.newaxis, :] # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)
Similarly you can use multiple np.newaxis
to add multiple dimensions:
>>> a[np.newaxis, :, np.newaxis] # note the 3 [] pairs in the output
array([[[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)
np.newaxis
?There is another very similar functionality in NumPy: np.expand_dims
, which can also be used to insert one dimension:
>>> np.expand_dims(a, 1) # like a[:, np.newaxis]
>>> np.expand_dims(a, 0) # like a[np.newaxis, :]
But given that it just inserts 1
s in the shape
you could also reshape
the array to add these dimensions:
>>> a.reshape(a.shape + (1,)) # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape) # like a[np.newaxis, :]
Most of the times np.newaxis
is the easiest way to add dimensions, but it's good to know the alternatives.
np.newaxis
?In several contexts is adding dimensions useful:
If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow
to display a 1D array.
If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]
. This works because NumPy operations broadcast starting with the last dimension 1.
To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.
1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis
:
>>> a = np.array([0.0, 10.0, 20.0, 30.0]) >>> b = np.array([1.0, 2.0, 3.0]) >>> a[:, np.newaxis] + b array([[ 1., 2., 3.], [ 11., 12., 13.], [ 21., 22., 23.], [ 31., 32., 33.]])
Just utilize toString
or toLocaleString
I'd say. So:
var page_number:number = 3;
window.location.hash = page_number.toLocaleString();
These throw an error if page_number
is null
or undefined
. If you don't want that you can choose the fix appropriate for your situation:
// Fix 1:
window.location.hash = (page_number || 1).toLocaleString();
// Fix 2a:
window.location.hash = !page_number ? "1" page_number.toLocaleString();
// Fix 2b (allows page_number to be zero):
window.location.hash = (page_number !== 0 && !page_number) ? "1" page_number.toLocaleString();
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
this.setState({abc: {xyz: 'new value'}});
will NOT work, as state.abc
will be entirely overwritten, not merged.
This works for me:
this.setState((previousState) => {
previousState.abc.xyz = 'blurg';
return previousState;
});
Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html
Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:
const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);
You can programmatically import data from a csv file in your Drive into an existing Google Sheet using Google Apps Script, replacing/appending data as needed.
Below is some sample code. It assumes that: a) you have a designated folder in your Drive where the CSV file is saved/uploaded to; b) the CSV file is named "report.csv" and the data in it comma-delimited; and c) the CSV data is imported into a designated spreadsheet. See comments in code for further details.
function importData() {
var fSource = DriveApp.getFolderById(reports_folder_id); // reports_folder_id = id of folder where csv reports are saved
var fi = fSource.getFilesByName('report.csv'); // latest report file
var ss = SpreadsheetApp.openById(data_sheet_id); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data
if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
var file = fi.next();
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv); // see below for CSVToArray function
var newsheet = ss.insertSheet('NEWDATA'); // create a 'NEWDATA' sheet to store imported data
// loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
newsheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
/*
** report data is now in 'NEWDATA' sheet in the spreadsheet - process it as needed,
** then delete 'NEWDATA' sheet using ss.deleteSheet(newsheet)
*/
// rename the report.csv file so it is not processed on next scheduled run
file.setName("report-"+(new Date().toString())+".csv");
}
};
// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ) {
// Check to see if the delimiter is defined. If not,
// then default to COMMA.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
};
You can then create time-driven trigger in your script project to run importData()
function on a regular basis (e.g. every night at 1AM), so all you have to do is put new report.csv file into the designated Drive folder, and it will be automatically processed on next scheduled run.
If you absolutely MUST work with Excel files instead of CSV, then you can use this code below. For it to work you must enable Drive API in Advanced Google Services in your script and in Developers Console (see How to Enable Advanced Services for details).
/**
* Convert Excel file to Sheets
* @param {Blob} excelFile The Excel file blob data; Required
* @param {String} filename File name on uploading drive; Required
* @param {Array} arrParents Array of folder ids to put converted file in; Optional, will default to Drive root folder
* @return {Spreadsheet} Converted Google Spreadsheet instance
**/
function convertExcel2Sheets(excelFile, filename, arrParents) {
var parents = arrParents || []; // check if optional arrParents argument was provided, default to empty array if not
if ( !parents.isArray ) parents = []; // make sure parents is an array, reset to empty array if not
// Parameters for Drive API Simple Upload request (see https://developers.google.com/drive/web/manage-uploads#simple)
var uploadParams = {
method:'post',
contentType: 'application/vnd.ms-excel', // works for both .xls and .xlsx files
contentLength: excelFile.getBytes().length,
headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
payload: excelFile.getBytes()
};
// Upload file to Drive root folder and convert to Sheets
var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);
// Parse upload&convert response data (need this to be able to get id of converted sheet)
var fileDataResponse = JSON.parse(uploadResponse.getContentText());
// Create payload (body) data for updating converted file's name and parent folder(s)
var payloadData = {
title: filename,
parents: []
};
if ( parents.length ) { // Add provided parent folder(s) id(s) to payloadData, if any
for ( var i=0; i<parents.length; i++ ) {
try {
var folder = DriveApp.getFolderById(parents[i]); // check that this folder id exists in drive and user can write to it
payloadData.parents.push({id: parents[i]});
}
catch(e){} // fail silently if no such folder id exists in Drive
}
}
// Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)
var updateParams = {
method:'put',
headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
contentType: 'application/json',
payload: JSON.stringify(payloadData)
};
// Update metadata (filename and parent folder(s)) of converted sheet
UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/'+fileDataResponse.id, updateParams);
return SpreadsheetApp.openById(fileDataResponse.id);
}
/**
* Sample use of convertExcel2Sheets() for testing
**/
function testConvertExcel2Sheets() {
var xlsId = "0B9**************OFE"; // ID of Excel file to convert
var xlsFile = DriveApp.getFileById(xlsId); // File instance of Excel file
var xlsBlob = xlsFile.getBlob(); // Blob source of Excel file for conversion
var xlsFilename = xlsFile.getName(); // File name to give to converted file; defaults to same as source file
var destFolders = []; // array of IDs of Drive folders to put converted file in; empty array = root folder
var ss = convertExcel2Sheets(xlsBlob, xlsFilename, destFolders);
Logger.log(ss.getId());
}
That's the distinction between declaration and definition. Header files typically include just the declaration, and the source file contains the definition.
In order to use something you only need to know it's declaration not it's definition. Only the linker needs to know the definition.
So this is why you will include a header file inside one or more source files but you won't include a source file inside another.
Also you mean #include
and not import.
if anyone is interested to use the cURL for validation. You can use the following code.
<?php
public function validationUrl($Url){
if ($Url == NULL){
return $false;
}
$ch = curl_init($Url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode >= 200 && $httpcode < 300) ? true : false;
}
This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.
The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.
The easiest thing to do is have your grid nodes register the Firefox binary path as part of the node config. It uses the same capabilities that the client has, but allows you to pick the browser by name and let the node find it.
Please also note that the capability you want is "firefox_binary" and not "binary". You can see the full list of Firefox capabilities at this wiki page:
I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:
Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)
You will see the following Eclipse error message:
org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control
After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)
You will see the following message dialog: "File list is empty"
Press cancel and refresh the project in Eclipse. Your project should be under version control again.
Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.
Usually a back-reference is either $1
or \1
(backslash one) for the first capture group (the first match of a pattern in parentheses), and indeed Sublime supports both syntaxes. So try:
my name used to be \1
or
my name used to be $1
Also note that your original capture pattern:
my name is (\w)+
is incorrect and will only capture the final letter of the name rather than the whole name. You should use the following pattern to capture all of the letters of the name:
my name is (\w+)
The answers above are correct: it is used in exception handling. The manual for GCC version 6 has more information (which is no longer present in the version 7 manual). The error can arise when linking an external function that - unknown to GCC - throws Java exceptions.
I have implemented data downloading functionality through FTP server and found the same exception there too while resuming that download. To resolve this exception, you will always have to disconnect from the previous session and create new instance of the Client and new connection with the server. This same approach could be helpful for HTTPClient too.
Validate it against FedEx's api. They have an API to generate labels from XML code. The process involves a step to validate the address.
Yes. See Named and Optional Arguments. Note that the default value needs to be a constant, so this is OK:
public string Foo(string myParam = "default value") // constant, OK
{
}
but this is not:
public void Bar(string myParam = Foo()) // not a constant, not OK
{
}
I wrote a util function to achieve this purpose. You can take a look:
// adjust the height of a multi-line label to make it align vertical with top + (void) alignLabelWithTop:(UILabel *)label { CGSize maxSize = CGSizeMake(label.frame.size.width, 999); label.adjustsFontSizeToFitWidth = NO; // get actual height CGSize actualSize = [label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode]; CGRect rect = label.frame; rect.size.height = actualSize.height; label.frame = rect; }
.How to use? (If lblHello is created by Interface builder, so I skip some UILabel attributes detail)
lblHello.text = @"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!"; lblHello.numberOfLines = 5; [Utils alignLabelWithTop:lblHello];
I also wrote it on my blog as an article: http://fstoke.me/blog/?p=2819
if modifying the image is not a problem for you, and
if you know the approximate width of the container that will display your markdown, and
if your image is used in one place only (for example a README used only in GitHub),
then you can edit your image in an image editor and pad it equally on both sides.
for names not present in the working copy or repo:
echo /globpattern >> .gitignore
or for an existing file (sh type command line):
echo /$(ls -1 file) >> .gitignore # I use tab completion to select the file to be ignored
git rm -r --cached file # if already checked in, deletes it on next commit
The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.
If you specifically want to send it as multipart/form-data
, you can use a FormData object:
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data
xmlHttpRequest.send(formData);
You can also send the data directly, instead of using multipart/form-data
. See the documentation. Of course, this will need a server-side change as well.
// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
xmlHttpRequest.setRequestHeader("Content-Type", file.type);
// Send the binary data.
// Since a File is a Blob, we can send it directly.
xmlHttpRequest.send(file);
For browser support, see: http://caniuse.com/#feat=xhr2 (most browsers, including IE 10+).
First: monkey patching is an evil hack (in my opinion).
It is often used to replace a method on the module or class level with a custom implementation.
The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code through monkey patching with an implementation inside your own module/package.
Just delete these lines from the root build.gradle
android {
compileSdkVersion 19
buildToolsVersion '19.1' }
Now trying and compile again. It should work.
Get the file from a previous commit through checking-out previous commit and copying file.
git checkout 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8
git checkout theBranchYouNoted
git commit -m "added file ?? from previous commit"
cat(capture.output(print(my.list), file="test.txt"))
from R: Export and import a list to .txt file https://stackoverflow.com/users/1855677/42 is the only thing that worked for me. This outputs the list of lists as it is in the text file
Get your object's constructor function and then inspect its name property.
myObj.constructor.name
Returns "myClass".
Just use the *
before it
:
set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
cout << *it;
}
This dereferences it and allows you to access the element the iterator is currently on.
Latest published version of the Support Library is 24.1.1, So you can use it like this,
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
Same as for other support components.
You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html
You can compile and run your code entirely in ST, and it's very quick/simple. There's a recent ST package called Javatar that can do this. https://javatar.readthedocs.org
In my case, the error was valid and it was due to using try with resource
try (ConfigurableApplicationContext cxt = new ClassPathXmlApplicationContext(
"classpath:application-main-config.xml")) {..
}
It auto closes the stream which should not happen if I want to reuse this context in other beans.
The equivalent would be class SortedDictionary<TKey, TValue>
in the System.Collections.Generic
namespace.
If you don't care about the order the class Dictionary<TKey, TValue>
in the System.Collections.Generic
namespace would probably be sufficient.
Just change from ProgressDialog
to ProgressBar
in a layout:
res/layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
//Your content here
</LinearLayout>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"
android:indeterminateDrawable="@drawable/progress" >
</ProgressBar>
</RelativeLayout>
src/yourPackage/YourActivity.java
public class YourActivity extends Activity{
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
bar = (ProgressBar) this.findViewById(R.id.progressBar);
new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask <Void,Void,Void>{
@Override
protected void onPreExecute(){
bar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
//my stuff is here
}
@Override
protected void onPostExecute(Void result) {
bar.setVisibility(View.GONE);
}
}
}
drawable/progress.xml This is a custom ProgressBar
that i use to change the default colors.
<?xml version="1.0" encoding="utf-8"?>
<!--
Duration = 1 means that one rotation will be done in 1 second. leave it.
If you want to speed up the rotation, increase duration value.
in example 1080 shows three times faster revolution.
make the value multiply of 360, or the ring animates clunky
-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1"
android:toDegrees="360" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="8"
android:useLevel="false" >
<size
android:height="48dip"
android:width="48dip" />
<gradient
android:centerColor="@color/color_preloader_center"
android:centerY="0.50"
android:endColor="@color/color_preloader_end"
android:startColor="@color/color_preloader_start"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Use a JSON parser, like JSON.NET
string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();
SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;
Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.
N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.
Yes, you can select the data, calculate the difference, and insert all values in the other table:
insert into #temp2 (Difference)
select previous - Present
from #TEMP1
I had this problem when moving my .edmx
database first model from one project to another.
I simply did the following:
app.config
or web.config
Do just simple thing:
If you are running it locally and want to be able to step through the code:
python -m pdb script.py
you can use @Component
@RequiredArgsConstructor
@Component
@Slf4j
public class BeerLoader implements CommandLineRunner {
//declare
@Override
public void run(String... args) throws Exception {
//some code here
}
$(document).ready(function(){
$('#mySelect').append("<option>BMW</option>")
})
in javaFx 8
javafx.scene.image.Image img = new javafx.scene.image.Image("/myPic.jpg", true);
URL url = new URL(img.impl_getUrl());
I ran S.Lott's code and produced the same 10% performance increase by preallocating. I tried Ned Batchelder's idea using a generator and was able to see the performance of the generator better than that of the doAllocate. For my project the 10% improvement matters, so thanks to everyone as this helps a bunch.
def doAppend(size=10000):
result = []
for i in range(size):
message = "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate(size=10000):
result = size*[None]
for i in range(size):
message = "some unique object %d" % ( i, )
result[i] = message
return result
def doGen(size=10000):
return list("some unique object %d" % ( i, ) for i in xrange(size))
size = 1000
@print_timing
def testAppend():
for i in xrange(size):
doAppend()
@print_timing
def testAlloc():
for i in xrange(size):
doAllocate()
@print_timing
def testGen():
for i in xrange(size):
doGen()
testAppend()
testAlloc()
testGen()
testAppend took 14440.000ms
testAlloc took 13580.000ms
testGen took 13430.000ms
You must fill the "Button" attribute of the "CompoundButton" class with a XML drawable path (my_checkbox). In the XML drawable, you must have :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:drawable="@drawable/checkbox_not_checked" />
<item android:state_checked="true" android:drawable="@drawable/checkbox_checked" />
<item android:drawable="@drawable/checkbox_not_checked" /> <!-- default -->
</selector>
Don't forget to replace my_checkbox by your filename of the checkbox drawable , checkbox_not_checked by your PNG drawable which is your checkbox when it's not checked and checkbox_checked with your image when it's checked.
For the size, directly update the layout parameters.
Java 8 introduced a nice computeIfAbsent default method to Map
interface which stores lazy-computed value and so doesn't break map contract:
Map<Key, Graph> map = new HashMap<>();
map.computeIfAbsent(aKey, key -> createExpensiveGraph(key));
Origin: http://blog.javabien.net/2014/02/20/loadingcache-in-java-8-without-guava/
Disclamer: This answer doesn't match exactly what OP asked but may be handy in some cases matching question's title when keys number is limited and caching of different values would be profitable. It shouldn't be used in opposite case with plenty of keys and same default value as this would needlessly waste memory.
This should do it:
declare
v_count integer;
begin
for r in (select table_name, owner from all_tables
where owner = 'SCHEMA_NAME')
loop
execute immediate 'select count(*) from ' || r.table_name
into v_count;
INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
VALUES (r.table_name,r.owner,v_count,SYSDATE);
end loop;
end;
I removed various bugs from your code.
Note: For the benefit of other readers, Oracle does not provide a table called STATS_TABLE
, you would need to create it.
An extension of @John Doe & @user3270492's answer. But, this seems to work for me.
<your_secret_command>; history -d $((HISTCMD-1))
You should not see the entry of the command in your history.
Here's the explanation..
The 'history -d' deletes the mentioned entry from the history.
The HISTCMD stores the command_number of the one to be executed next. So, (HISTCMD-1) refers to the last executed command.
Into phpmyadmin database's create that table, there miskta on name of that table it may be pma_table_uiprefs
and not pma__table_uiprefs
CREATE TABLE IF NOT EXISTS
pma_table_uiprefs
(username
varchar(64) NOT NULL,db_name
varchar(64) NOT NULL,table_name
varchar(64) NOT NULL,prefs
text NOT NULL,last_update
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (username
,db_name
,table_name
) ) COMMENT='Tables'' UI preferences' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?
If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.
If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.
You'll want to leave your session cookie as a cookie either way though.
As per the technical difference, and also my understanding:
Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domain — SO Question also mentions it.
localStorage
is an implementation of the Storage
Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.
EditText state = (EditText) findViewById(R.id.txtState);
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(state.getText().toString());
boolean bs = ms.matches();
if (bs == false) {
if (ErrorMessage.contains("invalid"))
ErrorMessage = ErrorMessage + "state,";
else
ErrorMessage = ErrorMessage + "invalid state,";
}
maybe not as stylish, but easier:
#!/bin/bash
log="/var/log/yourlog"
/path/to/your/script.py 2>&1 | (while read; do echo "$REPLY" >> $log; done)
In addition to Will Dean's version, the following are common for whole buffer initialization:
char s[10] = {'\0'};
or
char s[10];
memset(s, '\0', sizeof(s));
or
char s[10];
strncpy(s, "", sizeof(s));
If based on click here it is:
ng-click="orderReverse = orderReverse ? false : true"
Just my 2 Cents here ..
Bootstrap.yml or Bootstrap.properties is used to fetch the config from Spring Cloud Server.
For Example, in My Bootstrap.properties file I have the following Config
spring.application.name=Calculation-service
spring.cloud.config.uri=http://localhost:8888
On starting the application , It tries to fetch the configuration for the service by connecting to http://localhost:8888 and looks at Calculation-service.properties present in Spring Cloud Config server
You can validate the same from logs of Calcuation-Service when you start it up
INFO 10988 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
You have ("Something2")
by itself - you need to test it so a boolean is returned:
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.
Use concat() function instead of +
like this:
select concat(firstname, lastname) as "Name" from test.student
I'm using 2 ways to get the same response: one of them use:
os.path.basename(filename)
due to errors that I found in my script I changed to:
Path = filename[:(len(filename)-len(os.path.basename(filename)))]
it's a workaround due to python's '\\'
Think of (char *) as string.begin(). The essential difference is that (char *) is an iterator and std::string is a container. If you stick to basic strings a (char *) will give you what std::string::iterator does. You could use (char *) when you want the benefit of an iterator and also compatibility with C, but that's the exception and not the rule. As always, be careful of iterator invalidation. When people say (char *) isn't safe this is what they mean. It's as safe as any other C++ iterator.
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
Since version 3.8.2 of SQLite, an alternative to explicit NOT NULL specifications is the "WITHOUT ROWID" specification: [1]
NOT NULL is enforced on every column of the PRIMARY KEY
in a WITHOUT ROWID table.
"WITHOUT ROWID" tables have potential efficiency advantages, so a less verbose alternative to consider is:
CREATE TABLE t (
c1,
c2,
c3,
PRIMARY KEY (c1, c2)
) WITHOUT ROWID;
For example, at the sqlite3 prompt:
sqlite> insert into t values(1,null,3);
Error: NOT NULL constraint failed: t.c2
One thing you can do is this:
$(this)[0].value = "Something";
This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.
If it wasn't checked in as a Java Project, you can add the java nature as shown here.
Or you can simply start the activity as shown below;
startActivity( new Intent(currentactivity.this, Tostartactivity.class));
I had to add this:
bootRun {
String activeProfile = System.properties['spring.profiles.active']
String confLoc = System.properties['spring.config.location']
systemProperty "spring.profiles.active", activeProfile
systemProperty "spring.config.location", "file:$confLoc"
}
And now bootRun picks up the profile and config locations.
Thanks a lot @jst for the pointer.
Spring boot + spring mvn
with issue
@PostMapping("/addDonation")
public String addDonation(@RequestBody DonatorDTO donatorDTO) {
with solution
@RequestMapping(value = "/addDonation", method = RequestMethod.POST)
@ResponseBody
public GenericResponse addDonation(final DonatorDTO donatorDTO, final HttpServletRequest request){
My solution is similar.
// In destination class:
var AddressString:String = String()
// In segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "seguetobiddetailpagefromleadbidder")
{
let secondViewController = segue.destinationViewController as! BidDetailPage
secondViewController.AddressString = pr.address as String
}
}
You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.
In C language your examples has no relation to bool
whatsoever (that applies to C99 as well). In C language relational operators do not produce bool
results. Both 4 > 5
and 4 < 5
are expressions that produce results of type int
with values 0
or 1
. So, there's no "bool to int conversion" of any kind taking place in your examples in C.
In C++ relational operators do indeed produce bool
results. bool
values are convertible to int
type, with true
converting to 1
and false
converting to 0
. This is guaranteed by the language.
P.S. C language also has a dedicated boolean type _Bool
(macro-aliased as bool
), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int
(not bool
) results regardless of the version of the language specification.
First, note that the question presents an incorrect initialization of an aware datetime object:
>>> local_time=datetime.datetime(2010, 4, 27, 12, 0, 0, 0,
... tzinfo=pytz.timezone('Israel'))
creates an invalid instance. One can see the problem by computing the UTC offset of the resulting object:
>>> print(local_time.utcoffset())
2:21:00
(Note the result which is an odd fraction of an hour.)
To initialize an aware datetime properly using pytz one should use the localize()
method as follows:
>>> local_time=pytz.timezone('Israel').localize(datetime.datetime(2010, 4, 27, 12))
>>> print(local_time.utcoffset())
3:00:00
Now, if you require a local pytz timezone as the new tzinfo, you should use the tzlocal package as others have explained, but if all you need is an instance with a correct local time zone offset and abbreviation then tarting with Python 3.3, you can call the astimezone()
method with no arguments to convert an aware datetime
instance to your local timezone:
>>> local_time.astimezone().strftime('%Y-%m-%d %H:%M %Z %z')
'2010-04-27 05:00 EDT -0400'
You can use Konfig for environment specific config files. It loads json or yaml config files automatically, it has default value and dynamic configuration features.
An example from Konfig repo:
File: config/app.json
----------------------------
{
"default": {
"port": 3000,
"cache_assets": true,
"secret_key": "7EHDWHD9W9UW9FBFB949394BWYFG8WE78F"
},
"development": {
"cache_assets": false
},
"test": {
"port": 3001
},
"staging": {
"port": #{process.env.PORT},
"secret_key": "3F8RRJR30UHERGUH8UERHGIUERHG3987GH8"
},
"production": {
"port": #{process.env.PORT},
"secret_key": "3F8RRJR30UHERGUH8UERHGIUERHG3987GH8"
}
}
In development:
> config.app.port
3000
In production, assume we start application with $ NODE_ENV=production PORT=4567 node app.js
> config.app.port
4567
More details : https://github.com/vngrs/konfig
If an existing (non-bare) checkout begins giving this error, check your .git/config file; if core.bare
is true, remove that config line
You could use a map function that allows multiple arguments, as does the fork of multiprocessing
found in pathos
.
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>>
>>> def add_and_subtract(x,y):
... return x+y, x-y
...
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
pathos
enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.
>>> from pathos.multiprocessing import ThreadingPool as TPool
>>>
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
Even more fun, is to build a nested function that we can pass into the Pool.
This is possible because pathos
uses dill
, which can serialize almost anything in python.
>>> def build_fun_things(f, g):
... def do_fun_things(x, y):
... return f(x,y), g(x,y)
... return do_fun_things
...
>>> def add(x,y):
... return x+y
...
>>> def sub(x,y):
... return x-y
...
>>> neato = build_fun_things(add, sub)
>>>
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap
as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)
Get pathos
here: https://github.com/uqfoundation
You need not to worry about begin and end transaction. You have already apply @Transactional annotation, which internally open transaction when your method starts and ends when your method ends. So only required this is to persist your object in database.
@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public String persist(Details details){
details.getUsername();
details.getPassword();
Query query = em.createNativeQuery("db.details.find(username= "+details.getUsername()+"& password= "+details.getPassword());
em.persist(details);
System.out.println("Sucessful!");
return "persist";
}
EDIT : The problem seems to be with your configuration file. If you are using JPA then your configuration file should have below configuration
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="ORACLE" p:showSql="true" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:persistenceUnitName="YourProjectPU"
p:persistenceXmlLocation="classpath*:persistence.xml"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceProvider" ref="interceptorPersistenceProvider" />
</bean>
While in 2010, java.util.Date
was the class we all used (toghether with DateFormat
and Calendar
), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss");
String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter);
System.out.println("output here: " + dateTime);
Output is:
output here: 2010-04-29T13:00:14
The combination of uppercase HH
and aaa
in your format pattern strings does not make much sense since HH
is for hour of day, rendering the AM/PM marker from aaa
superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat
or the modern DateTimeFormatter
:
'aaa' should not be used, if you use 'aaa' then specify 'hh'
Lowercase hh
is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.
Other tips
2010-04-29T07:30:14Z
(the modern Instant
class parses and formats such strings as its default, that is, without any explicit formatter).GMT+05:30
for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.DateFormat
, its parse
method returns a Date
, so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);
.Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).This is an addition to dmd733's answer. I fixed the bug with Day duration (well I hope I did, haven't been able to test every case).
I also quickly added a String property to the result that holds the general time passed (sorry for the bad nested ifs!!). For example if used for UI and indicating when something was updated (like a RSS feed). Kind of out of place but nice-to-have:
function getTimeDiffAndPrettyText(oDatePublished) {
var oResult = {};
var oToday = new Date();
var nDiff = oToday.getTime() - oDatePublished.getTime();
// Get diff in days
oResult.days = Math.floor(nDiff / 1000 / 60 / 60 / 24);
nDiff -= oResult.days * 1000 * 60 * 60 * 24;
// Get diff in hours
oResult.hours = Math.floor(nDiff / 1000 / 60 / 60);
nDiff -= oResult.hours * 1000 * 60 * 60;
// Get diff in minutes
oResult.minutes = Math.floor(nDiff / 1000 / 60);
nDiff -= oResult.minutes * 1000 * 60;
// Get diff in seconds
oResult.seconds = Math.floor(nDiff / 1000);
// Render the diffs into friendly duration string
// Days
var sDays = '00';
if (oResult.days > 0) {
sDays = String(oResult.days);
}
if (sDays.length === 1) {
sDays = '0' + sDays;
}
// Format Hours
var sHour = '00';
if (oResult.hours > 0) {
sHour = String(oResult.hours);
}
if (sHour.length === 1) {
sHour = '0' + sHour;
}
// Format Minutes
var sMins = '00';
if (oResult.minutes > 0) {
sMins = String(oResult.minutes);
}
if (sMins.length === 1) {
sMins = '0' + sMins;
}
// Format Seconds
var sSecs = '00';
if (oResult.seconds > 0) {
sSecs = String(oResult.seconds);
}
if (sSecs.length === 1) {
sSecs = '0' + sSecs;
}
// Set Duration
var sDuration = sDays + ':' + sHour + ':' + sMins + ':' + sSecs;
oResult.duration = sDuration;
// Set friendly text for printing
if(oResult.days === 0) {
if(oResult.hours === 0) {
if(oResult.minutes === 0) {
var sSecHolder = oResult.seconds > 1 ? 'Seconds' : 'Second';
oResult.friendlyNiceText = oResult.seconds + ' ' + sSecHolder + ' ago';
} else {
var sMinutesHolder = oResult.minutes > 1 ? 'Minutes' : 'Minute';
oResult.friendlyNiceText = oResult.minutes + ' ' + sMinutesHolder + ' ago';
}
} else {
var sHourHolder = oResult.hours > 1 ? 'Hours' : 'Hour';
oResult.friendlyNiceText = oResult.hours + ' ' + sHourHolder + ' ago';
}
} else {
var sDayHolder = oResult.days > 1 ? 'Days' : 'Day';
oResult.friendlyNiceText = oResult.days + ' ' + sDayHolder + ' ago';
}
return oResult;
}
typeid(uint8_t).name()
is nice, but it returns "unsigned char" while you may expect "uint8_t".
This piece of code will return you the appropriate type
#define DECLARE_SET_FORMAT_FOR(type) \
if ( typeid(type) == typeid(T) ) \
formatStr = #type;
template<typename T>
static std::string GetFormatName()
{
std::string formatStr;
DECLARE_SET_FORMAT_FOR( uint8_t )
DECLARE_SET_FORMAT_FOR( int8_t )
DECLARE_SET_FORMAT_FOR( uint16_t )
DECLARE_SET_FORMAT_FOR( int16_t )
DECLARE_SET_FORMAT_FOR( uint32_t )
DECLARE_SET_FORMAT_FOR( int32_t )
DECLARE_SET_FORMAT_FOR( float )
// .. to be exptended with other standard types you want to be displayed smartly
if ( formatStr.empty() )
{
assert( false );
formatStr = typeid(T).name();
}
return formatStr;
}
In my case Right Click on Virtual Directory and Select "Convert To Application" worked!
Try to place the code of your query before. That fix my problem. e.g. change this:
query1
query2 - get the error
update
to this:
query2
query1
update
You are trying to concatenate a string and an integer.
You need to cast @ID
as a string.
try:
SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))
var getQueryParam = function(param) {
var found;
window.location.search.substr(1).split("&").forEach(function(item) {
if (param == item.split("=")[0]) {
found = item.split("=")[1];
}
});
return found;
};
Yes, you can run test scripts without a browser, But you should run them in headless mode.
You can use ORDER BY ID DESC
, but it's WAY faster if you go that way:
SELECT * FROM bugs WHERE ID = (SELECT MAX(ID) FROM bugs WHERE user = 'me')
In case that you have a huge table, it could make a significant difference.
EDIT
You can even set a variable in case you need it more than once (or if you think it is easier to read).
SELECT @bug_id := MAX(ID) FROM bugs WHERE user = 'me';
SELECT * FROM bugs WHERE ID = @bug_id;
That can be achieve in plain LaTeX without any specific package.
\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
\left\{
\begin{array}{l}
0\\
1
\end{array}
\right.
\end{math}
\end{document}
This code produces something which looks what you seems to need.
The same example as in the @Tombart can be obtained with similar code.
\documentclass{article}
\begin{document}
\begin{math}
f(x)=\left\{
\begin{array}{ll}
1, & \mbox{if $x<0$}.\\
0, & \mbox{otherwise}.
\end{array}
\right.
\end{math}
\end{document}
This code produces very similar results.
I could delete most of my branches but one looked like this and I could not delete it:
Turned out someone had set Branch permissions
under Settings
and from there unchecked Allow deleting this branch
. Hope this can help someone.
Update: Where settings are located from question in comment. Enter the repository that you wan't to edit to get the menu. You might need admin privileges to change this.
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
This one works for me (use "Default" instead of "UTF8"):
$MyFile = Get-Content $MyPath
$MyFile | Out-File -Encoding "Default" $MyPath
The result is ASCII without BOM.
(from a in db.Assignments
join b in db.Deliveryboys on a.AssignTo equals b.EmployeeId
//from d in eGroup.DefaultIfEmpty()
join c in db.Deliveryboys on a.DeliverTo equals c.EmployeeId into eGroup2
from e in eGroup2.DefaultIfEmpty()
where (a.Collected == false)
select new
{
OrderId = a.OrderId,
DeliveryBoyID = a.AssignTo,
AssignedBoyName = b.Name,
Assigndate = a.Assigndate,
Collected = a.Collected,
CollectedDate = a.CollectedDate,
CollectionBagNo = a.CollectionBagNo,
DeliverTo = e == null ? "Null" : e.Name,
DeliverDate = a.DeliverDate,
DeliverBagNo = a.DeliverBagNo,
Delivered = a.Delivered
});
jspcal's answer as a string extension.
Program.cs
class Program
{
static void Main(string[] args)
{
var myText = "MYTEXT";
Console.WriteLine(myText.ToTitleCase()); //Mytext
}
}
StringExtensions.cs
using System;
public static class StringExtensions
{
public static string ToTitleCase(this string str)
{
if (str == null)
return null;
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
}
Haven't seen the right answer, even though it's very easy to test.
In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5
. Once you go beyond that:
public class Foo {
public static void main(String[] args) {
Object[] array = new Object[Integer.MAX_VALUE - 4];
}
}
You get:
Exception in thread "main" java.lang.OutOfMemoryError:
Requested array size exceeds VM limit
With iOS 9.2 and Xcode 7.2, the following script will open the Documents folder of the last installed application on the last used simulator;
cd ~/Library/Developer/CoreSimulator/Devices/
cd `ls -t | head -n 1`/data/Containers/Data/Application
cd `ls -t | head -n 1`/Documents
open .
To create an easy runnable script, put it in an Automator Application with "Run Shell Script":
Here it is, wrapped up in a nice and reusable method:
public static int count(String text, String find) {
int index = 0, count = 0, length = find.length();
while( (index = text.indexOf(find, index)) != -1 ) {
index += length; count++;
}
return count;
}
You actually do not have to wait a full second for each request. I found that if I wait 200 miliseconds between each request I am able to avoid the OVER_QUERY_LIMIT response and the user experience is passable. With this solution you can load 20 items in 4 seconds.
$(items).each(function(i, item){
setTimeout(function(){
geoLocate("my address", function(myLatlng){
...
});
}, 200 * i);
}
In this case , this code
{<td><span onClick={this.toggle()}>Details</span></td>}
causes toggle function to call immediately and re render it again and again thus making infinite calls.
so passing only the reference to that toggle method will solve the problem.
so ,
{<td><span onClick={this.toggle}>Details</span></td>}
will be the solution code.
If you want to use the () , you should use an arrow function like this
{<td><span onClick={()=> this.toggle()}>Details</span></td>}
In case you want to pass parameters you should choose the last option and you can pass parameters like this
{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}
In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.
C99 requires that when a/b
is representable:
(a/b) * b
+ a%b
shall equal a
This makes sense, logically. Right?
Let's see what this leads to:
Example A. 5/(-3)
is -1
=> (-1) * (-3)
+ 5%(-3)
= 5
This can only happen if 5%(-3)
is 2.
Example B. (-5)/3
is -1
=> (-1) * 3
+ (-5)%3
= -5
This can only happen if (-5)%3
is -2
When I was trying to accomplish something very similar, I ended up doing something along these lines:
wp-content/themes/resources/functions.php
add_action('init', 'my_php_function');
function my_php_function() {
if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
// add desired php code here
}
}
#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}
#Convert dictionary to list (array)
keys = list(animals)
#Printing 1st dictionary key by index
print(keys[0])
#Done :)
Here is a simple and very inelegant & potentially dangerous way.
I'm guessing that you are not doing log backups. (Which truncate the log). My advice is to change recovery model from full to simple. This will prevent log bloat.
There are some issues with the scripts above:
shift "removes" the parameter $1, otherwise, "push" will read it and "misunderstand it".
My tip :
git config --global alias.acpp '!git add -A && branchatu="$(git symbolic-ref HEAD 2>/dev/null)" && branchatu=${branchatu##refs/heads/} && git commit -m "$1" && shift && git pull -u origin $branchatu && git push -u origin $branchatu'
function loadpage (page_request, containerid)
{
var loading = document.getElementById ( "loading" ) ;
// when connecting to server
if ( page_request.readyState == 1 )
loading.style.visibility = "visible" ;
// when loaded successfully
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
{
document.getElementById(containerid).innerHTML=page_request.responseText ;
loading.style.visibility = "hidden" ;
}
}
Implemented the same in scala, Please help urself with converting to Java, the core logic and functions used stays the same.
import java.text.SimpleDateFormat
import org.apache.commons.lang.time.DateUtils
object MultiDataFormat {
def main(args: Array[String]) {
val dates =Array("2015-10-31","26/12/2015","19-10-2016")
val possibleDateFormats:Array[String] = Array("yyyy-MM-dd","dd/MM/yyyy","dd-MM-yyyy")
val sdf = new SimpleDateFormat("yyyy-MM-dd") //change it as per the requirement
for (date<-dates) {
val outputDate = DateUtils.parseDateStrictly(date, possibleDateFormats)
System.out.println("inputDate ==> " + date + ", outputDate ==> " +outputDate + " " + sdf.format(outputDate) )
}
}
}
Use a regular expression on a string:
def is_numeric?(obj)
obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end
If you want to check if a variable is of certain type, you can simply use kind_of?
:
1.kind_of? Integer #true
(1.5).kind_of? Float #true
is_numeric? "545" #true
is_numeric? "2aa" #false
Below are the differences between CrudRepository
and JpaRepository
as:
CrudRepository
CrudRepository
is a base interface and extends the Repository
interface.CrudRepository
mainly provides CRUD (Create, Read, Update, Delete) operations.saveAll()
method is Iterable
.CrudRepository
.JpaRepository
JpaRepository
extends PagingAndSortingRepository
that extends CrudRepository
.JpaRepository
provides CRUD and pagination operations, along with additional methods like flush()
, saveAndFlush()
, and deleteInBatch()
, etc.saveAll()
method is a List
.JpaRepository
.I have an answer (I admit somewhat confusing answer) that involvessed
, regular expressions and capture groups:
\S*
- first word\s*
- delimiter(\S*)
- second word - captured.*
- rest of the lineAs a sed
expression, the capture group needs to be escaped, i.e. \(
and \)
.
The \1
returns a copy of the captured group, i.e. the second word.
$ echo "alpha beta gamma delta" | sed 's/\S*\s*\(\S*\).*/\1/'
beta
When you look at this answer, its somewhat confusing, and, you may think, why bother? Well, I'm hoping that some, may go "Aha!" and will use this pattern to solve some complex text extraction problems with a single sed
expression.
These are the changes to make:
CSS:
#container {
width: 100%;
height: 100%;
top: 0;
position: absolute;
visibility: hidden;
display: none;
background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
visibility: visible;
display: block;
}
.reveal-modal {
position: relative;
margin: 0 auto;
top: 25%;
}
/* Remove the left: 50% */
HTML:
<a href="#container">Reveal</a>
<div id="container">
<div id="exampleModal" class="reveal-modal">
........
<a href="#">Close Modal</a>
</div>
</div>
fork()
splits the current process into two processes. Or in other words, your nice linear easy to think of program suddenly becomes two separate programs running one piece of code:
int pid = fork();
if (pid == 0)
{
printf("I'm the child");
}
else
{
printf("I'm the parent, my child is %i", pid);
// here we can kill the child, but that's not very parently of us
}
This can kind of blow your mind. Now you have one piece of code with pretty much identical state being executed by two processes. The child process inherits all the code and memory of the process that just created it, including starting from where the fork()
call just left off. The only difference is the fork()
return code to tell you if you are the parent or the child. If you are the parent, the return value is the id of the child.
exec
is a bit easier to grasp, you just tell exec
to execute a process using the target executable and you don't have two processes running the same code or inheriting the same state. Like @Steve Hawkins says, exec
can be used after you fork
to execute in the current process the target executable.
From Android Studio v3 and up, Infer Constraint was removed from the dropdown.
Use the magic wand icon in the toolbar menu above the design preview; there is the "Infer Constraints" button. Click on this button, this will automatically add some lines in the text field and the red line will be removed.
i wrote a simple ES6 class that may come handy. inspired by https://stackoverflow.com/a/58580918/4907364 answer
export class IntervalTimer {
private callbackStartTime;
private remaining= 0;
private paused= false;
public timerId = null;
private readonly _callback;
private readonly _delay;
constructor(callback, delay) {
this._callback = callback;
this._delay = delay;
}
pause() {
if (!this.paused) {
this.clear();
this.remaining = new Date().getTime() - this.callbackStartTime;
this.paused = true;
}
}
resume() {
if (this.paused) {
if (this.remaining) {
setTimeout(() => {
this.run();
this.paused = false;
this.start();
}, this.remaining);
} else {
this.paused = false;
this.start();
}
}
}
clear() {
clearInterval(this.timerId);
}
start() {
this.clear();
this.timerId = setInterval(() => {
this.run();
}, this._delay);
}
private run() {
this.callbackStartTime = new Date().getTime();
this._callback();
}
}
usage is pretty straightforward,
const interval = new IntervalTimer(console.log(aaa), 3000);
interval.start();
interval.pause();
interval.resume();
interval.clear();
If you want to overwrite the existing class for different collection using typescript
then you have to inherit the existing class from different class.
export class User extends Typegoose{
@prop
username?:string
password?:string
}
export class newUser extends User{
constructor() {
super();
}
}
export const UserModel = new User ().getModelForClass(User , { schemaOptions: { collection: "collection1" } });
export const newUserModel = new newUser ().getModelForClass(newUser , { schemaOptions: { collection: "collection2" } });
Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx
web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
or one of its dep...".
So log on the server and debug from there.
you need to add Content-Length: 0
in your request header.
a very descriptive example of how to test is given here
You can do :
document.forms["loginForm"].submit()
But this won't call the onclick
action of your button, so you will need to call it by hand.
Be aware that you must use the name
of your form and not the id
to access it.
You cannot play two animations since the attribute can be defined only once. Rather why don't you include the second animation in the first and adjust the keyframes to get the timing right?
.image {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width: 120px;_x000D_
height: 120px;_x000D_
margin:-60px 0 0 -60px;_x000D_
-webkit-animation:spin-scale 4s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin-scale { _x000D_
50%{_x000D_
transform: rotate(360deg) scale(2);_x000D_
}_x000D_
100% { _x000D_
transform: rotate(720deg) scale(1);_x000D_
} _x000D_
}
_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
_x000D_
If you have the proxies set up correctly, and still cannot reach the internet, it could be the DNS resolution. Check /etc/resolve.conf
on the host Ubuntu VM. If it contains nameserver 127.0.1.1
, that is wrong.
Run these commands on the host Ubuntu VM to fix it:
sudo vi /etc/NetworkManager/NetworkManager.conf
# Comment out the line `dns=dnsmasq` with a `#`
# restart the network manager service
sudo systemctl restart network-manager
cat /etc/resolv.conf
Now /etc/resolv.conf
should have a valid value for nameserver, which will be copied by the docker containers.
If you are fine using a graphical tool this works very well:
gitk <file>
gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!
Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:
<button class="btn btn-large btn-primary newclass" type="button">Submit</button>
and the CSS would be:
.btn.newclass {width:25%; display:block; margin: 0 auto;}
The "width" value is up to you, and you can play with that to get the right look.
Steve
An understanding of the Iterator pattern will be helpful for you. I recommend reading the same.
At a high level the iterator pattern can be used to provide a standard way of iterating through collections of any type. We have 3 participants in the iterator pattern, the actual collection (client), the aggregator and the iterator. The aggregate is an interface/abstract class that has a method that returns an iterator. Iterator is an interface/abstract class that has methods allowing us to iterate through a collection.
In order to implement the pattern we first need to implement an iterator to produce a concrete that can iterate over the concerned collection (client) Then the collection (client) implements the aggregator to return an instance of the above iterator.
So basically in c#, IEnumerable is the abstract aggregate and IEnumerator is the abstract Iterator. IEnumerable has a single method GetEnumerator that is responsible for creating an instance of IEnumerator of the desired type. Collections like Lists implement the IEnumerable.
Example.
Lets suppose that we have a method getPermutations(inputString)
that returns all the permutations of a string and that the method returns an instance of IEnumerable<string>
In order to count the number of permutations we could do something like the below.
int count = 0;
var permutations = perm.getPermutations(inputString);
foreach (string permutation in permutations)
{
count++;
}
The c# compiler more or less converts the above to
using (var permutationIterator = perm.getPermutations(input).GetEnumerator())
{
while (permutationIterator.MoveNext())
{
count++;
}
}
If you have any questions please don't hesitate to ask.
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("Main Page");
w.show();
return a.exec();
}
I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure
- projects
- go.mod
- go.sum
- project1
- main.go
- project2
- main.go
- package1
- lib.go
- package2
- lib.go
And I am able to import package1 and package2 from project1 and project2 by using
import (
"projects/package1"
"projects/package2"
)
After running go mod init projects
. I can use go build
from project1 and project2 directories or I can do go build -o project1/exe project1/*.go
from the projects directory.
The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.
Do NOT do that! setNum(num);//fix- until someone fixes your setter. Your getter should not call your setter with the uninitialized value of
num(e.g.
0`).
I suggest making a few small changes -
public static class Vars { private int num = 5; // Default to 5. public void setNum(int x) { this.num = x; // actually "set" the value. } public int getNum() { return num; } }
I've been using the same approach of saving the hidden TabPages in a private list, but the problem is that when I want to show the TabPage again, they doesn't appears in the original position (order). So, finally, I wrote a class in VB to add the TabControl with two methods: HideTabPageByName and ShowTabPageByName. You can just call the methods passing the name (not the TabPage instance).
Public Class CS_Control_TabControl
Inherits System.Windows.Forms.TabControl
Private mTabPagesHidden As New Dictionary(Of String, System.Windows.Forms.TabPage)
Private mTabPagesOrder As List(Of String)
Public Sub HideTabPageByName(ByVal TabPageName As String)
If mTabPagesOrder Is Nothing Then
' The first time the Hide method is called, save the original order of the TabPages
mTabPagesOrder = New List(Of String)
For Each TabPageCurrent As TabPage In Me.TabPages
mTabPagesOrder.Add(TabPageCurrent.Name)
Next
End If
If Me.TabPages.ContainsKey(TabPageName) Then
Dim TabPageToHide As TabPage
' Get the TabPage object
TabPageToHide = TabPages(TabPageName)
' Add the TabPage to the internal List
mTabPagesHidden.Add(TabPageName, TabPageToHide)
' Remove the TabPage from the TabPages collection of the TabControl
Me.TabPages.Remove(TabPageToHide)
End If
End Sub
Public Sub ShowTabPageByName(ByVal TabPageName As String)
If mTabPagesHidden.ContainsKey(TabPageName) Then
Dim TabPageToShow As TabPage
' Get the TabPage object
TabPageToShow = mTabPagesHidden(TabPageName)
' Add the TabPage to the TabPages collection of the TabControl
Me.TabPages.Insert(GetTabPageInsertionPoint(TabPageName), TabPageToShow)
' Remove the TabPage from the internal List
mTabPagesHidden.Remove(TabPageName)
End If
End Sub
Private Function GetTabPageInsertionPoint(ByVal TabPageName As String) As Integer
Dim TabPageIndex As Integer
Dim TabPageCurrent As TabPage
Dim TabNameIndex As Integer
Dim TabNameCurrent As String
For TabPageIndex = 0 To Me.TabPages.Count - 1
TabPageCurrent = Me.TabPages(TabPageIndex)
For TabNameIndex = TabPageIndex To mTabPagesOrder.Count - 1
TabNameCurrent = mTabPagesOrder(TabNameIndex)
If TabNameCurrent = TabPageCurrent.Name Then
Exit For
End If
If TabNameCurrent = TabPageName Then
Return TabPageIndex
End If
Next
Next
Return TabPageIndex
End Function
Protected Overrides Sub Finalize()
mTabPagesHidden = Nothing
mTabPagesOrder = Nothing
MyBase.Finalize()
End Sub
End Class
I don't think this is achievable using only CSS animations. I am assuming that CSS transitions do not fulfil your use case, because (for example) you want to chain two animations together, use multiple stops, iterations, or in some other way exploit the additional power animations grant you.
I've not found any way to trigger a CSS animation specifically on mouse-out without using JavaScript to attach "over" and "out" classes. Although you can use the base CSS declaration trigger an animation when the :hover ends, that same animation will then run on page load. Using "over" and "out" classes you can split the definition into the base (load) declaration and the two animation-trigger declarations.
The CSS for this solution would be:
.class {
/* base element declaration */
}
.class.out {
animation-name: out;
animation-duration:2s;
}
.class.over {
animation-name: in;
animation-duration:5s;
animation-iteration-count:infinite;
}
@keyframes in {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes out {
from {
transform: rotate(360deg);
}
to {
transform: rotate(0deg);
}
}
And using JavaScript (jQuery syntax) to bind the classes to the events:
$(".class").hover(
function () {
$(this).removeClass('out').addClass('over');
},
function () {
$(this).removeClass('over').addClass('out');
}
);
Discussing nested classes...
The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.
When you have a nested class declaration that is not static, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.
But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.
You only need to add your "mingw-install-directory"/bin/ to your Path in your System environment variables ... that's it !!
It affects the whole child divs when you use the opacity feature with positions other than absolute. So another way to achieve it not to put divs inside each other and then use the position absolute for the divs. Dont use any background color for the upper div.
Use this condition:
if (jQuery(".profile-page-cont").css('display') == 'block'){
// Condition
}
Here is example using xargs
:
$ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file