You can add a file as a resource using two separate methods.
The C# code required to access the file is different, depending on the method used to add the file in the first place.
Embedded Resource
Add the file to your project, then set the type to Embedded Resource
.
NOTE: If you add the file using this method, you can use GetManifestResourceStream
to access it (see answer from @dtb).
Resources.resx
Open up the Resources.resx
file, use the dropdown box to add the file, set Access Modifier
to public
.
NOTE: If you add the file using this method, you can use Properties.Resources
to access it (see answer from @Night Walker).
To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.
Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.
From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:
E:first-child
, E:hover
, E > F
(Child combinator), E + F
(Adjacent sibling combinator), E ~ F
(General sibling combinator). This unfortunately means resorting to workarounds like inline styles.white-space
won't work.background-image
property won't work.height
, width
, and the max-
versions are either not usable or have bugs for certain elements.display
, float
s and position
are all out).In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.
PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top
" where you probably meant to use vertical-align
. Also: cell-padding
for td
s doesn't exist.
I would suggest you have to use a Reader to convert your InputStream in.
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
new JSONObject(responseStrBuilder.toString());
I tried in.toString() but it returns:
getClass().getName() + '@' + Integer.toHexString(hashCode())
(like documentation says it derives to toString from Object)
If you have two DateTime that looks the same, but Compare or Equals doesn't return what you expect, this is how to compare them.
Here an example with 1-millisecond precision:
bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);
I solved this on my WAMP setup by enabling the php_openssl
extension, since the URL I was loading from used https://
.
According to Scalability and Limits section in http://dev.mysql.com/doc/refman/5.6/en/features.html, MySQL support for large databases. They use MySQL Server with databases that contain 50 million records. Some users use MySQL Server with 200,000 tables and about 5,000,000,000 rows.
Here's a possibile solution (in Python):
Let's say you have a notebook with a file name, call it Notebook.ipynb. You are currently working in that notebook, and want to access other folders and files around it. Here's it's path:
import os
notebook_path = os.path.abspath("Notebook.ipynb")
In other words, just use the os module, and get the absolute path of your notebook (it's a file, too!). From there, use the os module and your path to navigate.
For example, if your train.csv is in a folder called 'Datasets', and the notebook is sitting right next to that folder, you could get the data like this:
train_csv = os.path.join(os.path.dirname(notebook_path), "Datasets/train.csv")
with open(train_csv) as file:
#....etc
The takeaway is that the notebook has a file name, and as long as your language supports pathname manipulations (e.g. the os module in Python) you can likely use the notebook filename.
Lastly, the reason your code fails is probably because you're either trying to access local files (like your Mac's 'Downloads' folder) when you're working in an online Notebook (like Kaggle, which hosts your environment for you, online and away from your Mac), or you moved or deleted something in that path. This is what the os module in Python is meant to do; it will find the file's path whether it's on your Mac or in a Kaggle server.
On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div
again). This is probably done on other architectures too.
Instruction:
DIV
srcNote: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.
int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, @"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
So if condition equals the value you want then the php document will run "include" and include will add that document to the current window for example:
`
<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>
`
For AWS if the user is ubuntu use the following to connect to remote server.
chmod 400 mykey.pem
ssh -i mykey.pem ubuntu@your-ip
Hi guys. Here is a jQuery plugin I wrote to do the same, but also account for the height differences that will occur when you have box-sizing
set to border-box
.
I also included a "yShrinkOut" plugin that hides the element by shrinking it along the y-axis.
// -------------------------------------------------------------------
// Function to show an object by allowing it to grow to the given height value.
// -------------------------------------------------------------------
$.fn.yGrowIn = function (growTo, duration, whenComplete) {
var f = whenComplete || function () { }, // default function is empty
obj = this,
h = growTo || 'calc', // default is to calculate height
bbox = (obj.css('box-sizing') == 'border-box'), // check box-sizing
d = duration || 200; // default duration is 200 ms
obj.css('height', '0px').removeClass('hidden invisible');
var padTop = 0 + parseInt(getComputedStyle(obj[0], null).paddingTop), // get the starting padding-top
padBottom = 0 + parseInt(getComputedStyle(obj[0], null).paddingBottom), // get the starting padding-bottom
padLeft = 0 + parseInt(getComputedStyle(obj[0], null).paddingLeft), // get the starting padding-left
padRight = 0 + parseInt(getComputedStyle(obj[0], null).paddingRight); // get the starting padding-right
obj.css('padding-top', '0px').css('padding-bottom', '0px'); // Set the padding to 0;
// If no height was given, then calculate what the height should be.
if(h=='calc'){
var p = obj.css('position'); // get the starting object "position" style.
obj.css('opacity', '0'); // Set the opacity to 0 so the next actions aren't seen.
var cssW = obj.css('width') || 'auto'; // get the CSS width if it exists.
var w = parseInt(getComputedStyle(obj[0], null).width || 0) // calculate the computed inner-width with regard to box-sizing.
+ (!bbox ? parseInt((getComputedStyle(obj[0], null).borderRightWidth || 0)) : 0) // remove these values if using border-box.
+ (!bbox ? parseInt((getComputedStyle(obj[0], null).borderLeftWidth || 0)) : 0) // remove these values if using border-box.
+ (!bbox ? (padLeft + padRight) : 0); // remove these values if using border-box.
obj.css('position', 'fixed'); // remove the object from the flow of the document.
obj.css('width', w); // make sure the width remains the same. This prevents content from throwing off the height.
obj.css('height', 'auto'); // set the height to auto for calculation.
h = parseInt(0); // calculate the auto-height
h += obj[0].clientHeight // calculate the computed height with regard to box-sizing.
+ (bbox ? parseInt((getComputedStyle(obj[0], null).borderTopWidth || 0)) : 0) // add these values if using border-box.
+ (bbox ? parseInt((getComputedStyle(obj[0], null).borderBottomWidth || 0)) : 0) // add these values if using border-box.
+ (bbox ? (padTop + padBottom) : 0); // add these values if using border-box.
obj.css('height', '0px').css('position', p).css('opacity','1'); // reset the height, position, and opacity.
};
// animate the box.
// Note: the actual duration of the animation will change depending on the box-sizing.
// e.g., the duration will be shorter when using padding and borders in box-sizing because
// the animation thread is growing (or shrinking) all three components simultaneously.
// This can be avoided by retrieving the calculated "duration per pixel" based on the box-sizing type,
// but it really isn't worth the effort.
obj.animate({ 'height': h, 'padding-top': padTop, 'padding-bottom': padBottom }, d, 'linear', (f)());
};
// -------------------------------------------------------------------
// Function to hide an object by shrinking its height to zero.
// -------------------------------------------------------------------
$.fn.yShrinkOut = function (d,whenComplete) {
var f = whenComplete || function () { },
obj = this,
padTop = 0 + parseInt(getComputedStyle(obj[0], null).paddingTop),
padBottom = 0 + parseInt(getComputedStyle(obj[0], null).paddingBottom),
begHeight = 0 + parseInt(obj.css('height'));
obj.animate({ 'height': '0px', 'padding-top': 0, 'padding-bottom': 0 }, d, 'linear', function () {
obj.addClass('hidden')
.css('height', 0)
.css('padding-top', padTop)
.css('padding-bottom', padBottom);
(f)();
});
};
Any of the parameters I used can be omitted or set to null in order to accept default values. The parameters I used:
Go into your AndroidManifest.xml file
Enjoy using a gui rather then messing with an image editor! Hope this helps!
There is a way to do this without using a pipe character, which is convenient if you are forking a process from another programming language to do this:
find $JAVA_SRC_DIR -name '*.java' -exec javac -d $OUTPUT_DIR {} +
Though if you are in Bash and/or don't mind using a pipe, then you can do:
find $JAVA_SRC_DIR -name '*.java' | xargs javac -d $OUTPUT_DIR
Adding the default_url in routes not the right solution although, it works for some cases.
You've to set the default_url in each environment(development, test, production).
You need make these changes.
config/environments/development.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
config/environments/test.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
config/environments/development.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
Add the image to Your project by clicking File -> "Add Files to ...".
Then choose the image in ImageView properties (Utilities -> Attributes Inspector).
Partitioning data is often used for distributing load horizontally, this has performance benefit, and helps in organizing data in a logical fashion. Example: if we are dealing with a large employee
table and often run queries with WHERE
clauses that restrict the results to a particular country or department . For a faster query response Hive table can be PARTITIONED BY (country STRING, DEPT STRING)
. Partitioning tables changes how Hive structures the data storage and Hive will now create subdirectories reflecting the partitioning structure like
.../employees/country=ABC/DEPT=XYZ.
If query limits for employee from country=ABC
, it will only scan the contents of one directory country=ABC
. This can dramatically improve query performance, but only if the partitioning scheme reflects common filtering. Partitioning feature is very useful in Hive, however, a design that creates too many partitions may optimize some queries, but be detrimental for other important queries. Other drawback is having too many partitions is the large number of Hadoop files and directories that are created unnecessarily and overhead to NameNode since it must keep all metadata for the file system in memory.
Bucketing is another technique for decomposing data sets into more manageable parts. For example, suppose a table using date
as the top-level partition and employee_id
as the second-level partition leads to too many small partitions. Instead, if we bucket the employee table and use employee_id
as the bucketing column, the value of this column will be hashed by a user-defined number into buckets. Records with the same employee_id
will always be stored in the same bucket. Assuming the number of employee_id
is much greater than the number of buckets, each bucket will have many employee_id
. While creating table you can specify like CLUSTERED BY (employee_id) INTO XX BUCKETS;
where XX is the number of buckets . Bucketing has several advantages. The number of buckets is fixed so it does not fluctuate with data. If two tables are bucketed by employee_id
, Hive can create a logically correct sampling. Bucketing also aids in doing efficient map-side joins etc.
All of the above solutions I tried failed either to separate stderr and stdout output, (multiple pipes) or blocked forever when the OS pipe buffer was full which happens when the command you are running outputs too fast (there is a warning for this on python poll() manual of subprocess). The only reliable way I found was through select, but this is a posix-only solution:
import subprocess
import sys
import os
import select
# returns command exit status, stdout text, stderr text
# rtoutput: show realtime output while running
def run_script(cmd,rtoutput=0):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
poller = select.poll()
poller.register(p.stdout, select.POLLIN)
poller.register(p.stderr, select.POLLIN)
coutput=''
cerror=''
fdhup={}
fdhup[p.stdout.fileno()]=0
fdhup[p.stderr.fileno()]=0
while sum(fdhup.values()) < len(fdhup):
try:
r = poller.poll(1)
except select.error, err:
if err.args[0] != EINTR:
raise
r=[]
for fd, flags in r:
if flags & (select.POLLIN | select.POLLPRI):
c = os.read(fd, 1024)
if rtoutput:
sys.stdout.write(c)
sys.stdout.flush()
if fd == p.stderr.fileno():
cerror+=c
else:
coutput+=c
else:
fdhup[fd]=1
return p.poll(), coutput.strip(), cerror.strip()
I know this is old, but none of these expressions worked for me (maybe it's because I'm on PHP). The following expression worked fine to validate that a number is higher than 49:
/([5-9][0-9])|([1-9]\d{3}\d*)/
You can do something like this
Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();
where you can change "firstname" with the name of the column you want.
I got this issue for my demo program created in IntelliJ.
There are two key points to solve it:
my demo program:
package io.rlx.tij.c2;
public class Ex10 {
public static void main(String[] args) {
// do something
}
}
the path of source code:
../projectRoot/src/main/java/io/rlx/tij/c2/Ex10.java
java
dir: cd ../projectRoot/src/main/java
javac ./io/rlx/tij/c2/Ex10.java
java io.rlx.tij.c2.Ex10
if I run program in ../projectRoot/src/main/java/io/rlx/tij/c2
or I run it without package name, I will get this error: Error: Could not find or load main class
.
The CSS solution for Angular Bootstrap is
::ng-deep .tooltip-inner {
white-space: pre-wrap;
}
No need to use a parent element or class selector if you don't need to restrict it's use. Copy/Pasta, and this rule will apply to all sub-components
This is how I've added a bot to my channel and set up notifications:
telegram.me/whateverIWantAndAvailable
the channel id will be @whateverIWantAndAvailable
Now set up your bot to send notifications by pusshing the messages here:
https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test
the message which bot will notify is: Test
I strongly suggest an urlencode of the message like
https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works
in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");
I hope it helps
I used the following:
delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")
Mutex and Semaphore didn't work in my case (I tried them as suggested, but it didn't do the trick in the application I developed). The answer abramlimpin provided worked for me, after I made a slight modification.
This is how I got it working finally. First, I created some helper functions:
public static class Ext
{
private static string AssemblyFileName(this Assembly myAssembly)
{
string strLoc = myAssembly.Location;
FileSystemInfo fileInfo = new FileInfo(strLoc);
string sExeName = fileInfo.Name;
return sExeName;
}
private static int HowManyTimesIsProcessRunning(string name)
{
int count = 0;
name = name.ToLowerInvariant().Trim().Replace(".exe", "");
foreach (Process clsProcess in Process.GetProcesses())
{
var processName = clsProcess.ProcessName.ToLowerInvariant().Trim();
// System.Diagnostics.Debug.WriteLine(processName);
if (processName.Contains(name))
{
count++;
};
};
return count;
}
public static int HowManyTimesIsAssemblyRunning(this Assembly myAssembly)
{
var fileName = AssemblyFileName(myAssembly);
return HowManyTimesIsProcessRunning(fileName);
}
}
Then, I added the following to the main method:
[STAThread]
static void Main()
{
const string appName = "Name of your app";
// Check number of instances running:
// If more than 1 instance, cancel this one.
// Additionally, if it is the 2nd invocation, show a message and exit.
var numberOfAppInstances = Assembly.GetExecutingAssembly().HowManyTimesIsAssemblyRunning();
if (numberOfAppInstances == 2)
{
MessageBox.Show("The application is already running!
+"\nClick OK to close this dialog, then switch to the application by using WIN + TAB keys.",
appName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
};
if (numberOfAppInstances >= 2)
{
return;
};
}
If you invoke the application a 3rd, 4th ... time, it does not show the warning any more and just exits immediately.
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
Simply grab a reference to the target view controller in prepareForSegue:
method and pass any objects you need to there. Here's an example...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
{
// Get reference to the destination view controller
YourViewController *vc = [segue destinationViewController];
// Pass any objects to the view controller here, like...
[vc setMyObjectHere:object];
}
}
REVISION: You can also use performSegueWithIdentifier:sender:
method to activate the transition to a new view based on a selection or button press.
For instance, consider I had two view controllers. The first contains three buttons and the second needs to know which of those buttons has been pressed before the transition. You could wire the buttons up to an IBAction
in your code which uses performSegueWithIdentifier:
method, like this...
// When any of my buttons are pressed, push the next view
- (IBAction)buttonPressed:(id)sender
{
[self performSegueWithIdentifier:@"MySegue" sender:sender];
}
// This will get called too before the view appears
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"MySegue"]) {
// Get destination view
SecondView *vc = [segue destinationViewController];
// Get button tag number (or do whatever you need to do here, based on your object
NSInteger tagIndex = [(UIButton *)sender tag];
// Pass the information to your destination view
[vc setSelectedButton:tagIndex];
}
}
EDIT: The demo application I originally attached is now six years old, so I've removed it to avoid any confusion.
Years later, but a useful option would be to utilize XPath Axes (https://www.w3schools.com/xml/xpath_axes.asp). More specifically, you are looking to use the descendants axes.
I believe this example would do the trick:
//book[descendant::title[@lang='it']]
This allows you to select all book
elements that contain a child title
element (regardless of how deep it is nested) containing language attribute value equal to 'it'.
I cannot say for sure whether or not this answer is relevant to the year 2009 as I am not 100% certain that the XPath Axes existed at that time. What I can confirm is that they do exist today and I have found them to be extremely useful in XPath navigation and I am sure you will as well.
The standard Servlet API doesn't support this facility. You may want either to use a rewrite-URL filter for this like Tuckey's one (which is much similar Apache HTTPD's mod_rewrite
), or to add a check in the doFilter()
method of the Filter listening on /*
.
String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
chain.doFilter(request, response); // Just continue chain.
} else {
// Do your business stuff here for all paths other than /specialpath.
}
You can if necessary specify the paths-to-be-ignored as an init-param
of the filter so that you can control it in the web.xml
anyway. You can get it in the filter as follows:
private String pathToBeIgnored;
public void init(FilterConfig config) {
pathToBeIgnored = config.getInitParameter("pathToBeIgnored");
}
If the filter is part of 3rd party API and thus you can't modify it, then map it on a more specific url-pattern
, e.g. /otherfilterpath/*
and create a new filter on /*
which forwards to the path matching the 3rd party filter.
String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
chain.doFilter(request, response); // Just continue chain.
} else {
request.getRequestDispatcher("/otherfilterpath" + path).forward(request, response);
}
To avoid that this filter will call itself in an infinite loop you need to let it listen (dispatch) on REQUEST
only and the 3rd party filter on FORWARD
only.
Besides the solution of using an additional list and calling addAll to insert the new items after the iteration (as e.g. the solution by user Nat), you can also use concurrent collections like the CopyOnWriteArrayList.
The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.
With this special collection (usually used for concurrent access) it is possible to manipulate the underlying list while iterating over it. However, the iterator will not reflect the changes.
Is this better than the other solution? Probably not, I don't know the overhead introduced by the Copy-On-Write approach.
In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.
So register the ChildComponent in Shared Module manually.
You can use the description
method inherited by NSDictionary
from NSObject
, or write a custom method that formats NSDictionary
to your liking.
In IntelliJ you can specify default settings for each run configuration. In Run/Debug configuration dialog (the one you use to configure heap per test) click on Defaults and JUnit. These settings will be automatically applied to each new JUnit test configuration. I guess similar setting exists for Eclipse.
However there is no simple option to transfer such settings (at least in IntelliJ) across environments. You can commit IntelliJ project files to your repository: it might work, but I do not recommend it.
You know how to set these for maven-surefire-plugin
. Good. This is the most portable way (see Ptomli's answer for an example).
For the rest - you must remember that JUnit test cases are just a bunch of Java classes, not a standalone program. It is up to the runner (let it be a standalone JUnit runner, your IDE, maven-surefire-plugin
to set those options. That being said there is no "portable" way to set them, so that memory settings are applied irrespective to the runner.
To give you an example: you cannot define Xmx
parameter when developing a servlet - it is up to the container to define that. You can't say: "this servlet should always be run with Xmx=1G
.
instead of using
session.delete(object)
use
getHibernateTemplate().delete(object)
In both place for select
query and also for delete
use getHibernateTemplate()
In select
query you have to use DetachedCriteria
or Criteria
Example for select query
List<foo> fooList = new ArrayList<foo>();
DetachedCriteria queryCriteria = DetachedCriteria.forClass(foo.class);
queryCriteria.add(Restrictions.eq("Column_name",restriction));
fooList = getHibernateTemplate().findByCriteria(queryCriteria);
In hibernate avoid use of session,here I am not sure but problem occurs just because of session use
A) Run gradle dependencies
or ./gradlew dependencies
B) Look at your tree and figure out which of your dependencies is specifying a different support library version for a dependency you don't control.
I didn't realize that this warning also displays if the dependency is completely unused directly by your own code. In my case, Facebook specifies some support libs I wasn't using, you can see below most of those dependencies were overridden by my own specification of 25.2.0, denoted by the -> X.X.X (*) symbols. The card view and custom tabs libs weren't overridden by anyone, so I need to ask for 25.2.0 for those ones myself even though I don't use them.
+--- com.facebook.android:facebook-android-sdk:4.17.0
| +--- com.android.support:support-v4:25.0.0 -> 25.2.0 (*)
| +--- com.android.support:appcompat-v7:25.0.0 -> 25.2.0 (*)
| +--- com.android.support:cardview-v7:25.0.0
| | \--- com.android.support:support-annotations:25.0.0 -> 25.2.0
| +--- com.android.support:customtabs:25.0.0
| | +--- com.android.support:support-compat:25.0.0 -> 25.2.0 (*)
| | \--- com.android.support:support-annotations:25.0.0 -> 25.2.0
| \--- com.parse.bolts:bolts-android:1.4.0 (*)
If gradle has already warned you and given you examples...
Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0
... it's even easier if you throw in some grep highlighting for the lower version since gradle dependencies
can be quite verbose:
./gradlew dependencies | grep --color -E 'com.android.support:mediarouter-v7|$'
There may be two approaches depending on your server side logic.
Approach 1: When server is not smart enough to handle object states.
You could send all cached record unique id’s to server, for example ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"] and a boolean parameter to know whether you are requesting new records(pull to refresh) or old records(load more).
Your sever should responsible to return new records(load more records or new records via pull to refresh) as well as id’s of deleted records from ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"].
Example:- If you are requesting load more then your request should look something like this:-
{
"isRefresh" : false,
"cached" : ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"]
}
Now suppose you are requesting old records(load more) and suppose "id2" record is updated by someone and "id5" and "id8" records is deleted from server then your server response should look something like this:-
{
"records" : [
{"id" :"id2","more_key":"updated_value"},
{"id" :"id11","more_key":"more_value"},
{"id" :"id12","more_key":"more_value"},
{"id" :"id13","more_key":"more_value"},
{"id" :"id14","more_key":"more_value"},
{"id" :"id15","more_key":"more_value"},
{"id" :"id16","more_key":"more_value"},
{"id" :"id17","more_key":"more_value"},
{"id" :"id18","more_key":"more_value"},
{"id" :"id19","more_key":"more_value"},
{"id" :"id20","more_key":"more_value"}],
"deleted" : ["id5","id8"]
}
But in this case if you’ve a lot of local cached records suppose 500, then your request string will be too long like this:-
{
"isRefresh" : false,
"cached" : ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10",………,"id500"]//Too long request
}
Approach 2: When server is smart enough to handle object states according to date.
You could send the id of first record and the last record and previous request epoch time. In this way your request is always small even if you’ve a big amount of cached records
Example:- If you are requesting load more then your request should look something like this:-
{
"isRefresh" : false,
"firstId" : "id1",
"lastId" : "id10",
"last_request_time" : 1421748005
}
Your server is responsible to return the id’s of deleted records which is deleted after the last_request_time as well as return the updated record after last_request_time between "id1" and "id10" .
{
"records" : [
{"id" :"id2","more_key":"updated_value"},
{"id" :"id11","more_key":"more_value"},
{"id" :"id12","more_key":"more_value"},
{"id" :"id13","more_key":"more_value"},
{"id" :"id14","more_key":"more_value"},
{"id" :"id15","more_key":"more_value"},
{"id" :"id16","more_key":"more_value"},
{"id" :"id17","more_key":"more_value"},
{"id" :"id18","more_key":"more_value"},
{"id" :"id19","more_key":"more_value"},
{"id" :"id20","more_key":"more_value"}],
"deleted" : ["id5","id8"]
}
Pull To Refresh:-
Load More
These are all close to the right answer, but I wouldn't say any solve the problem while remaining most readable to others reading your code. I'd say that answer is a combination of BrenBarn's Answer and tuomasttik's comment below that answer. BrenBarn's answer utilizes isspace
builtin, but does not support removing empty strings, as OP requested, and I would tend to attribute that as the standard use case of replacing strings with null.
I rewrote it with .apply
, so you can call it on a pd.Series
or pd.DataFrame
.
Python 3:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and x.isspace() else x)
To use this in Python 2, you'll need to replace str
with basestring
.
Python 2:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)
move your "uses-sdk" attribute in top of the manifest like the below answer https://stackoverflow.com/a/27658827/1394139
I would also recommend Ilmbase, which is part of OpenEXR. It's a good set of templated 2,3,4-vector and matrix routines.
Please check the following file
%SystemRoot%\system32\drivers\etc\host
The line which bind the host name with ip is probably missing a line which bind them togather
127.0.0.1 localhost
If the given line is missing. Add the line in the file
Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.
This is a little more lightweight than Arrays.copyOfRange - no range or negative
public static final byte[] copy(byte[] data, int pos, int length )
{
byte[] transplant = new byte[length];
System.arraycopy(data, pos, transplant, 0, length);
return transplant;
}
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
Documentation: Convert JSON to a Type
You can have it this way:
It is important to mind the commas after each struct item or set of items.
earnings := []LineItemsType{
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
}
Click ok and your web sites will load properly.
I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.
I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.
This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.
From @NHG comment — works perfectly
{% for post in posts|slice(0,10) %}
My favorite approach, without external libraries:
try {
URI uri = new URI(name);
// perform checks for scheme, authority, host, etc., based on your requirements
if ("mailto".equals(uri.getScheme()) {/*Code*/}
if (uri.getHost() == null) {/*Code*/}
} catch (URISyntaxException e) {
}
Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...
My answer is superfluous, but if you are OCD, visually oriented and you just have to see that now keyword in your code, use:
date( 'Y-m-d H:i:s', strtotime( 'now' ) );
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json)
. my_json_object
in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.
The way I ended up solving it: the write_to_file.json
will have everything up to the bytes object that is causing the issue.
In my particular case this was a line obtained through
for line in text:
json_object['line'] = line.strip()
I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:
for line in text:
json_object['line'] = line.strip().decode()
Thanks @rofly, the full conversion from string to string is as follows:
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
My summary of the time
/calendar
functions:
time.strptime
string --> tuple (no timezone applied, so matches string)
time.mktime
local time tuple --> seconds since epoch (always local time)
time.gmtime
seconds since epoch --> tuple in UTC
and
calendar.timegm
tuple in UTC --> seconds since epoch
time.localtime
seconds since epoch --> tuple in local timezone
Use requests
library to GET, POST, PUT or DELETE by hitting a REST API endpoint. Pass the rest api endpoint url in url
, payload(dict) in data
and header/metadata in headers
import requests, json
url = "bugs.python.org"
payload = {"number": 12524,
"type": "issue",
"action": "show"}
header = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
response_decoded_json = requests.post(url, data=payload, headers=header)
response_json = response_decoded_json.json()
print response_json
aws s3api list-objects --bucket bucket-name
For more details see here - http://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
You need to be more explicit and add the start and end times as well, down to the milliseconds:
select *
from xxx
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'
The database can very well interpret '2012-10-27'
as '2012-10-27 00:00:00.000'
.
This is the wrong syntax. When you create an anonymous array you MUST NOT give its size.
When you write the following code :
new int[] {1,23,4,4,5,5,5};
You are here creating an anonymous int array whose size will be determined by the number of values that you provide in the curly braces.
You can assign this a reference as you have done, but this will be the correct syntax for the same :-
int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};
Now, just Sysout with proper index position:
System.out.println(a[7]);
Actually ngAfterViewInit()
will initiate only once when the component initiate.
If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()
I tried to store properties by using objc_getAssociatedObject, objc_setAssociatedObject, without any luck. My goal was create extension for UITextField, to validate text input characters length. Following code works fine for me. Hope this will help someone.
private var _min: Int?
private var _max: Int?
extension UITextField {
@IBInspectable var minLength: Int {
get {
return _min ?? 0
}
set {
_min = newValue
}
}
@IBInspectable var maxLength: Int {
get {
return _max ?? 1000
}
set {
_max = newValue
}
}
func validation() -> (valid: Bool, error: String) {
var valid: Bool = true
var error: String = ""
guard let text = self.text else { return (true, "") }
if text.characters.count < minLength {
valid = false
error = "Textfield should contain at least \(minLength) characters"
}
if text.characters.count > maxLength {
valid = false
error = "Textfield should not contain more then \(maxLength) characters"
}
if (text.characters.count < minLength) && (text.characters.count > maxLength) {
valid = false
error = "Textfield should contain at least \(minLength) characters\n"
error = "Textfield should not contain more then \(maxLength) characters"
}
return (valid, error)
}
}
I have tried all of the answers above and it didn't work for me.
In my case when I chekced the log on /usr/local/var/log/postgres.log
. It was fine no error. But I could see that it was listening my local IPV6 address which is "::1"
In my database.yml
I was did it like this
host: <%= ENV['POSTGRESQL_ADDON_HOST'] || '127.0.0.1' %>
I changed it by
host: <%= ENV['POSTGRESQL_ADDON_HOST'] || 'localhost' %>
and then it worked
Method
$user = $stmt->fetch(PDO::FETCH_ASSOC);
returns a dictionary. You can simply get email and password:
$email = $user['email'];
$password = $user['password'];
Other method
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
returns a list of a dictionary
This seems to work for me.
var combindedString = new string(list.ToArray());
Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )
Well generally you shouldn't need to classify an element specified by id, because id is always unique, but if you really need to, the following should work:
div#content.sectionA {
/* ... */
}
Maybe it's possible to debug PHP on Visual Studio, but it's simpler and more logical to use Eclipse PDT or Netbeans IDE for your PHP projects, aside from Visual Studio if you need to use both technologies from two different vendors.
I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.
In your Manifest
<activity android:name=".ActivityHere"
android:label="">
Just check that your packages.config
file is checked in (when excluded, there will be a red no-entry symbol shown in the explorer). For some bizarre reason mine was excluded and caused this issue.
Mux (my company) has an open source android app that streams RTMP to a server, including setting up the camera and user interactions. It's built to stream to Mux's live streaming API but can easily stream to any RTMP entrypoint.
Code will be As below.
[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->
[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->
[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->
[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->
For Details: https://contactform7.com/text-fields/
JSON is simpler and faster than PHP's serialization format and should be used unless:
json_decode()
: "This function will return false if the JSON encoded data is deeper than 127 elements."Refer this link
mysql> SHOW COLUMNS FROM mytable FROM mydb;
mysql> SHOW COLUMNS FROM mydb.mytable;
Hope this may help you
You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:
var a = [];
for (key in saveData) {
a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
In Python:
self
argument.self
) or the class (cls
) argument.__init__
is a special function and without overriding __new__
it will always be given the instance of the class as its first argument.
An example using the builtin classmethod and staticmethod decorators:
import sys
class Num:
max = sys.maxint
def __init__(self,num):
self.n = num
def getn(self):
return self.n
@staticmethod
def getone():
return 1
@classmethod
def getmax(cls):
return cls.max
myObj = Num(3)
# with the appropriate decorator these should work fine
myObj.getone()
myObj.getmax()
myObj.getn()
That said, I would try to use @classmethod
/@staticmethod
sparingly. If you find yourself creating objects that consist of nothing but staticmethod
s the more pythonic thing to do would be to create a new module of related functions.
I tried this and it worked :
git stash && git add . && git stash pop
git stash
will only put all modified tracked files into separate stack, then left over files are untracked files. Then by doing git add .
will stage all files untracked files, as required. Eventually, to get back all modified files from stack by doing git stash pop
No, you can't in Firefox, Safari, etc. You can in Internet Explorer. There are several scripts out there that will allow you to make a scroll bar.
Another cool trick is to run functions or subshells in background, not always feasible though
name(){
echo "Do something"
sleep 1
}
# put a function in the background
name &
#Example taken from here
#https://bash.cyberciti.biz/guide/Putting_functions_in_background
Running a subshell in the background
(echo "started"; sleep 15; echo "stopped") &
Use numpy.apply_along_axis()
. Assuming your matrix is 2D, you can use like:
import numpy as np
mymatrix = np.matrix([[11,12,13],
[21,22,23],
[31,32,33]])
def myfunction( x ):
return sum(x)
print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]
I would extend this question with a NDIS driver example on getting time. As one knows, KeQuerySystemTime (mimicked under NdisGetCurrentSystemTime) has a low resolution above milliseconds, and there are some processes like network packets or other IRPs which may need a better timestamp;
The example is just as simple:
LONG_INTEGER data, frequency;
LONGLONG diff;
data = KeQueryPerformanceCounter((LARGE_INTEGER *)&frequency)
diff = data.QuadPart / (Frequency.QuadPart/$divisor)
where divisor is 10^3, or 10^6 depending on required resolution.
It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:
class A
{
public:
A () {
throw int ();
}
};
A a; // Implementation defined behaviour if exception is thrown (15.3/13)
int main ()
{
try
{
// Exception for 'a' not caught here.
}
catch (int)
{
}
}
A combination of the regex and SimpleDateFormat is the right answer i believe. SimpleDateFormat does not catch exception if the individual components are invalid meaning, Format Defined: yyyy-mm-dd input: 201-0-12 No exception will be thrown.This case should have been handled. But with the regex as suggested by Sok Pomaranczowy and Baby will take care of this particular case.
You can use window.scroll()
with behavior: smooth
and top
set to the anchor tag's offset top which ensures that the anchor tag will be at the top of the viewport.
document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', function (e) {
e.preventDefault();
var href = this.getAttribute("href");
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
//gets Element with an id of the link's href
//or an anchor tag with a name attribute of the href of the link without the #
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
});
//if you want to add the hash to window.location.hash
//you will need to use setTimeout to prevent losing the smooth scrolling behavior
//the following code will work for that purpose
/*setTimeout(function(){
window.location.hash = this.hash;
}, 2000); */
});
});
Demo:
a, a:visited{_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
section{_x000D_
margin: 500px 0px; _x000D_
text-align: center;_x000D_
}
_x000D_
<a href="#section1">Section 1</a>_x000D_
<br/>_x000D_
<a href="#section2">Section 2</a>_x000D_
<br/>_x000D_
<a href="#section3">Section 3</a>_x000D_
<br/>_x000D_
<a href="#section4">Section 4</a>_x000D_
<section id="section1">_x000D_
<b style="font-size: 2em;">Section 1</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>_x000D_
<section>_x000D_
<section id="section2">_x000D_
<b style="font-size: 2em;">Section 2</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<section id="section3">_x000D_
<b style="font-size: 2em;">Section 3</b>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<a style="margin: 500px 0px; color: initial;" name="section4">_x000D_
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>_x000D_
</a>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<script>_x000D_
document.querySelectorAll('a[href^="#"]').forEach(a => {_x000D_
a.addEventListener('click', function (e) {_x000D_
e.preventDefault();_x000D_
var href = this.getAttribute("href");_x000D_
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");_x000D_
window.scroll({_x000D_
top: elem.offsetTop, _x000D_
left: 0, _x000D_
behavior: 'smooth' _x000D_
});_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
You can just set the CSS property scroll-behavior
to smooth
(which most modern browsers support) which obviates the need for Javascript.
html, body{_x000D_
scroll-behavior: smooth;_x000D_
}_x000D_
a, a:visited{_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
section{_x000D_
margin: 500px 0px; _x000D_
text-align: center;_x000D_
}
_x000D_
<a href="#section1">Section 1</a>_x000D_
<br/>_x000D_
<a href="#section2">Section 2</a>_x000D_
<br/>_x000D_
<a href="#section3">Section 3</a>_x000D_
<br/>_x000D_
<a href="#section4">Section 4</a>_x000D_
<section id="section1">_x000D_
<b style="font-size: 2em;">Section 1</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>_x000D_
<section>_x000D_
<section id="section2">_x000D_
<b style="font-size: 2em;">Section 2</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<section id="section3">_x000D_
<b style="font-size: 2em;">Section 3</b>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<a style="margin: 500px 0px; color: initial;" name="section4">_x000D_
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>_x000D_
</a>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
_x000D_
You can do it with Intl.NumberFormat native API.
var number = 123456.78;_x000D_
_x000D_
// India uses thousands/lakh/crore separators_x000D_
console.log(new Intl.NumberFormat('en-IN', {_x000D_
style: 'currency',_x000D_
currency: 'INR'_x000D_
}).format(number));
_x000D_
I had similar requirement (to avoid this ugly ORA-31061: XDB error: special char to escaped char conversion failed. ), but had to keep the line breaks.
I tried this from an excellent comment
'[^ -~|[:space:]]'
but got this ORA-12728: invalid range in regular expression .
but it lead me to my solution:
select t.*, regexp_replace(deta, '[^[:print:]|[:space:]]', '#') from
(select '- <- strangest thing here, and I want to keep line break after
-' deta from dual ) t
displays (in my TOAD tool) as
^
=> is not in the sets (of printing [:print:]
or space |[:space:]
chars)For prototyping, using curl from the shell with the -m
parameter allow to pass milliseconds, and will work in both cases, either the connection didn't initiate, error 404, 500, bad url, or the whole data wasn't retrieved in full in the allowed time range, the timeout is always effective. Php won't ever hang out.
Simply don't pass unsanitized user data in the shell call.
system("curl -m 50 -X GET 'https://api.kraken.com/0/public/OHLC?pair=LTCUSDT&interval=60' -H 'accept: application/json' > data.json");
// This data had been refreshed in less than 50ms
var_dump(json_decode(file_get_contents("data.json"),true));
this is server configuration, set up config.addAllowedHeader("*"); in the CorsConfiguration.
I receive this error in any new module I create with create-react-native-module. None of the posted solutions worked for me.
What worked for me was first making sure to run yarn
in the newly created module folder in order to create node_modules/
(this step is probably obvious). Then, in XCode, select Product -> Scheme -> React instead of the default selection of MyModuleName.
No there isn't. You can only read information associated with the current domain.
A simple Stream extension method would do the job:
public static class StreamExtensions
{
public static string ConvertToBase64(this Stream stream)
{
var bytes = new Byte[(int)stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(bytes, 0, (int)stream.Length);
return Convert.ToBase64String(bytes);
}
}
The methods for Read (and also Write) and optimized for the respective class (whether is file stream, memory stream, etc.) and will do the work for you. For simple task like this, there is no need of readers, and etc.
The only drawback is that the stream is copied into byte array, but that is how the conversion to base64 via Convert.ToBase64String works unfortunately.
declare @cnt bigint
set @cnt = 1
while @cnt*100<10000000
begin
UPDATE top(100) [Imp].[dbo].[tablename]
SET [col1] = xxxx
WHERE[col1] is null
print '@cnt: '+convert(varchar,@cnt)
set @cnt=@cnt+1
end
This works for me
td::after {
content: '';
display: block;
width: 30px;
}
If this object passing does not works:
await browser.executeScript( "arguments[0].scrollIntoView()", await browser.wait( until.elementLocated( By.xpath( "//div[@jscontroller='MC8mtf']" ) ), 1000 ) );
There is a demonstration for scroll to microphone button, on google page. Found it by javascript xpath, using chromedriver and selenium-webdriver.
start1() start a browser in narrow window, the microphone button does not shows.
start2() start a browser in narrow window, then scroll to microphone button.
require('chromedriver');
const { Builder,
By,
Key,
until
} = require('selenium-webdriver');
async function start1() {
var browser = new Builder()
.forBrowser( 'chrome' )
.build();
await browser
.manage()
.window()
.setRect( { width: 80,
height: 1040,
x:-10,
y:0}
);
await browser.navigate().to( "https://www.google.com/" );
}
async function start2() {
var browser = new Builder()
.forBrowser( 'chrome' )
.build();
await browser
.manage()
.window()
.setRect( { width: 80,
height: 1040,
x:-10,
y:0}
);
await browser.navigate().to( "https://www.google.com/" );
await browser.executeScript( "document.evaluate(\"//div[@jscontroller='MC8mtf']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.scrollIntoView(true);");
}
start1();
start2();
You can also specify <error-page>
for exceptions using <exception-type>
, eg below:
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/errorpages/exception.html</location>
</error-page>
Or map a error code using <error-code>
:
<error-page>
<error-code>404</error-code>
<location>/errorpages/404error.html</location>
</error-page>
iTerm2 - an alternative to Terminal - has an option to use configurable system-wide hotkey to show/hide (initially set to Alt+Space, disabled by default)
Thnaks for your answers, it help me alot. as i code in Vb.Net, this Bolt code for Vb.Net
Try
Return MyBase.SaveChanges()
Catch dbEx As Validation.DbEntityValidationException
For Each [error] In From validationErrors In dbEx.EntityValidationErrors
From validationError In validationErrors.ValidationErrors
Select New With { .PropertyName = validationError.PropertyName,
.ErrorMessage = validationError.ErrorMessage,
.ClassFullName = validationErrors.Entry.Entity
.GetType().FullName}
Diagnostics.Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
[error].ClassFullName,
[error].PropertyName,
[error].ErrorMessage)
Next
Throw
End Try
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
This worked for me
getActionBar().setDisplayShowHomeEnabled(false);
Though this is old, I think question is valid even today
My suspicion is that aud should refer to the resource server(s), and the client_id should refer to one of the client applications recognized by the authentication server
Yes, aud should refer to token consuming party. And client_id refers to token obtaining party.
In my current case, my resource server is also my web app client.
In the OP's scenario, web app and resource server both belongs to same party. So this means client and audience to be same. But there can be situations where this is not the case.
Think about a SPA which consume an OAuth protected resource. In this scenario SPA is the client. Protected resource is the audience of access token.
This second scenario is interesting. There is a working draft in place named "Resource Indicators for OAuth 2.0" which explain where you can define the intended audience in your authorisation request. So the resulting token will restricted to the specified audience. Also, Azure OIDC use a similar approach where it allows resource registration and allow auth request to contain resource parameter to define access token intended audience. Such mechanisms allow OAuth adpotations to have a separation between client and token consuming (audience) party.
Caution! The scripts have a limit: it handles up to 500 values in a single drop-down list.
More Info
This solution is not perfect, but it gives some benefits:
First of all, here's working example, so you can test it before going further.
Installation:
Data > Validation
Prepare Data
Data looks like a single table with all possible variants inside it. It must be located on a separate sheet, so it can be used by the script. Look at this example:
Here we have four levels, each value repeats. Note that 2 columns on the right of data are reserved, so don't type/paste there any data.
First simple Data Validation (DV)
Prepare a list of unique values. In our example, it is a list of Planets. Find free space on sheet with data, and paste formula: =unique(A:A)
On your mainsheet select first column, where DV will start. Go to Data > Validation and select range with a unique list.
Script
Paste this code into script editor:
function onEdit(event) _x000D_
{_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data1'; // name of sheet with data_x000D_
var NumOfLevels = 4; // number of levels of data validation_x000D_
var lcol = 2; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,2]; // offsets for levels_x000D_
// ^ means offset column #4 on one position right._x000D_
_x000D_
// =====================================================================================_x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data2'; // name of sheet with data_x000D_
var NumOfLevels = 7; // number of levels of data validation_x000D_
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,1,1,1,1]; // offsets for levels_x000D_
// ===================================================================================== _x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets) _x000D_
{_x000D_
//--------------------------------------------------------------------------------------_x000D_
// The event handler, adds data validation for the input parameters_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
var FormulaSplitter = ';'; // depends on regional setting, ';' or ',' works for US_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
// =================================== key variables =================================_x000D_
//_x000D_
// ss sheet we change (TargetSheet)_x000D_
// br range to change_x000D_
// scol number of column to edit_x000D_
// srow number of row to edit _x000D_
// CurrentLevel level of drop-down, which we change_x000D_
// HeadLevel main level_x000D_
// r current cell, which was changed by user_x000D_
// X number of levels could be checked on the right_x000D_
//_x000D_
// ls Data sheet (LogSheet)_x000D_
//_x000D_
// ======================================================================================_x000D_
_x000D_
// Checks_x000D_
var ts = event.source.getActiveSheet();_x000D_
var sname = ts.getName(); _x000D_
if (sname !== TargetSheet) { return -1; } // not main sheet_x000D_
// Test if range fits_x000D_
var br = event.range;_x000D_
var scol = br.getColumn(); // the column number in which the change is made_x000D_
var srow = br.getRow() // line number in which the change is made_x000D_
var ColNum = br.getWidth();_x000D_
_x000D_
if ((scol + ColNum - 1) < lcol) { return -2; } // columns... _x000D_
if (srow < lrow) { return -3; } // rows_x000D_
// Test range is in levels_x000D_
var columnsLevels = getColumnsOffset_(offsets, lcol); // Columns for all levels _x000D_
var CurrentLevel = getCurrentLevel_(ColNum, br, scol, columnsLevels);_x000D_
if(CurrentLevel === 1) { return -4; } // out of data validations_x000D_
if(CurrentLevel > NumOfLevels) { return -5; } // last level _x000D_
_x000D_
_x000D_
/*_x000D_
ts - sheet with validation, sname = name of sheet_x000D_
_x000D_
NumOfLevels = 4 _x000D_
offsets = [1,1,1,2] - last offset is 2 because need to skip 1 column_x000D_
columnsLevels = [4,5,6,8] - Columns of validation_x000D_
_x000D_
Columns 7 is skipped_x000D_
|_x000D_
1 2 3 4 5 6 7 8 9 _x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
1 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
2 | | | | v | V | ? | x | ? | | lrow = 2 - number of row where validation starts_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
3 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
4 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
| | | | |_x000D_
| | | | Currentlevel = 3 - the number of level to change_x000D_
| | | |_x000D_
| | | br - cell, user changes: scol - column, srow - row,_x000D_
| | ColNum = 1 - width _x000D_
|__|________ _.....____|_x000D_
| v_x000D_
| Drop-down lists _x000D_
|_x000D_
| lcol = 4 - number of column where validation starts_x000D_
*/_x000D_
// Constants_x000D_
var ReplaceCommas = getDecimalMarkIsCommaLocals(); // // ReplaceCommas = true if locale uses commas to separate decimals_x000D_
var ls = SpreadsheetApp.getActive().getSheetByName(LogSheet); // Data sheet _x000D_
var RowNum = br.getHeight();_x000D_
/* Adjust the range 'br' _x000D_
??? !_x000D_
xxx x_x000D_
xxx x _x000D_
xxx => x_x000D_
xxx x_x000D_
xxx x_x000D_
*/ _x000D_
br = ts.getRange(br.getRow(), columnsLevels[CurrentLevel - 2], RowNum); _x000D_
// Levels_x000D_
var HeadLevel = CurrentLevel - 1; // main level_x000D_
var X = NumOfLevels - CurrentLevel + 1; // number of levels left _x000D_
// determine columns on the sheet "Data"_x000D_
var KudaCol = NumOfLevels + 2;_x000D_
var KudaNado = ls.getRange(1, KudaCol); // 1 place for a formula_x000D_
var lastRow = ls.getLastRow();_x000D_
var ChtoNado = ls.getRange(1, KudaCol, lastRow, KudaCol); // the range with list, returned by a formula_x000D_
_x000D_
// ============================================================================= > loop >_x000D_
var CurrLevelBase = CurrentLevel; // remember the first current level_x000D_
_x000D_
_x000D_
_x000D_
for (var j = 1; j <= RowNum; j++) // [01] loop rows start_x000D_
{ _x000D_
// refresh first val _x000D_
var currentRow = br.getCell(j, 1).getRow(); _x000D_
loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrLevelBase, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} // [01] loop rows end_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getColumnsOffset_(offsets, lefColumn)_x000D_
{_x000D_
// Columns for all levels_x000D_
var columnsLevels = [];_x000D_
var totalOffset = 0; _x000D_
for (var i = 0, l = offsets.length; i < l; i++)_x000D_
{ _x000D_
totalOffset += offsets[i];_x000D_
columnsLevels.push(totalOffset + lefColumn - 1);_x000D_
} _x000D_
_x000D_
return columnsLevels;_x000D_
_x000D_
}_x000D_
_x000D_
function test_getCurrentLevel()_x000D_
{_x000D_
var br = SpreadsheetApp.getActive().getActiveSheet().getRange('A5:C5');_x000D_
var scol = 1;_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/_x000D_
Logger.log(getCurrentLevel_(1, br, scol, [1,2,3])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxx| |xxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(2, br, scol, [1,3,5])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxxxxxxxx| _x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,5,6])); // 2_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxx| |xxxxx| _x000D_
levels 1 2 3_x000D_
level 3_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,8])); // 3_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 4 (error)_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,3]));_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels _x000D_
level 1 (error) _x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [5,6,7])); // 1 _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getCurrentLevel_(ColNum, br, scol, columnsLevels)_x000D_
{_x000D_
var colPlus = 2; // const_x000D_
if (ColNum === 1) { return columnsLevels.indexOf(scol) + colPlus; }_x000D_
var CurrentLevel = -1;_x000D_
var level = 0;_x000D_
var column = 0;_x000D_
for (var i = 0; i < ColNum; i++ )_x000D_
{_x000D_
column = br.offset(0, i).getColumn();_x000D_
level = columnsLevels.indexOf(column) + colPlus;_x000D_
if (level > CurrentLevel) { CurrentLevel = level; }_x000D_
}_x000D_
return CurrentLevel;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
for (var k = 1; k <= X; k++)_x000D_
{ _x000D_
HeadLevel = HeadLevel + k - 1; _x000D_
CurrentLevel = CurrLevelBase + k - 1;_x000D_
var r = ts.getRange(currentRow, columnsLevels[CurrentLevel - 2]);_x000D_
var SearchText = r.getValue(); // searched text _x000D_
X = loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} _x000D_
}_x000D_
_x000D_
_x000D_
function loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
_x000D_
_x000D_
// if nothing is chosen!_x000D_
if (SearchText === '') // condition value =''_x000D_
{_x000D_
// kill extra data validation if there were _x000D_
// columns on the right_x000D_
if (CurrentLevel <= NumOfLevels) _x000D_
{_x000D_
for (var f = 0; f < X; f++) _x000D_
{_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel + f - 1]); _x000D_
// clean & get rid of validation_x000D_
cell.clear({contentsOnly: true}); _x000D_
cell.clear({validationsOnly: true});_x000D_
// exit columns loop _x000D_
}_x000D_
}_x000D_
return 0; // end loop this row _x000D_
}_x000D_
_x000D_
_x000D_
// formula for values_x000D_
var formula = getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts); _x000D_
KudaNado.setFormula(formula);_x000D_
_x000D_
_x000D_
// get response_x000D_
var Response = getResponse_(ChtoNado, lastRow, ReplaceCommas);_x000D_
var Variants = Response.length;_x000D_
_x000D_
_x000D_
// build data validation rule_x000D_
if (Variants === 0.0) // empty is found_x000D_
{_x000D_
return;_x000D_
} _x000D_
if(Variants >= 1.0) // if some variants were found_x000D_
{_x000D_
_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel - 1]);_x000D_
var rule = SpreadsheetApp_x000D_
.newDataValidation()_x000D_
.requireValueInList(Response, true)_x000D_
.setAllowInvalid(false)_x000D_
.build();_x000D_
// set validation rule_x000D_
cell.setDataValidation(rule);_x000D_
} _x000D_
if (Variants === 1.0) // // set the only value_x000D_
{ _x000D_
cell.setValue(Response[0]);_x000D_
SearchText = null;_x000D_
Response = null;_x000D_
return X; // continue doing DV_x000D_
} // the only value_x000D_
_x000D_
return 0; // end DV in this row_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts)_x000D_
{_x000D_
_x000D_
var checkVals = [];_x000D_
var Offs = CurrentLevel - 2;_x000D_
var values = [];_x000D_
// get values and display values for a formula_x000D_
for (var s = 0; s <= Offs; s++)_x000D_
{_x000D_
var checkR = ts.getRange(currentRow, columnsLevels[s]);_x000D_
values.push(checkR.getValue());_x000D_
} _x000D_
_x000D_
var LookCol = colName(CurrentLevel-1); // gets column name "A,B,C..."_x000D_
var formula = '=unique(filter(' + LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84_x000D_
_x000D_
var mathOpPlusVal = ''; _x000D_
var value = '';_x000D_
_x000D_
// loop levels for multiple conditions _x000D_
for (var i = 0; i < CurrentLevel - 1; i++) { _x000D_
formula += FormulaSplitter; // =unique(filter(A2:A84;_x000D_
LookCol = colName(i);_x000D_
_x000D_
value = values[i];_x000D_
_x000D_
mathOpPlusVal = getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas); // =unique(filter(A2:A84;B2:B84="Text"_x000D_
_x000D_
if ( Array.isArray(mathOpPlusVal) )_x000D_
{_x000D_
formula += mathOpPlusVal[0];_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;ROUND(B2:B84_x000D_
formula += mathOpPlusVal[1];_x000D_
}_x000D_
else_x000D_
{_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;B2:B84_x000D_
formula += mathOpPlusVal;_x000D_
}_x000D_
_x000D_
_x000D_
} _x000D_
_x000D_
formula += "))"; //=unique(filter(A2:A84;B2:B84="Text"))_x000D_
_x000D_
return formula;_x000D_
}_x000D_
_x000D_
_x000D_
function getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas)_x000D_
{_x000D_
var result = '';_x000D_
var splinter = ''; _x000D_
_x000D_
var type = typeof value;_x000D_
_x000D_
_x000D_
// strings_x000D_
if (type === 'string') return '="' + value + '"';_x000D_
// date_x000D_
if(value instanceof Date)_x000D_
{_x000D_
return ['ROUND(', FormulaSplitter +'5)=ROUND(DATE(' + value.getFullYear() + FormulaSplitter + (value.getMonth() + 1) + FormulaSplitter + value.getDate() + ')' + '+' _x000D_
+ 'TIME(' + value.getHours() + FormulaSplitter + value.getMinutes() + FormulaSplitter + value.getSeconds() + ')' + FormulaSplitter + '5)']; _x000D_
} _x000D_
// numbers_x000D_
if (type === 'number')_x000D_
{_x000D_
if (ReplaceCommas)_x000D_
{_x000D_
return '+0=' + value.toString().replace('.', ','); _x000D_
}_x000D_
else_x000D_
{_x000D_
return '+0=' + value;_x000D_
}_x000D_
}_x000D_
// booleans_x000D_
if (type === 'boolean')_x000D_
{_x000D_
return '=' + value;_x000D_
} _x000D_
// other_x000D_
return '=' + value;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getResponse_(allRange, l, ReplaceCommas)_x000D_
{_x000D_
var data = allRange.getValues();_x000D_
var data_ = allRange.getDisplayValues();_x000D_
_x000D_
var response = [];_x000D_
var val = '';_x000D_
for (var i = 0; i < l; i++)_x000D_
{_x000D_
val = data[i][0];_x000D_
if (val !== '') _x000D_
{_x000D_
var type = typeof val;_x000D_
if (type === 'boolean' || val instanceof Date) val = String(data_[i][0]);_x000D_
if (type === 'number' && ReplaceCommas) val = val.toString().replace('.', ',')_x000D_
response.push(val); _x000D_
}_x000D_
}_x000D_
_x000D_
return response; _x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function colName(n) {_x000D_
var ordA = 'a'.charCodeAt(0);_x000D_
var ordZ = 'z'.charCodeAt(0);_x000D_
_x000D_
var len = ordZ - ordA + 1;_x000D_
_x000D_
var s = "";_x000D_
while(n >= 0) {_x000D_
s = String.fromCharCode(n % len + ordA) + s;_x000D_
n = Math.floor(n / len) - 1;_x000D_
}_x000D_
return s; _x000D_
}_x000D_
_x000D_
_x000D_
function getDecimalMarkIsCommaLocals() {_x000D_
_x000D_
_x000D_
// list of Locals Decimal mark = comma_x000D_
var LANGUAGE_BY_LOCALE = {_x000D_
af_NA: "Afrikaans (Namibia)",_x000D_
af_ZA: "Afrikaans (South Africa)",_x000D_
af: "Afrikaans",_x000D_
sq_AL: "Albanian (Albania)",_x000D_
sq: "Albanian",_x000D_
ar_DZ: "Arabic (Algeria)",_x000D_
ar_BH: "Arabic (Bahrain)",_x000D_
ar_EG: "Arabic (Egypt)",_x000D_
ar_IQ: "Arabic (Iraq)",_x000D_
ar_JO: "Arabic (Jordan)",_x000D_
ar_KW: "Arabic (Kuwait)",_x000D_
ar_LB: "Arabic (Lebanon)",_x000D_
ar_LY: "Arabic (Libya)",_x000D_
ar_MA: "Arabic (Morocco)",_x000D_
ar_OM: "Arabic (Oman)",_x000D_
ar_QA: "Arabic (Qatar)",_x000D_
ar_SA: "Arabic (Saudi Arabia)",_x000D_
ar_SD: "Arabic (Sudan)",_x000D_
ar_SY: "Arabic (Syria)",_x000D_
ar_TN: "Arabic (Tunisia)",_x000D_
ar_AE: "Arabic (United Arab Emirates)",_x000D_
ar_YE: "Arabic (Yemen)",_x000D_
ar: "Arabic",_x000D_
hy_AM: "Armenian (Armenia)",_x000D_
hy: "Armenian",_x000D_
eu_ES: "Basque (Spain)",_x000D_
eu: "Basque",_x000D_
be_BY: "Belarusian (Belarus)",_x000D_
be: "Belarusian",_x000D_
bg_BG: "Bulgarian (Bulgaria)",_x000D_
bg: "Bulgarian",_x000D_
ca_ES: "Catalan (Spain)",_x000D_
ca: "Catalan",_x000D_
tzm_Latn: "Central Morocco Tamazight (Latin)",_x000D_
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",_x000D_
tzm: "Central Morocco Tamazight",_x000D_
da_DK: "Danish (Denmark)",_x000D_
da: "Danish",_x000D_
nl_BE: "Dutch (Belgium)",_x000D_
nl_NL: "Dutch (Netherlands)",_x000D_
nl: "Dutch",_x000D_
et_EE: "Estonian (Estonia)",_x000D_
et: "Estonian",_x000D_
fi_FI: "Finnish (Finland)",_x000D_
fi: "Finnish",_x000D_
fr_BE: "French (Belgium)",_x000D_
fr_BJ: "French (Benin)",_x000D_
fr_BF: "French (Burkina Faso)",_x000D_
fr_BI: "French (Burundi)",_x000D_
fr_CM: "French (Cameroon)",_x000D_
fr_CA: "French (Canada)",_x000D_
fr_CF: "French (Central African Republic)",_x000D_
fr_TD: "French (Chad)",_x000D_
fr_KM: "French (Comoros)",_x000D_
fr_CG: "French (Congo - Brazzaville)",_x000D_
fr_CD: "French (Congo - Kinshasa)",_x000D_
fr_CI: "French (Côte d’Ivoire)",_x000D_
fr_DJ: "French (Djibouti)",_x000D_
fr_GQ: "French (Equatorial Guinea)",_x000D_
fr_FR: "French (France)",_x000D_
fr_GA: "French (Gabon)",_x000D_
fr_GP: "French (Guadeloupe)",_x000D_
fr_GN: "French (Guinea)",_x000D_
fr_LU: "French (Luxembourg)",_x000D_
fr_MG: "French (Madagascar)",_x000D_
fr_ML: "French (Mali)",_x000D_
fr_MQ: "French (Martinique)",_x000D_
fr_MC: "French (Monaco)",_x000D_
fr_NE: "French (Niger)",_x000D_
fr_RW: "French (Rwanda)",_x000D_
fr_RE: "French (Réunion)",_x000D_
fr_BL: "French (Saint Barthélemy)",_x000D_
fr_MF: "French (Saint Martin)",_x000D_
fr_SN: "French (Senegal)",_x000D_
fr_CH: "French (Switzerland)",_x000D_
fr_TG: "French (Togo)",_x000D_
fr: "French",_x000D_
gl_ES: "Galician (Spain)",_x000D_
gl: "Galician",_x000D_
ka_GE: "Georgian (Georgia)",_x000D_
ka: "Georgian",_x000D_
de_AT: "German (Austria)",_x000D_
de_BE: "German (Belgium)",_x000D_
de_DE: "German (Germany)",_x000D_
de_LI: "German (Liechtenstein)",_x000D_
de_LU: "German (Luxembourg)",_x000D_
de_CH: "German (Switzerland)",_x000D_
de: "German",_x000D_
el_CY: "Greek (Cyprus)",_x000D_
el_GR: "Greek (Greece)",_x000D_
el: "Greek",_x000D_
hu_HU: "Hungarian (Hungary)",_x000D_
hu: "Hungarian",_x000D_
is_IS: "Icelandic (Iceland)",_x000D_
is: "Icelandic",_x000D_
id_ID: "Indonesian (Indonesia)",_x000D_
id: "Indonesian",_x000D_
it_IT: "Italian (Italy)",_x000D_
it_CH: "Italian (Switzerland)",_x000D_
it: "Italian",_x000D_
kab_DZ: "Kabyle (Algeria)",_x000D_
kab: "Kabyle",_x000D_
kl_GL: "Kalaallisut (Greenland)",_x000D_
kl: "Kalaallisut",_x000D_
lv_LV: "Latvian (Latvia)",_x000D_
lv: "Latvian",_x000D_
lt_LT: "Lithuanian (Lithuania)",_x000D_
lt: "Lithuanian",_x000D_
mk_MK: "Macedonian (Macedonia)",_x000D_
mk: "Macedonian",_x000D_
naq_NA: "Nama (Namibia)",_x000D_
naq: "Nama",_x000D_
pl_PL: "Polish (Poland)",_x000D_
pl: "Polish",_x000D_
pt_BR: "Portuguese (Brazil)",_x000D_
pt_GW: "Portuguese (Guinea-Bissau)",_x000D_
pt_MZ: "Portuguese (Mozambique)",_x000D_
pt_PT: "Portuguese (Portugal)",_x000D_
pt: "Portuguese",_x000D_
ro_MD: "Romanian (Moldova)",_x000D_
ro_RO: "Romanian (Romania)",_x000D_
ro: "Romanian",_x000D_
ru_MD: "Russian (Moldova)",_x000D_
ru_RU: "Russian (Russia)",_x000D_
ru_UA: "Russian (Ukraine)",_x000D_
ru: "Russian",_x000D_
seh_MZ: "Sena (Mozambique)",_x000D_
seh: "Sena",_x000D_
sk_SK: "Slovak (Slovakia)",_x000D_
sk: "Slovak",_x000D_
sl_SI: "Slovenian (Slovenia)",_x000D_
sl: "Slovenian",_x000D_
es_AR: "Spanish (Argentina)",_x000D_
es_BO: "Spanish (Bolivia)",_x000D_
es_CL: "Spanish (Chile)",_x000D_
es_CO: "Spanish (Colombia)",_x000D_
es_CR: "Spanish (Costa Rica)",_x000D_
es_DO: "Spanish (Dominican Republic)",_x000D_
es_EC: "Spanish (Ecuador)",_x000D_
es_SV: "Spanish (El Salvador)",_x000D_
es_GQ: "Spanish (Equatorial Guinea)",_x000D_
es_GT: "Spanish (Guatemala)",_x000D_
es_HN: "Spanish (Honduras)",_x000D_
es_419: "Spanish (Latin America)",_x000D_
es_MX: "Spanish (Mexico)",_x000D_
es_NI: "Spanish (Nicaragua)",_x000D_
es_PA: "Spanish (Panama)",_x000D_
es_PY: "Spanish (Paraguay)",_x000D_
es_PE: "Spanish (Peru)",_x000D_
es_PR: "Spanish (Puerto Rico)",_x000D_
es_ES: "Spanish (Spain)",_x000D_
es_US: "Spanish (United States)",_x000D_
es_UY: "Spanish (Uruguay)",_x000D_
es_VE: "Spanish (Venezuela)",_x000D_
es: "Spanish",_x000D_
sv_FI: "Swedish (Finland)",_x000D_
sv_SE: "Swedish (Sweden)",_x000D_
sv: "Swedish",_x000D_
tr_TR: "Turkish (Turkey)",_x000D_
tr: "Turkish",_x000D_
uk_UA: "Ukrainian (Ukraine)",_x000D_
uk: "Ukrainian",_x000D_
vi_VN: "Vietnamese (Vietnam)",_x000D_
vi: "Vietnamese"_x000D_
}_x000D_
_x000D_
_x000D_
var SS = SpreadsheetApp.getActiveSpreadsheet();_x000D_
var LocalS = SS.getSpreadsheetLocale();_x000D_
_x000D_
_x000D_
if (LANGUAGE_BY_LOCALE[LocalS] == undefined) {_x000D_
return false;_x000D_
_x000D_
}_x000D_
//Logger.log(true);_x000D_
return true;_x000D_
}_x000D_
_x000D_
/*_x000D_
function ReplaceDotsToCommas(dataIn) {_x000D_
var dataOut = dataIn.map(function(num) {_x000D_
if (isNaN(num)) {_x000D_
return num;_x000D_
} _x000D_
num = num.toString();_x000D_
return num.replace(".", ",");_x000D_
});_x000D_
return dataOut;_x000D_
}_x000D_
*/
_x000D_
Here's set of variables that are to be changed, you'll find them in script:
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data2'; // name of sheet with data
var NumOfLevels = 7; // number of levels of data validation
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,1,1,1,1]; // offsets for levels
I suggest everyone, who knows scripts well, send your edits to this code. I guess, there's simpler way to find validation list and make script run faster.
**@page {
margin-top:21% !important;
@top-left{
content: element(header);
}
@bottom-left {
content: element(footer
}
div.header {
position: running(header);
}
div.footer {
position: running(footer);
border-bottom: 2px solid black;
}
.pagenumber:before {
content: counter(page);
}
.pagecount:before {
content: counter(pages);
}
<div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
<span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
</div >**
After a quick google:
__STDC__
and __STDC_VERSION__
, see here
There are several ways. One way is to use save()
to save the exact object. e.g. for data frame foo
:
save(foo,file="data.Rda")
Then load it with:
load("data.Rda")
You could also use write.table()
or something like that to save the table in plain text, or dput()
to obtain R code to reproduce the table.
$(function(){
$(window).resize(function(){
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
});
});
Scrollbars etc have an effect on the window size so you may want to tweak to desired size.
This is a cool function
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
Just use
$myarray = array_push_assoc($myarray, 'h', 'hello');
If you have installed .NET desktop development and still you can't see the templates, then VS is probably getting the templates from your custom templates folder and not installed.
To fix that, copy the installed templates folder to custom.
This is your "installed" folder
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ProjectTemplates
This is your "custom" folder
C:\Users[your username]\Documents\Visual Studio\2017\Templates\ProjectTemplates
Typically this happens when you are at the office and you are running VS as an administrator and visual studio is confused how to merge both of them and if you notice they don't have the same folder structure and folder names.. One is CSHARP and the other C#....
I didn't have the same problem when I installed VS 2017 community edition at home though. This happened when I installed visual studio 2017 "enterprise" edition.
Don't use multiple parameters in the function name just go with simple few args convention that will increase the readability of codes, for this you can do like -
// MultipartBody.Part.createFormData("partName", data)
Call<SomReponse> methodName(@Part MultiPartBody.Part part);
// RequestBody.create(MediaType.get("text/plain"), data)
Call<SomReponse> methodName(@Part(value = "partName") RequestBody part);
/* for single use or you can use by Part name with Request body */
// add multiple list of part as abstraction |ease of readability|
Call<SomReponse> methodName(@Part List<MultiPartBody.Part> parts);
Call<SomReponse> methodName(@PartMap Map<String, RequestBody> parts);
// this way you will save the abstraction of multiple parts.
There can be multiple exceptions that you may encounter while using Retrofit, all of the exceptions documented as code, have a walkthrough to retrofit2/RequestFactory.java
. you can able to two functions parseParameterAnnotation
and parseMethodAnnotation
where you can able to exception thrown, please go through this, it will save your much of time than googling/stackoverflow
I wrote and released a small Nuget Package which can be used to print a PDF file to a printerdriver. It can also print to a XPS file or PDF file. Here is a link to it.
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
If you need good, easy GIT server than you must try GitBlit. Also i use gitolite but it only server, with GitBlit you get all in one, server, admin, repos. manager ... URL: http://gitblit.com/
You can append the text to $0
in awk if it matches the condition:
awk '/^all:/ {$0=$0" anotherthing"} 1' file
/patt/ {...}
if the line matches the pattern given by patt
, then perform the actions described within {}
./^all:/ {$0=$0" anotherthing"}
if the line starts (represented by ^
) with all:
, then append anotherthing
to the line.1
as a true condition, triggers the default action of awk
: print the current line (print $0
). This will happen always, so it will either print the original line or the modified one.For your given input it returns:
somestuff...
all: thing otherthing anotherthing
some other stuff
Note you could also provide the text to append in a variable:
$ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file
somestuff...
all: thing otherthing EXTRA TEXT
some other stuff
Update maven version to 3.6.3 and run
mvn -Dhttps.protocols=TLSv1.2 install
it worked on centos 6.9
It prevents the browser from doing MIME-type sniffing. Most browsers are now respecting this header, including Chrome/Chromium, Edge, IE >= 8.0, Firefox >= 50 and Opera >= 13. See :
Sending the new X-Content-Type-Options response header with the value nosniff will prevent Internet Explorer from MIME-sniffing a response away from the declared content-type.
EDIT:
Oh and, that's an HTTP header, not a HTML meta tag option.
See also : http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx
The del statement is what you're looking for. If you have a dictionary named foo with a key called 'bar', you can delete 'bar' from foo like this:
del foo['bar']
Note that this permanently modifies the dictionary being operated on. If you want to keep the original dictionary, you'll have to create a copy beforehand:
>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}
The dict
call makes a shallow copy. If you want a deep copy, use copy.deepcopy
.
Here's a method you can copy & paste, for your convenience:
def minus_key(key, dictionary):
shallow_copy = dict(dictionary)
del shallow_copy[key]
return shallow_copy
*Make sure you update your linux box first
yum update
In case someone still has this problem, this is a valid solution:
centos-release : rpm -q centos-release
Centos 6.*
wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm
Centos 5.*
wget http://ftp.jaist.ac.jp/pub/Linux/Fedora/epel/5/x86_64/epel-release-5-4.noarch.rpm
rpm -ivh epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
rpm -Uvh remi-release-5*.rpm
Then just do this to update:
yum --enablerepo=remi upgrade php-mbstring
Or this to install:
yum --enablerepo=remi install php-mbstring
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
Don't. Leave them as Java and use IKVM to convert them to .Net DLLs.
You have very little control over a browser's printing methods. At most you can SUGGEST, but if the browser's print settings have "don't print background images", there's nothing you can do without rewriting your page to turn the background images into floating "foreground" images that happen to be behind other content.
1NF: Only one value per column
2NF: All the non primary key columns in the table should depend on the entire primary key.
3NF: All the non primary key columns in the table should depend DIRECTLY on the entire primary key.
I have written an article in more detail over here
Here's my solution using only Graph API Explorer & Access Token Debugger:
(Tested with API Version 2.9-2.11, 3.0-3.1)
I know this is an old question but according what @mikejones1477 said, modern front end libraries and frameworks escape the text giving you protection against XSS. The reason why cookies are not a secure method using credentials is that cookies doesn't prevent CSRF when localStorage does (also remember that cookies are accessible by javascript too, so XSS isn't the big problem here), this answer resume why.
The reason storing an authentication token in local storage and manually adding it to each request protects against CSRF is that key word: manual. Since the browser is not automatically sending that auth token, if I visit evil.com and it manages to send a POST http://example.com/delete-my-account, it will not be able to send my authn token, so the request is ignored.
Of course httpOnly is the holy grail but you can't access from reactjs or any js framework beside you still have CSRF vulnerability. My recommendation would be localstorage or if you want to use cookies make sure implemeting some solution to your CSRF problem like django does.
Regarding with the CDN's make sure you're not using some weird CDN, for example CDN like google or bootstrap provide, are maintained by the community and doesn't contain malicious code, if you are not sure, you're free to review.
This works for me:
ln -s /usr/local/Cellar/mysql/5.6.22/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
I use
Response.Redirect(Page.Request.Path);
If you have to check for the Request.Params when the page is refresh use below. This will not rewrite the Request.Params to the URL.
Response.Redirect(Page.Request.Path + "?Remove=1");
updateValue(data){
// retriving index from array
let indexValue = this.items.indexOf(data);
// changing specific element in array
this.items[indexValue].isShow = !this.items[indexValue].isShow;
}
It’s not a good practice to set http.sslVerify false. Instead we can use SSL certificate.
So, build agent will use https with SSL certificate and PAT for authentication.
Copy the content of cer file including –begin—and –end--.
git bash on build agent => git config –global http.sslcainfo “C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt” Go to this file and append the .cer content.
Thus, build agent can access the SSL certificate
Similar to @radiak's response, but with jQuery (see this API document and comment on how to change the selectedIndex
).
$('#mySelectParent').find("select").prop("selectedIndex",-1);
The benefits to this approach are:
#mySelectParent
in the example)You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
So, let's say you have this table:
CREATE TABLE YourTable(Col1 VARCHAR(10))
And you want to change Col1
to VARCHAR(20)
. What you need to do is this:
ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)
That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5)
, then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE
will fail.
How about simply (Please note, come up with a better name for the class name this is simply an example):
.centerText{
text-align: center;
}
<div>
<table style="width:100%">
<tbody>
<tr>
<td class="centerText">Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td class="centerText">Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
Example here
You can place the css
in a separate file, which is recommended.
In my example, I created a file called styles.css
and placed my css
rules in it.
Then include it in the html document in the <head>
section as follows:
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
The alternative, not creating a seperate css file, not recommended at all...
Create <style>
block in your <head>
in the html document. Then just place your rules there.
<head>
<style type="text/css">
.centerText{
text-align: center;
}
</style>
</head>
Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.
Server side Comments:
Razor .cshtml
@* Comment goes here *@
.aspx
For those looking for the older .aspx
view (and Asp.Net WebForms) server side comment syntax:
<%-- Comment goes here --%>
Client Side Comments
HTML Comment
<!-- Comment goes here -->
Javascript Comment
// One line Comment goes Here
/* Multiline comment
goes here */
As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).
First things first, if the date property is storing a date, store it using a DateTime. If you parse the date through the sort you have to parse it for each item being compared, that's not very efficient...
You can then make an IComparer:
public class TagComparer : IComparer<cTag>
{
public int Compare(cTag first, cTag second)
{
if (first != null && second != null)
{
// We can compare both properties.
return first.date.CompareTo(second.date);
}
if (first == null && second == null)
{
// We can't compare any properties, so they are essentially equal.
return 0;
}
if (first != null)
{
// Only the first instance is not null, so prefer that.
return -1;
}
// Only the second instance is not null, so prefer that.
return 1;
}
}
var list = new List<cTag>();
// populate list.
list.Sort(new TagComparer());
You can even do it as a delegate:
list.Sort((first, second) =>
{
if (first != null && second != null)
return first.date.CompareTo(second.date);
if (first == null && second == null)
return 0;
if (first != null)
return -1;
return 1;
});
Factory classes are useful for when the object type that they return has a private constructor, when different factory classes set different properties on the returning object, or when a specific factory type is coupled with its returning concrete type.
WCF uses ServiceHostFactory classes to retrieve ServiceHost objects in different situations. The standard ServiceHostFactory is used by IIS to retrieve ServiceHost instances for .svc files, but a WebScriptServiceHostFactory is used for services that return serializations to JavaScript clients. ADO.NET Data Services has its own special DataServiceHostFactory and ASP.NET has its ApplicationServicesHostFactory since its services have private constructors.
If you only have one class that's consuming the factory, then you can just use a factory method within that class.
You could use a colormap such as HSV to generate a set of colors. For example:
cc=hsv(12);
figure;
hold on;
for i=1:12
plot([0 1],[0 i],'color',cc(i,:));
end
MATLAB has 13 different named colormaps ('doc colormap' lists them all).
Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.
If the above solution does not work for you, try this:
#1.1 Do NOT ignore file pattern in any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php
##########################
# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.
Use Arrays.sort
and then take the middle element (in case the number n
of elements in the array is odd) or take the average of the two middle elements (in case n
is even).
public static long median(long[] l)
{
Arrays.sort(l);
int middle = l.length / 2;
if (l.length % 2 == 0)
{
long left = l[middle - 1];
long right = l[middle];
return (left + right) / 2;
}
else
{
return l[middle];
}
}
Here are some examples:
@Test
public void evenTest()
{
long[] l = {
5, 6, 1, 3, 2
};
Assert.assertEquals((3 + 4) / 2, median(l));
}
@Test
public oddTest()
{
long[] l = {
5, 1, 3, 2, 4
};
Assert.assertEquals(3, median(l));
}
And in case your input is a Collection
, you might use Google Guava to do something like this:
public static long median(Collection<Long> numbers)
{
return median(Longs.toArray(numbers)); // requires import com.google.common.primitives.Longs;
}
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
Check this out, it might help you a bit in your understanding.
#program to find the prime factors of a given number
import sympy as smp
try:
number = int(input('Enter a number : '))
except(ValueError) :
print('Please enter an integer !')
num = number
prime_factors = []
if smp.isprime(number) :
prime_factors.append(number)
else :
for i in range(2, int(number/2) + 1) :
"""while figuring out prime factors of a given number, n
keep in mind that a number can itself be prime or if not,
then all its prime factors will be less than or equal to its int(n/2 + 1)"""
if smp.isprime(i) and number % i == 0 :
while(number % i == 0) :
prime_factors.append(i)
number = number / i
print('prime factors of ' + str(num) + ' - ')
for i in prime_factors :
print(i, end = ' ')
You could try:
#applyCSS .ui-bar-a {property:value}
#applyCSS .ui-bar-a .ui-link-inherit {property:value}
Etc, etc... Is that what you're looking for?
Your method should work fine on a Mac, but on Windows, two additional steps are necessary.
Saving the id_rsa key in this location should solve the permission error.
Another simple way (Bootstrap 4) to work with multiple dropdowns
$('.dropdown-item').on('click', function(){
var btnObj = $(this).parent().siblings('button');
$(btnObj).text($(this).text());
$(btnObj).val($(this).text());
});
I've accidentally found that DebugView (with enabled Capture > Capture Win32
option) will capture writes to System.Console
.
Example test:
[Test]
public void FooTest()
{
for (int i = 0; i < 5; i++)
Console.WriteLine($"[{DateTime.UtcNow.ToString("G")}] Hello World");
}
LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).
RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.
WebView : to load html, static or dynamic pages.
For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html
Nobody mentioned using reversed:
f=open(file,"r")
r=reversed(f.readlines())
last_line_of_file = r.next()
You could do:
var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));
This will return the matching dog, else it will return null
.
You can then set the property like follows:
if (matchingDog != null)
matchingDog.Name = "New Dog Name";
For me, the only way on SQL 2008 R2 was this :
EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE **WITH OVERRIDE**
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE **WITH OVERRIDE**
Both prior answers are definitely good solutions. If you're amenable to a library, I like moment.js - it does a lot more than just getting/formatting the date.
Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:
import msvcrt
def kbfunc():
x = msvcrt.kbhit()
if x:
ret = ord(msvcrt.getch())
else:
ret = 0
return ret
My Problem was solved
The problem occurs when you have the wrong/different team on MyProject and MyProjectTest.
Reconnecting your phone prior to rebuilding may also assist with fixing this issue.
The previous solutions have used the custom StructType.
With spark-sql 2.4.5 (scala version 2.12.10) it is now possible to specify the schema as a string using the schema
function
import org.apache.spark.sql.SparkSession;
val sparkSession = SparkSession.builder()
.appName("sample-app")
.master("local[2]")
.getOrCreate();
val pageCount = sparkSession.read
.format("csv")
.option("delimiter","|")
.option("quote","")
.schema("project string ,article string ,requests integer ,bytes_served long")
.load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")
It seems you have changed some permissions of the directory. I did the following steps to restore it.
$ git diff > backup-diff.txt ### in case you have some other code changes
$ git checkout .
By using nio in Java SE 7,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
If both exists
and notExists
return false, the existence of the file cannot be verified. (maybe no access right to this path)
You can check if path
is a directory or regular file.
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
Please check this Java SE 7 tutorial.
Generally, you could create a channel and receive a stop signal in the goroutine.
There two way to create channel in this example.
channel
context. In the example I will demo context.WithCancel
The first demo, use channel
:
package main
import "fmt"
import "time"
func do_stuff() int {
return 1
}
func main() {
ch := make(chan int, 100)
done := make(chan struct{})
go func() {
for {
select {
case ch <- do_stuff():
case <-done:
close(ch)
return
}
time.Sleep(100 * time.Millisecond)
}
}()
go func() {
time.Sleep(3 * time.Second)
done <- struct{}{}
}()
for i := range ch {
fmt.Println("receive value: ", i)
}
fmt.Println("finish")
}
The second demo, use context
:
package main
import (
"context"
"fmt"
"time"
)
func main() {
forever := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done(): // if cancel() execute
forever <- struct{}{}
return
default:
fmt.Println("for loop")
}
time.Sleep(500 * time.Millisecond)
}
}(ctx)
go func() {
time.Sleep(3 * time.Second)
cancel()
}()
<-forever
fmt.Println("finish")
}
this
refers to the current instance of the class (object) your equals-method belongs to. When you test this
against an object, the testing method (which is equals(Object obj)
in your case) will check wether or not the object is equal to the current instance (referred to as this
).
An example:
Object obj = this; this.equals(obj); //true Object obj = this; new Object().equals(obj); //false
Bad Programmers are Language-Agnostic
A really bad programmer can write bad code in almost any language.
The child can only take a height if the parent has one already set. See this exaple : Vertical Scrolling 100% height
html, body {
height: 100%;
margin: 0;
}
.header{
height: 10%;
background-color: #a8d6fe;
}
.middle {
background-color: #eba5a3;
min-height: 80%;
}
.footer {
height: 10%;
background-color: #faf2cc;
}
$(function() {_x000D_
$('a[href*="#nav-"]').click(function() {_x000D_
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {_x000D_
var target = $(this.hash);_x000D_
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');_x000D_
if (target.length) {_x000D_
$('html, body').animate({_x000D_
scrollTop: target.offset().top_x000D_
}, 500);_x000D_
return false;_x000D_
}_x000D_
}_x000D_
});_x000D_
});
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.header {_x000D_
height: 100%;_x000D_
background-color: #a8d6fe;_x000D_
}_x000D_
.middle {_x000D_
background-color: #eba5a3;_x000D_
min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
height: 100%;_x000D_
background-color: #faf2cc;_x000D_
}_x000D_
nav {_x000D_
position: fixed;_x000D_
top: 10px;_x000D_
left: 0px;_x000D_
}_x000D_
nav li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#nav-a">got to a</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#nav-b">got to b</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#nav-c">got to c</a>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>_x000D_
<div class="header" id="nav-a">_x000D_
_x000D_
</div>_x000D_
<div class="middle" id="nav-b">_x000D_
_x000D_
</div>_x000D_
<div class="footer" id="nav-c">_x000D_
_x000D_
</div>
_x000D_
This article from W3C tells you what they think you should do https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage
and has examples here http://mars.dequecloud.com/demo/ImgRole.htm
among which
<a href="http://www.facebook.com">
<span class="fb_logo" role="img" aria-label="Connect via Facebook">
</span>
</a>
Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:
<a href="http://www.facebook.com"><span class="fb_logo">
Connect via Facebook
</span></a>
.fb_logo {
height: 37px; width: 37px;
background-image: url('../gfx/logo-facebook.svg');
color:transparent; overflow:hidden; /* hide the text */
}
From my experience in SQL Server,I found one of the scenarios where CTE outperformed Temp table
I needed to use a DataSet(~100000) from a complex Query just ONCE in my stored Procedure.
Temp table was causing an overhead on SQL where my Procedure was performing slowly(as Temp Tables are real materialized tables that exist in tempdb and Persist for the life of my current procedure)
On the other hand, with CTE, CTE Persist only until the following query is run. So, CTE is a handy in-memory structure with limited Scope. CTEs don't use tempdb by default.
This is one scenario where CTEs can really help simplify your code and Outperform Temp Table. I had Used 2 CTEs, something like
WITH CTE1(ID, Name, Display)
AS (SELECT ID,Name,Display from Table1 where <Some Condition>),
CTE2(ID,Name,<col3>) AS (SELECT ID, Name,<> FROM CTE1 INNER JOIN Table2 <Some Condition>)
SELECT CTE2.ID,CTE2.<col3>
FROM CTE2
GO
Under Bash (at least), this can be done automatically with tab completion:
make
spacetabtab
How about creating an ArrayList of a set amount of Integers?
The below method returns an ArrayList of a set amount of Integers.
public static ArrayList<Integer> createRandomList(int sizeParameter)
{
// An ArrayList that method returns
ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
// Random Object helper
Random randomHelper = new Random();
for (int x = 0; x < sizeParameter; x++)
{
setIntegerList.add(randomHelper.nextInt());
} // End of the for loop
return setIntegerList;
}
Equivalent C# code which i used to implement same functionality and can even customize to accept N number of Taps
public interface IOnTouchInterface
{
void ViewTapped();
}
public class MultipleTouchGestureListener : Java.Lang.Object, View.IOnTouchListener
{
int clickCount = 0;
long startTime;
static long MAX_DURATION = 500;
public int NumberOfTaps { get; set; } = 7;
readonly IOnTouchInterface interfc;
public MultipleTouchGestureListener(IOnTouchInterface tch)
{
this.interfc = tch;
}
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
clickCount++;
if(clickCount == 1)
startTime = Utility.CurrentTimeSince1970;
break;
case MotionEventActions.Up:
var currentTime = Utility.CurrentTimeSince1970;
long time = currentTime - startTime;
if(time <= MAX_DURATION * NumberOfTaps)
{
if (clickCount == NumberOfTaps)
{
this.interfc.ViewTapped();
clickCount = 0;
}
}
else
{
clickCount = 0;
}
break;
}
return true;
}
}
public static class Utility
{
public static long CurrentTimeSince1970
{
get
{
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
DateTime dtNow = DateTime.Now;
TimeSpan result = dtNow.Subtract(dt);
long seconds = (long)result.TotalMilliseconds;
return seconds;
}
}
}
Currently Above code accepts 7 as number of taps before it raises the View Tapped event. But it can be customized with any number
Debug.WriteLine() can be used as well.
They are terms from two different domains: 'port' is a concept from TCP/IP networking, 'socket' is an API (programming) thing. A 'socket' is made (in code) by taking a port and a hostname or network adapter and combining them into a data structure that you can use to send or receive data.
After two dozens of comments to understand the situation, it was found that the libhdf5.so.7
was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.
For future reference: other than checking LD_LIBRARY_PATH
, it's always a good idea to check a library with nm -D
to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum
revealed that the files were actually different.
numpy 1D array --> column/row matrix:
>>> a=np.array([1,2,4])
>>> a[:, None] # col
array([[1],
[2],
[4]])
>>> a[None, :] # row, or faster `a[None]`
array([[1, 2, 4]])
And as @joe-kington said, you can replace None
with np.newaxis
for readability.
toString() is a debug info string. The default implementation returns the class name and the system identity hash. Collections return all elements but arrays not.
Also be aware of NullPointerException
creating the log!
In this case a Arrays.toString()
may help:
Object temp = data.getParameterValue("request");
String log = temp == null ? "null" : (temp.getClass().isArray() ? Arrays.toString((Object[])temp) : temp.toString());
log.info("end " + temp);
You can also use Arrays.asList()
:
Object temp = data.getParameterValue("request");
Object log = temp == null ? null : (temp.getClass().isArray() ? Arrays.asList((Object[])temp) : temp);
log.info("end " + temp);
This may result in a ClassCastException
for primitive arrays (int[]
, ...).
You must create two key hashes, one for Debug and one for Release.
For the Debug key hash:
On OS X, run:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
On Windows, run:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl
base64
For the Release key hash:
On OS X, run (replace what is between <>
with your values):
keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64
On Windows, use (replace what is between <>
with your values):
keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64
Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!
Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278
Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
Dim rw As Long, ref
With ThisWorkbook.Sheets(1)
.Cells.Clear
rw = 1
.Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
For Each ref In ThisWorkbook.VBProject.References
rw = rw + 1
.Range("A" & rw & ":D" & rw) = Array(ref.Description, _
"v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
Next ref
.Range("A:D").Columns.AutoFit
End With
End Sub
Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.
Sub ListReferencePaths()
'Macro purpose: To determine full path and Globally Unique Identifier (GUID)
'to each referenced library. Select the reference in the Tools\References
'window, then run this code to get the information on the reference's library
On Error Resume Next
Dim i As Long
Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID"
For i = 1 To ThisWorkbook.VBProject.References.Count
With ThisWorkbook.VBProject.References(i)
Debug.Print .Name & " | " & .FullPath & " | " & .GUID
End With
Next i
On Error GoTo 0
End Sub
I had the same error after I posted a form of mine. I simply missed the opening quote in one of my input name attributes. I had:
<input name=first_name">
Fixing that got rid of the error.
For people looking this up now:
It seems that now setting the User-Agent
header is allowed since Firefox 43. See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name for the current list of forbidden headers.
I don't find any of the answers here useful, so I am providing my solution.
The problem is that you are using multipart/related
as the content type which is not good in this case. I am using multipart/mixed
and inside it multipart/alternative
(it works on most clients).
The message structure should be as follows:
[Headers]
Content-type:multipart/mixed; boundary="boundary1"
--boundary1
Content-type:multipart/alternative; boundary="boundary2"
--boundary2
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit
[HTML code with a href="cid:..."]
--boundary2
Content-Type: image/png;
name="moz-screenshot.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.06090408.01060107>
Content-Disposition: inline; filename="moz-screenshot.png"
[base64 image data here]
--boundary2--
--boundary1--
Then it will work
Feedback Guys, first create database example live; before execute sql file below.
sqlcmd -U SA -P yourPassword -S YourHost -d live -i live.sql
Dim
is short for Dimension and is used in VBA and VB6 to declare local variables.
Set on the other hand, has nothing to do with variable declarations. The Set
keyword is used to assign an object variable to a new object.
Hope that clarifies the difference for you.
You can use:
input[type=text]
{
/*Styles*/
}
Define your common style attributes inside this. and for extra style you can add a class then.
c
can be used on lists (and not only on vectors):
# you have
l1 = list(2, 3)
l2 = list(4)
# you want
list(2, 3, 4)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
# you can do
c(l1, l2)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
If you have a list of lists, you can do it (perhaps) more comfortably with do.call
, eg:
do.call(c, list(l1, l2))
Follow all the steps.
Step 1: initialize git
$ git init
Step 2: Check files are exist or not.
$git ls
Step 3 : Add the file
$git add filename
Step 4: Add comment to show
$git commit -m "your comment"
Step 5: Link to your repository
$git remote add origin "copy repository link and paste here"
Step 6: Push on Git
$ git push -u origin master
Can you test with surefire 2.6 and either configure Surefire with <testFailureIgnore>true</testFailureIgnore>
.
Or on the command line:
mvn install -Dmaven.test.failure.ignore=true
Simple Example:
videoSource=test.mp4
videoEncoded=test2.mp4
videoSubtitle=test.srt
videoFontSize=24
ffmpeg -i "$videoSource" -vf subtitles="$videoSubtitle":force_style='Fontsize="$videoFontSize"' "$videoEncoded"
Only replace the linux variables
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
thanks kkudi! I was able to adapt your answer to work for an activity... here's what worked in my app..
public boolean isServiceRunning() {
ActivityManager activityManager = (ActivityManager)Monitor.this.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
isServiceFound = false;
for (int i = 0; i < services.size(); i++) {
if (services.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.lyo.AutoMessage/com.lyo.AutoMessage.TextLogList}")) {
isServiceFound = true;
}
}
return isServiceFound;
}
this example will give you a true or false if the topActivity matches what the user is doing. So if the activity your checking for is not being displayed (i.e. is onPause) then you won't get a match. Also, to do this you need to add the permission to your manifest..
<uses-permission android:name="android.permission.GET_TASKS"/>
I hope this was helpful!
All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.
[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
--lang en-US
--layout ".\Visual Studio Cummunity 2017"
--add Microsoft.VisualStudio.Workload.NativeDesktop
--includeRecommended
I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).
The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.
"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.
Watch out for the parentheses. As has been pointed out above, in Python 3, assert
is still a statement, so by analogy with print(..)
, one may extrapolate the same to assert(..)
or raise(..)
but you shouldn't.
This is important because:
assert(2 + 2 == 5, "Houston we've got a problem")
won't work, unlike
assert 2 + 2 == 5, "Houston we've got a problem"
The reason the first one will not work is that bool( (False, "Houston we've got a problem") )
evaluates to True
.
In the statement assert(False)
, these are just redundant parentheses around False
, which evaluate to their contents. But with assert(False,)
the parentheses are now a tuple, and a non-empty tuple evaluates to True
in a boolean context.
You have to placed this code in application.rb
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}
Do not forget to request permissions:
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
android.Manifest.permission.READ_EXTERNAL_STORAGE
Add in AndroidManifest.xml the provider and permission:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
Create XML file provider res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Use below example code:
public class InstallManagerApk extends AppCompatActivity {
static final String NAME_APK_FILE = "some.apk";
public static final int REQUEST_INSTALL = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// required permission:
// android.Manifest.permission.WRITE_EXTERNAL_STORAGE
// android.Manifest.permission.READ_EXTERNAL_STORAGE
installApk();
}
...
/**
* Install APK File
*/
private void installApk() {
try {
File filePath = Environment.getExternalStorageDirectory();// path to file apk
File file = new File(filePath, LoadManagerApkFile.NAME_APK_FILE);
Uri uri = getApkUri( file.getPath() ); // get Uri for each SDK Android
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData( uri );
intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK );
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, getApplicationInfo().packageName);
if ( getPackageManager().queryIntentActivities(intent, 0 ) != null ) {// checked on start Activity
startActivityForResult(intent, REQUEST_INSTALL);
} else {
throw new Exception("don`t start Activity.");
}
} catch ( Exception e ) {
Log.i(TAG + ":InstallApk", "Failed installl APK file", e);
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
/**
* Returns a Uri pointing to the APK to install.
*/
private Uri getApkUri(String path) {
// Before N, a MODE_WORLD_READABLE file could be passed via the ACTION_INSTALL_PACKAGE
// Intent. Since N, MODE_WORLD_READABLE files are forbidden, and a FileProvider is
// recommended.
boolean useFileProvider = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
String tempFilename = "tmp.apk";
byte[] buffer = new byte[16384];
int fileMode = useFileProvider ? Context.MODE_PRIVATE : Context.MODE_WORLD_READABLE;
try (InputStream is = new FileInputStream(new File(path));
FileOutputStream fout = openFileOutput(tempFilename, fileMode)) {
int n;
while ((n = is.read(buffer)) >= 0) {
fout.write(buffer, 0, n);
}
} catch (IOException e) {
Log.i(TAG + ":getApkUri", "Failed to write temporary APK file", e);
}
if (useFileProvider) {
File toInstall = new File(this.getFilesDir(), tempFilename);
return FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, toInstall);
} else {
return Uri.fromFile(getFileStreamPath(tempFilename));
}
}
/**
* Listener event on installation APK file
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_INSTALL) {
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this,"Install succeeded!", Toast.LENGTH_SHORT).show();
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this,"Install canceled!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Install Failed!", Toast.LENGTH_SHORT).show();
}
}
}
...
}
If you wish to invoke a method if some boolean is true, you can put else None
to terminate the trinary.
>>> a=1
>>> print(a) if a==1 else None
1
>>> print(a) if a==2 else None
>>> a=2
>>> print(a) if a==2 else None
2
>>> print(a) if a==1 else None
>>>
Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL
1) Enter MySQL
mysql -u your_user -p
2) Let's see the list of locked tables
mysql> show open tables where in_use>0;
3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;
4) Let's kill one of these processes
mysql> kill put_process_id_here;
You can use the following to send an HTTP-POST
request to a URL
and receive the response. I always use this:
try {
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
String u = "B2mGaME";
String au = "gamewrapperB2M";
// String mob = "880xxxxxxxxxx";
params.put("usr", u.toString());
params.put("aut", au.toString());
params.put("uph", MobileNo.toString());
// params.put("uph", mob.toString());
client.post("http://196.6.13.01:88/ws/game_wrapper_reg_check.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
playStatus = response;
//////Get your Response/////
Log.i(getClass().getSimpleName(), "Response SP Status. " + playStatus);
}
@Override
public void onFailure(Throwable throwable) {
super.onFailure(throwable);
}
});
} catch (Exception e) {
e.printStackTrace();
}
You Also need to Add bellow Jar file in libs folder
android-async-http-1.3.1.jar
Finally, I have edit your build.gradle:
dependencies {
compile files('libs/<android-async-http-1.3.1.jar>')
}
In the last Rebuild your project.
I also faced similar issues when tried to do ng serve. I was able to resolve it as below.
Note:
C:\Windows\system32> is on windows command prompt
C:\apps\workspace\testProj> is on VS code Terminal (can also be doable in another command prompt)
Following are the steps which I used to resolve this.
Step1. Verify the cli version installed on command prompt (will be Angular CLI global version)
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
If cli was installed earlier, it shows the global cli version.
If cli was not installed, we may get the error
ng is not recognized as an internal or external command
a. (Optional Step) Install Angular CLI global version
C:\Windows\system32>npm install -g @angular/cli
C:\Windows\system32>npm install -g @angular-cli/latest
b. Check version again
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
Step2. Verify the local cli version installed on your angular project(VS code ide or command prompt cd'd to your project project)
C:\apps\workspace\testProj>ng --version
Angular CLI: 7.3.8
Note: Clearly versions are not in sync. Do the following in your angular project
C:\apps\workspace\testProj>ng update @angular/cli -> important to sync with global cli version
Note: If upgrade donot work using above command (ref: How to upgrade Angular CLI to the latest version)
On command prompt, uninstall global angular cli, clean the cache and reinstall the cli
C:\Windows\system32>npm uninstall -g angular-cli
C:\Windows\system32>npm cache clean or npm cache verify #(if npm > 5)
C:\Windows\system32>npm install -g @angular/cli@latest
Now update your local project version, because cli version of your local project is having higher priority than global one when you try to execute your project.
C:\apps\workspace\testProj>rm -rf node_modules
C:\apps\workspace\testProj>npm uninstall --save-dev angular-cli
C:\apps\workspace\testProj>npm install --save-dev @angular/cli@latest
C:\apps\workspace\testProj>npm install
C:\apps\workspace\testProj>ng update @angular/cli
Step3. Verify if local project cli version now in sync with global one
C:\Windows\system32>ng --version
Angular CLI: 8.3.13
C:\apps\workspace\testProj>ng --version
Angular CLI: 8.3.13
Step4.. Revalidate on the project
C:\apps\workspace\testProj>ng serve
Should work now
Early versions of unix measured system time in 1/60 s intervals. This meant that a 32-bit unsigned integer could only represent a span of time less than 829 days. For this reason, the time represented by the number 0
(called the epoch) had to be set in the very recent past. As this was in the early 1970s, the epoch was set to 1971-1-1.
Later, the system time was changed to increment every second, which increased the span of time that could be represented by a 32-bit unsigned integer to around 136 years. As it was no longer so important to squeeze every second out of the counter, the epoch was rounded down to the nearest decade, thus becoming 1970-1-1. One must assume that this was considered a bit neater than 1971-1-1.
Note that a 32-bit signed integer using 1970-1-1 as its epoch can represent dates up to 2038-1-19, on which date it will wrap around to 1901-12-13.
Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.
Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname
to display the commit it points to.
In your case you have at least these two alternatives:
Reset the current branch to specific tag:
git reset --hard tagname
Generate revert commit on top to get you to the state of the tag:
git revert tag
This might introduce some conflicts if you have merge commits though.
What operating system is this? The answer might depend on the OS involved. However, it looks like you need to find this BLAS library and install it. It doesn't seem to be in PIP (you'll have to do it by hand thus), but if you install it, it ought let you progress your SciPy install.
You can use SimpleDateFormat to convert the String to Date. And after that you have two options,
get the time in millisecond from that date object, and add two hours like, (2 * 60 * 60 * 1000)
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// replace with your start date string
Date d = df.parse("2008-04-16 00:05:05");
Calendar gc = new GregorianCalendar();
gc.setTime(d);
gc.add(Calendar.HOUR, 2);
Date d2 = gc.getTime();
Or,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// replace with your start date string
Date d = df.parse("2008-04-16 00:05:05");
Long time = d.getTime();
time +=(2*60*60*1000);
Date d2 = new Date(time);
Have a look to these tutorials.
My simple answer.
def get_files_tree(src="src_path"):
req_files = []
for r, d, files in os.walk(src):
for file in files:
src_file = os.path.join(r, file)
src_file = src_file.replace('\\', '/')
if src_file.endswith('.db'):
continue
req_files.append(src_file)
return req_files
def copy_tree_force(src_path="",dest_path=""):
"""
make sure that all the paths has correct slash characters.
"""
for cf in get_files_tree(src=src_path):
df= cf.replace(src_path, dest_path)
if not os.path.exists(os.path.dirname(df)):
os.makedirs(os.path.dirname(df))
shutil.copy2(cf, df)
Here is the minimal change to the original proposal to create a valid daemon in Bourne shell (or Bash):
#!/bin/sh
if [ "$1" != "__forked__" ]; then
setsid "$0" __forked__ "$@" &
exit
else
shift
fi
trap 'siguser1=true' SIGUSR1
trap 'echo "Clean up and exit"; kill $sleep_pid; exit' SIGTERM
exec > outfile
exec 2> errfile
exec 0< /dev/null
while true; do
(sleep 30000000 &>/dev/null) &
sleep_pid=$!
wait
kill $sleep_pid &>/dev/null
if [ -n "$siguser1" ]; then
siguser1=''
echo "Wait was interrupted by SIGUSR1, do things here."
fi
done
Explanation:
Guess it does not get any simpler than that.
This might not be the answer you're looking for, but I don't have a better way for downloading DB from phone. What I will suggest is make sure you're using this mini-DDMS. It will be super hidden though if you don't click the very small camoflage box at the very bottom left of program. (tried to hover over it otherwise you might miss it.)
Also the drop down that says no filters (top right). It literally has a ton of different ways you can monitor different process/apps by PPID, name, and a lot more. I've always used this to monitor phone, but keep in mind I'm not doing the type of dev work that needs to be 120% positive the database isn't doing something out of the ordinary.
Hope it helps
Error: 10060 Adding a timeout parameter to request solved the issue for me.
import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)
A similar error also occurred while I was making a GET request. Again, passing a timeout
parameter solved the 10060 Error.
response = requests.get(param_url, timeout=20)