If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:
I use the first, and it works perfectly! It has a sample project to try it on.
I was integrating ZXING into an Android application and there were no good sources for the input all over, I will give you a hint on what worked for me - because it turned out to be very easy.
There is a real handy git repository that provides the zxing
android library project as an AAR archive.
All you have to do is add this to your build.gradle
repositories {
jcenter()
}
dependencies {
implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
implementation 'com.google.zxing:core:3.2.0'
}
and Gradle does all the magic to compile the code and makes it accessible in your app.
To start the Scanner afterwards, use this class/method: From the Activity:
new IntentIntegrator(this).initiateScan(); // `this` is the current Activity
From a Fragment:
IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use IntentIntegrator.forSupportFragment(this) instead.
There are several customizing options:
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
They have a sample-project and are providing several integration examples:
If you already visited the link you going to see that I just copy&pasted the code from the git README. If not, go there to get some more insight and code examples.
If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103
I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.
The following code works fine with me:
brew install zbar
pip install pyqrcode
pip install pyzbar
For QR code image creation:
import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)
For QR code decoding:
from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)
that prints the result:
[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]
Why use an external lib, when google play services (since version 7.8.0) includes a barcode decoder.
The following works for me in Gradle / Groovy for build.gradle
for an Android project, without having to import groovy.io.FileType
(NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):
FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
println "Proguard file located and processed: " + it
}
The accepted answer worked fine for me, but expanding on gimenete's answer, I wanted a generic template I could use to pass through all query/path/header params (just as strings for now), and I came up the following template. I'm posting it here in case someone finds it useful:
#set($keys = [])
#foreach($key in $input.params().querystring.keySet())
#set($success = $keys.add($key))
#end
#foreach($key in $input.params().headers.keySet())
#if(!$keys.contains($key))
#set($success = $keys.add($key))
#end
#end
#foreach($key in $input.params().path.keySet())
#if(!$keys.contains($key))
#set($success = $keys.add($key))
#end
#end
{
#foreach($key in $keys)
"$key": "$util.escapeJavaScript($input.params($key))"#if($foreach.hasNext),#end
#end
}
I developed a generic statement to apply the filter:
string rowFilter = string.Format("[{0}] = '{1}'", columnName, filterValue);
(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = rowFilter;
The square brackets allow for spaces in the column name.
Additionally, if you want to include multiple values in your filter, you can add the following line for each additional value:
rowFilter += string.Format(" OR [{0}] = '{1}'", columnName, additionalFilterValue);
As a modification to crazylammer's answer, I often use:
your_vector_type::iterator it;
for( it = res.start(); it != res.end();)
{
your_vector_type::iterator curr = it++;
if (something)
res.erase(curr);
}
The advantage of this is that you don't have to worry about forgetting to increment your iterator, making it less bug prone when you have complex logic. Inside the loop, curr will never be equal to res.end(), and it will be at the next element regardless of if you erase it from your vector.
You can also use format function. Which can also implicitly take care of type conversion of text, int, etc by itself.
create or replace function concat_return_row_count(tbl_name text, column_name text, value int)
returns integer as $row_count$
declare
total integer;
begin
EXECUTE format('select count(*) from %s WHERE %s = %s', tbl_name, column_name, value) INTO total;
return total;
end;
$row_count$ language plpgsql;
postgres=# select concat_return_row_count('tbl_name','column_name',2); --2 is the value
This wrapper method will help :
private static JSONObject merge(JSONObject... jsonObjects) throws JSONException {
JSONObject jsonObject = new JSONObject();
for(JSONObject temp : jsonObjects){
Iterator<String> keys = temp.keys();
while(keys.hasNext()){
String key = keys.next();
jsonObject.put(key, temp.get(key));
}
}
return jsonObject;
}
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
Converting your set into an array may also help you for iterating over the elements:
Object[] array = set.toArray();
for(int i=0; i<array.length; i++)
Object o = array[i];
The preferred method for passing an array of values to a stored procedure in SQL server is to use table valued parameters.
First you define the type like this:
CREATE TYPE UserList AS TABLE ( UserID INT );
Then you use that type in the stored procedure:
create procedure [dbo].[get_user_names]
@user_id_list UserList READONLY,
@username varchar (30) output
as
select last_name+', '+first_name
from user_mstr
where user_id in (SELECT UserID FROM @user_id_list)
So before you call that stored procedure, you fill a table variable:
DECLARE @UL UserList;
INSERT @UL VALUES (5),(44),(72),(81),(126)
And finally call the SP:
EXEC dbo.get_user_names @UL, @username OUTPUT;
I agree with Cade Roux.
This article should get you on the right track:
One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits.
Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused.
e.g. imagine you search a table on three columns
state, county, zip.
Then an index with state, county, zip. will be used in all three of these searches.
If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful.
You could then create an index on Zip alone that would be used in this instance.
By the way We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state'
I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's.
The article will help a lot. :-)
In my experience, using an event listener on scroll can create a lot of noise due to piping into that event stream, which can cause performance issues if you are executing a bulky handleScroll
function.
I often use the technique shown here in the highest rated answer, but I add debounce on top of it, usually about 100ms
yields good performance to UX ratio.
Here is an example using the top-rated answer with Lodash debounce added:
import debounce from 'lodash/debounce';
export default {
methods: {
handleScroll(event) {
// Any code to be executed when the window is scrolled
this.isUserScrolling = (window.scrollY > 0);
console.log('calling handleScroll');
}
},
created() {
this.handleDebouncedScroll = debounce(this.handleScroll, 100);
window.addEventListener('scroll', this.handleDebouncedScroll);
},
beforeDestroy() {
// I switched the example from `destroyed` to `beforeDestroy`
// to exercise your mind a bit. This lifecycle method works too.
window.removeEventListener('scroll', this.handleDebouncedScroll);
}
}
Try changing the value of 100
to 0
and 1000
so you can see the difference in how/when handleScroll
is called.
BONUS: You can also accomplish this in an even more concise and reuseable manner with a library like vue-scroll
. It is a great use case for you to learn about custom directives in Vue if you haven't seen those yet. Check out https://github.com/wangpin34/vue-scroll.
This is also a great tutorial by Sarah Drasner in the Vue docs: https://vuejs.org/v2/cookbook/creating-custom-scroll-directives.html
Returns true or false based on input
Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
The plain javascript code sample which answers your question literally:
return location.search.indexOf('q=')>=0;
The plain javascript code sample which attempts to find if the q parameter exists and if it has a value:
var queryString=location.search;
var params=queryString.substring(1).split('&');
for(var i=0; i<params.length; i++){
var pair=params[i].split('=');
if(decodeURIComponent(pair[0])=='q' && pair[1])
return true;
}
return false;
How dumb is this solution?
def is_number?(i)
begin
i+0 == i
rescue TypeError
false
end
end
You could use 'corrplot' package.
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
M <- cor(d) # get correlations
library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix
More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
Running the CMD as Administrator on Windows got me going and I think it only makes perfect sense because people don't really ever make an effort to install their stuff in a custom directory. So when you install node.js in Windows directory and then try to install PhoneGap on a Unelevated CMD it has a hard time setting the path variables.
idk if this might help you after 9 years... its a simple bubble sort program
l=[1,6,3,7,5,9,8,2,4,10]
for i in range(1,len(l)):
for j in range (i+1,len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
I faced the same problem. Found the fix here.
Basically just install this.
shasum output:
3e0de8af516c15547602977db939d8c2e44fcc0b visualcppbuildtools_full.exe
md5sum output:
MD5 (visualcppbuildtools_full.exe) = 8d4afd3b226babecaa4effb10d69eb2e
Run your pip installation command again. If everything works fine, its good. Or you might face the following error like me:
Finished generating code
LINK : fatal error LNK1158: cannot run 'rc.exe'
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158
Found the fix for the above problem here: Visual Studio can't build due to rc.exe
That basically says
Add this to your PATH environment variables:
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
Copy these files:
rc.exe
rcdll.dll
From
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
To
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin
It works like a charm
Write a single function and call it for both of them.
function yourHandler(e){
alert( 'something happened!' );
}
jQuery(':input').change(yourHandler).keyup(yourHandler);
The change() and keyup() event registration functions return the original set, so they can be chained.
Sure it isn't actual right now but I faced this issue also and my way: Looks like 'save_screenshot' have some troubles with creating files with space in name same time as I added randomization to filenames for escaping override.
Here I got method to clean my filename of whitespaces (How do I replace whitespaces with underscore and vice versa?):
def urlify(self, s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '-', s)
return s
then
driver.save_screenshot('c:\\pytest_screenshots\\%s' % screen_name)
where
def datetime_now(prefix):
symbols = str(datetime.datetime.now())
return prefix + "-" + "".join(symbols)
screen_name = self.urlify(datetime_now('screen')) + '.png'
Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib
Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.
As Murphy would have it, every well intended change like this has at least one failure mode that nobody thought of. This appears to go wrong when ILMerge was used to merge several assemblies into one and that tool was used incorrectly. A good feedback article that describes this breakage is here. It links to a blog post that describes the mistake. It is rather a long article, but if I interpret it correctly then the wrong ILMerge command line option causes this problem:
/targetplatform:"v4,c:\windows\Microsoft.NET\Framework\v4.0.30319"
Which is incorrect. When you install 4.5 on the machine that builds the program then the assemblies in that directory are updated from 4.0 to 4.5 and are no longer suitable to target 4.0. Those assemblies really shouldn't be there anymore but were kept for compat reasons. The proper reference assemblies are the 4.0 reference assemblies, stored elsewhere:
/targetplatform:"v4,C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
So possible workarounds are to fall back to 4.0 on the build machine, install .NET 4.5 on the target machine and the real fix, to rebuild the project from the provided source code, fixing the ILMerge command.
Do note that this failure mode isn't exclusive to ILMerge, it is just a very common case. Any other scenario where these 4.5 assemblies are used as reference assemblies in a project that targets 4.0 is liable to fail the same way. Judging from other questions, another common failure mode is in build servers that were setup without using a valid VS license. And overlooking that the multi-targeting packs are a free download.
Using the reference assemblies in the c:\program files (x86) subdirectory is a rock hard requirement. Starting at .NET 4.0, already important to avoid accidentally taking a dependency on a class or method that was added in the 4.01, 4.02 and 4.03 releases. But absolutely essential now that 4.5 is released.
From the docs:
To extract the files from a jar file, use
x
, as in:C:\Java> jar xf myFile.jar
To extract only certain files from a jar file, supply their filenames:
C:\Java> jar xf myFile.jar foo bar
The folder where jar
is probably isn't C:\Java
for you, on my Windows partition it's:
C:\Program Files (x86)\Java\jdk[some_version_here]\bin
Unless the location of jar
is in your path environment variable, you'll have to specify the full path/run the program from inside the folder.
EDIT: Here's another article, specifically focussed on extracting JARs: http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html
For PHP:
The DateTimeZone class in PHP > 5.2 is already based on the Olson DB which others mention, so if you are doing timezone conversions in PHP and not in the DB, you are exempt of working with (the hard-to-understand) Olson files.
However, PHP is not updated as frequently as the Olson DB, so just using PHPs time zone conversions may leave you with outdated DST information and influence the correctness of your data. While this is not expected to happen frequently, it may happen, and will happen if you have a large base of users worldwide.
To cope with the above issue, use the timezonedb pecl package. Its function is to update PHP's timezone data. Install this package as frequently as it is updated. (I'm not sure if the updates to this package follow Olson updates exactly, but it seems to be updated at a frequency which is at least very close to the frequency of Olson updates.)
It's just a variable name, and it's conventional in python to use _
for throwaway variables. It just indicates that the loop variable isn't actually used.
An extension of the answer from Keith Hill (to account for whitespace):
$str = " "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }
This returns "Empty" for nulls, empty strings, and strings with whitespace, and "Not Empty" for everything else.
No, you don't need to copy all 387 constructors to Bar and Bah. Bar and Bah can have as many or as few constructors as you want independent of how many you define on Foo. For example, you could choose to have just one Bar constructor which constructs Foo with Foo's 212th constructor.
Yes, any constructors you change in Foo that Bar or Bah depend on will require you to modify Bar and Bah accordingly.
No, there is no way in .NET to inherit constructors. But you can achieve code reuse by calling a base class's constructor inside the subclass's constructor or by calling a virtual method you define (like Initialize()).
You could also check to make sure the DLLs you're looking for aren't included in the GAC. I believe Visual Studio is being smart about not copying those files if it already exists in the GAC on the build machine.
I recently ran in this situation where I'd been testing an SSIS package that needed assemblies to exist in the GAC. I'd since forgotten that and was wondering why those DLLs weren't coming out during a build.
To check what's in the GAC (from a Visual Studio Developer Command Prompt):
gacutil -l
Or output to a file to make it easier to read:
gacutil -l > output.txt
notepad.exe output.txt
To remove an assembly:
gacutil -u MyProjectAssemblyName
I should also note, that once I removed the files from the GAC they were correctly output in the \bin directory after a build (Even for assemblies that were not directly referenced in the root project). This was on Visual Studio 2013 Update 5.
In Short: In order to deal with "Leading Zero" numbers (any 0 digit that comes before the first non-zero) in bash
- Use bc
An arbitrary precision calculator language
Example:
a="000001"
b=$(echo $a | bc)
echo $b
Output: 1
From Bash manual:
"bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming lan- guage. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)"
You can set your custom difference by inserting values in end and updatedAt
getDifference(theDate: string): string {
let end = moment(moment(moment()).valueOf());
let updatedAt = moment(new Date(theDate).valueOf());
let diff = end.diff(updatedAt, "hour", false);
if (diff > 8760) {
diff = end.diff(updatedAt, "years", false);
return diff > 1 ? diff + " years ago" : diff + " year ago";
} else if (diff > 730) {
diff = end.diff(updatedAt, "months", false);
return diff > 1 ? diff + " months ago" : diff + " month ago";
} else if (diff > 24) {
diff = end.diff(updatedAt, "days", false);
return diff > 1 ? diff + " days ago" : diff + " day ago";
} else if (diff <= 0) {
diff = end.diff(updatedAt, "minutes", false);
return diff > 1 ? diff + " minutes ago" : diff + " minute ago";
} else return diff > 1 ? diff + " hours ago" : diff + " hour ago";
}
Why not override the function? In that case you can always be sure it returns 0
in case of NaN
:
(function(original) {
parseInt = function() {
return original.apply(window, arguments) || 0;
};
})(parseInt);
Now, anywhere in your code:
parseInt('') === 0
Was able to get this working:
ng-attr-aria-current="{{::item.isSelected==true ? 'page' : undefined}}"
The nice thing here is that if item.isSelected is false then the attribute simply isn't rendered.
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush
as an object and push that onto cookie_value_add
:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);
A7Soft provide XML comparison tools freeware and shareware:
Using Ref forwarding you can pass the ref from parent to further down to a child.
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
Reference: React Documentation.
As Kintaro already says, person is a method (because of def) and always returns a new Person instance. As you found out it would work if you change the method to a var or val:
val person = new Person("Kumar",12)
Another possibility would be:
def person = new Person("Kumar",12)
val p = person
p.age=20
println(p.age)
However, person.age=20
in your code is allowed, as you get back a Person
instance from the person
method, and on this instance you are allowed to change the value of a var
. The problem is, that after that line you have no more reference to that instance (as every call to person
will produce a new instance).
This is nothing special, you would have exactly the same behavior in Java:
class Person{
public int age;
private String name;
public Person(String name; int age) {
this.name = name;
this.age = age;
}
public String name(){ return name; }
}
public Person person() {
return new Person("Kumar", 12);
}
person().age = 20;
System.out.println(person().age); //--> 12
Had the same problem. found some videos on Youtube. So here is an even simpler suggestion. This is all the code you need:
#include <QDebug>
int main(int argc, char *argv[])
{
qDebug() <<"Hello World"<< endl;
return 0;
}
The above code comes from Qt5 Tutorial: Building a simple Console application by
Dominique Thiebaut
If you are using Spring Security ver >= 3.2, you can use the @AuthenticationPrincipal
annotation:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(@AuthenticationPrincipal CustomUser currentUser, HttpServletRequest request) {
String currentUsername = currentUser.getUsername();
// ...
}
Here, CustomUser
is a custom object that implements UserDetails
that is returned by a custom UserDetailsService
.
More information can be found in the @AuthenticationPrincipal chapter of the Spring Security reference docs.
I used this code to add something to my request.
$req->query->add(['key'=>'variable']);
$req->request->add(['key'=>'variable']);
I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.
I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.
# Enable TCP/IP
Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable
# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433
# Modify TCP/IP properties to enable an IP address
$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }
# Restart SQL Server
Restart-Service 'MSSQL$SQLEXPRESS'
Mac OS:
open -a Google\ Chrome --args --disable-web-security --user-data-dir=
UPD: add =
to --user-data-dir
because newer chrome versions require it in order to work
Also note, that if you happen to be using Yahoo geocoding service you can have timezone information returned to you by setting the correct flag.
http://developer.yahoo.com/geo/placefinder/guide/requests.html#flags-parameter
Can't you start maximized?
Set the System.Windows.Forms.Form.WindowState
property to FormWindowState.Maximized
WinSQL to get last day of last month (i.e today is 2017-02-09, returns 2017-01-31: Select dateadd(day,-day(today()),today())
I encountered the same problem and solved it by
git checkout -f branch
and its specification is rather clear.
-f, --force
When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.
When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.
None of the above solutions worked for me on Windows 8
But the following command works fine
SHIFT + Q
Given that the Apache Subversion server will be moved to this new DNS alias: sub.someaddress.com.tr
:
With Subversion 1.7 or higher, use svn relocate
. Relocate is used when the SVN server's location changes. switch
is only used if you want to change your local working copy to another branch or another path. If using TortoiseSVN, you may follow instructions from the TortoiseSVN Manual. If using the SVN command line interface, refer to this section of SVN's documentation. The command should look like this:
svn relocate svn://sub.someaddress.com.tr/project
Keep using /project
given that the actual contents of your repository probably won't change.
Note: svn relocate
is not available before version 1.7 (thanks to ColinM for the info). In older versions you would use:
svn switch --relocate OLD NEW
https://github.com/loic-sharma/profiler this is good example for alternative to laravel3 debug bar.
I will add that if your need is just to override a property used by your bean, the id approach works too like skaffman explained :
In your first called XML configuration file :
<bean id="myBeanId" class="com.blabla">
<property name="myList" ref="myList"/>
</bean>
<util:list id="myList">
<value>3</value>
<value>4</value>
</util:list>
In your second called XML configuration file :
<util:list id="myList">
<value>6</value>
</util:list>
Then your bean "myBeanId" will be instantiated with a "myList" property of one element which is 6.
In my dimens.xml I have
<dimen name="test">48dp</dimen>
In code If I do
int valueInPixels = (int) getResources().getDimension(R.dimen.test)
this will return 72 which as docs state is multiplied by density of current phone (48dp x 1.5 in my case)
exactly as docs state :
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.
so if you want exact dp value just as in xml just divide it with DisplayMetrics density
int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density)
dp will be 48 now
Set a proper golang middleware, so you can reuse on any endpoint.
type Adapter func(http.Handler) http.Handler
// Adapt h with all specified adapters.
func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
for _, adapter := range adapters {
h = adapter(h)
}
return h
}
func EnableCORS() Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if r.Method == "OPTIONS" {
return
}
h.ServeHTTP(w, r)
})
}
}
mux.Handle("/watcher/{action}/{device}",Adapt(api.SerialHandler(mux),
api.EnableCORS(),
api.ExpectGET(),
))
Have you noticed that in the code you posted, condition2
is never set to False
? This way, your loop body is never executed.
Also, note that in Python, not condition
is preferred to condition == False
; likewise, condition
is preferred to condition == True
.
Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.
Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).
Django 1.4.1
Python 2.7.3
#Model
class MonthEnd(models.Model):
report = models.FileField(db_index=True, upload_to='not_used')
import csv
from os.path import join
#build and store the file
def write_csv():
path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
f = open(path, "w+b")
#wipe the existing content
f.truncate()
csv_writer = csv.writer(f)
csv_writer.writerow(('col1'))
for num in range(3):
csv_writer.writerow((num, ))
month_end_file = MonthEnd()
month_end_file.report.name = path
month_end_file.save()
from my_app.models import MonthEnd
#serve it up as a download
def get_report(request):
month_end = MonthEnd.objects.get(file_criteria=criteria)
response = HttpResponse(month_end.report, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=report.csv'
return response
Starting with Go 1.16, you can use the os.ReadDir function.
func ReadDir(name string) ([]DirEntry, error)
It reads a given directory and returns a DirEntry
slice that contains the directory entries sorted by filename.
It's an optimistic function, so that, when an error occurs while reading the directory entries, it tries to return you a slice with the filenames up to the point before the error.
package main
import (
"fmt"
"log"
"os"
)
func main() {
files, err := os.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(file.Name())
}
}
Go 1.16 (Q1 2021) will propose, with CL 243908 and CL 243914 , the ReadDir
function, based on the FS
interface:
// An FS provides access to a hierarchical file system.
//
// The FS interface is the minimum implementation required of the file system.
// A file system may implement additional interfaces,
// such as fsutil.ReadFileFS, to provide additional or optimized functionality.
// See io/fsutil for details.
type FS interface {
// Open opens the named file.
//
// When Open returns an error, it should be of type *PathError
// with the Op field set to "open", the Path field set to name,
// and the Err field describing the problem.
//
// Open should reject attempts to open names that do not satisfy
// ValidPath(name), returning a *PathError with Err set to
// ErrInvalid or ErrNotExist.
Open(name string) (File, error)
}
That allows for "os: add ReadDir
method for lightweight directory reading":
See commit a4ede9f:
// ReadDir reads the contents of the directory associated with the file f
// and returns a slice of DirEntry values in directory order.
// Subsequent calls on the same file will yield later DirEntry records in the directory.
//
// If n > 0, ReadDir returns at most n DirEntry records.
// In this case, if ReadDir returns an empty slice, it will return an error explaining why.
// At the end of a directory, the error is io.EOF.
//
// If n <= 0, ReadDir returns all the DirEntry records remaining in the directory.
// When it succeeds, it returns a nil error (not io.EOF).
func (f *File) ReadDir(n int) ([]DirEntry, error)
// A DirEntry is an entry read from a directory (using the ReadDir method).
type DirEntry interface {
// Name returns the name of the file (or subdirectory) described by the entry.
// This name is only the final element of the path, not the entire path.
// For example, Name would return "hello.go" not "/home/gopher/hello.go".
Name() string
// IsDir reports whether the entry describes a subdirectory.
IsDir() bool
// Type returns the type bits for the entry.
// The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
Type() os.FileMode
// Info returns the FileInfo for the file or subdirectory described by the entry.
// The returned FileInfo may be from the time of the original directory read
// or from the time of the call to Info. If the file has been removed or renamed
// since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
// If the entry denotes a symbolic link, Info reports the information about the link itself,
// not the link's target.
Info() (FileInfo, error)
}
src/os/os_test.go#testReadDir()
illustrates its usage:
file, err := Open(dir)
if err != nil {
t.Fatalf("open %q failed: %v", dir, err)
}
defer file.Close()
s, err2 := file.ReadDir(-1)
if err2 != nil {
t.Fatalf("ReadDir %q failed: %v", dir, err2)
}
Ben Hoyt points out in the comments to Go 1.16 os.ReadDir
:
os.ReadDir(path string) ([]os.DirEntry, error)
, which you'll be able to call directly without theOpen
dance.
So you can probably shorten this to justos.ReadDir
, as that's the concrete function most people will call.
See commit 3d913a9 (Dec. 2020):
os
: addReadFile
,WriteFile
,CreateTemp
(wasTempFile
),MkdirTemp
(wasTempDir
) fromio/ioutil
io/ioutil
was a poorly defined collection of helpers.Proposal #40025 moved out the generic I/O helpers to io. This CL for proposal #42026 moves the OS-specific helpers to
os
, making the entireio/ioutil
package deprecated.
os.ReadDir
returns[]DirEntry
, in contrast toioutil.ReadDir
's[]FileInfo
.
(Providing a helper that returns[]DirEntry
is one of the primary motivations for this change.)
% notation is called a format specifier. For example, %d tells printf() to print an integer. %s to print a string (char *) etc. You should really look it up here: http://google.com/search?q=printf+format+specifiers
No, commas are not used for string concatenation. Commas are for separating arguments passed to a function.
It sounds like git is launching your editor (probably vi
) so that you can type a commit message. If you are not familiar with vi
, it is easy to learn the basics. Alternatives are:
Use git commit -a -m "my first commit message"
to specify the commit message on the command line (using this will not launch an editor)
Set the EDITOR
environment variable to an editor that you are familiar with
An alternative to dos2unix
command would be using standard utilities like sed
.
For example, dos to unix:
sed 's/\r$//' dos.txt > unix.txt
unix to dos:
sed 's/$/\r/' unix.txt > dos.txt
Angualr itself provide a min and max number validation functionality.
Example - we have a field like age range then see the use of validation.
age_range : ['', Validators.min(1), Validators.max(18)]]
the age always be between 1 to 18.
getDay()
returns the day of the week. To get the date, use date.getDate()
. getMonth()
retrieves the month, but month is zero based, so using getMonth()+1
should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC
to the methods (e.g. date.getUTCFullYear()
, date.getUTCHours()
)
var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
No.
The following solution relies on JavaScript.
<button type="button" onclick="location.href='http://www.stackoverflow.com'">ABC</button>
If the button is to be placed inside an existing <form>
with method="post"
, then ensure the button has the attribute type="button"
otherwise the button will submit the POST operation. In this way you can have a <form>
that contains a mixture of GET and POST operation buttons.
I found an excellent solution to this problem on Mats Karlsson's blog. The solution is to write a subclass of ActionResult that serializes data via JSON.NET, configuring the latter to follow the camelCase convention:
public class JsonCamelCaseResult : ActionResult
{
public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior)
{
Data = data;
JsonRequestBehavior = jsonRequestBehavior;
}
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonRequestBehavior JsonRequestBehavior { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
var response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data == null)
return;
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
}
}
Then use this class as follows in your MVC controller method:
public ActionResult GetPerson()
{
return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}
This error occurs when we parse json content to model object. Json content type is string. For example: https://dotnetfiddle.net/uFClKj Some times, an api that we call may return an error. If we do not check the response status, but proceed to parse the response to model, this issue will occur.
You are still in the context of your CategoryController
even though you're loading a PartialView
from your Views/News
folder.
In such a situation, I populate the password field with some random characters just after the original password is retrieved by the internal JavaScript code, but just before the form submission.
NOTE: The actual password is surely used for the next step by the form. The value is transferred to a hidden field first. See the code example.
That way, when the browser's password manager saves the password, it is not really the password the user had given there. So the user thinks the password has been saved, when in fact some random stuff is what got saved. Over time, the user would know that he/she can't trust the password manager to do the right job for that site.
Now this can lead to a bad user experience; I know because the user may feel that the browser has indeed saved the password. But with adequate documentation, the user can be consoled. I feel this is the way one can fully be sure that the actual password entered by the user cannot be picked up by the browser and saved.
<form id='frm' action="https://google.com">
Password: <input type="password" id="pwd" />
<input type='hidden' id='hiddenpwd' />
<button onclick='subm()'>Submit this</button>
</form>
<script>
function subm() {
var actualpwd = $('#pwd').val();
$('#hiddenpwd').val(actualpwd);
// ...Do whatever Ajax, etc. with this actual pwd
// ...Or assign the value to another hidden field
$('#pwd').val('globbedygook');
$('#frm').submit();
}
</script>
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
};
</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
Use the hex code for a non-breaking space. Something like this:
.breadcrumbs a:before {
content: '>\00a0';
}
Run this command to change .cert
file to .p12
:
openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt
Where server.key
is the server key and server.cert
is a CA issue cert or a self sign cert file.
Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.
There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.
Let me know if there additional problems you are missing.
You can use jQuery to get text in textbox (work well for me), check in image detail
Code:
$(document.evaluate( "xpath" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Example:
$(document.evaluate( "//*[@id='mail']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Inject this above query to your code. Image detail:
Swift 3, pre iOS 10
func schedule() {
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(timeInterval: 20, target: self,
selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: false)
}
}
@objc private func timerDidFire(timer: Timer) {
print(timer)
}
Swift 3, iOS 10+
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { timer in
print(timer)
}
}
Notes
@objc
Use schema name with period in psql command to obtain information about this schema.
Setup:
test=# create schema test_schema;
CREATE SCHEMA
test=# create table test_schema.test_table (id int);
CREATE TABLE
test=# create table test_schema.test_table_2 (id int);
CREATE TABLE
Show list of relations in test_schema
:
test=# \dt test_schema.
List of relations
Schema | Name | Type | Owner
-------------+--------------+-------+----------
test_schema | test_table | table | postgres
test_schema | test_table_2 | table | postgres
(2 rows)
Show test_schema.test_table
definition:
test=# \d test_schema.test_table
Table "test_schema.test_table"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Show all tables in test_schema
:
test=# \d test_schema.
Table "test_schema.test_table"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Table "test_schema.test_table_2"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
etc...
In XML Design
android:background="@drawable/imagename
android:src="@drawable/imagename"
Drawable Image via code
imageview.setImageResource(R.drawable.imagename);
Server image
## Dependency ##
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
Glide.with(context).load(url) .placeholder(R.drawable.image)
.into(imageView);
## dependency ##
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.with(context).load(url) .placeholder(R.drawable.image)
.into(imageView);
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
3 ways to do this:
In C Language (Command Line Tool) Works with Objective C, too:
printf("Hello World");
In Objective C:
NSLog(@"Hello, World!");
In Objective C with variables:
NSString * myString = @"Hello World";
NSLog(@"%@", myString);
In the code with variables, the variable created with class, NSString was outputted be NSLog. The %@ represents text as a variable.
Usually there are 2 types of seed data required.
In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.
I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:
rake db:setup
Fixtures are fragile and flakey to maintain, as are regular sql dumps.
Firstly said, I try to force all my users to use Chrome when printing because other browsers create different layouts.
An answer from this question recommends:
@page {
size: 210mm 297mm;
/* Chrome sets own margins, we change these printer settings */
margin: 27mm 16mm 27mm 16mm;
}
However, I ended up using this CSS for all my pages to be printed:
@media print
{
@page {
size: A4; /* DIN A4 standard, Europe */
margin:0;
}
html, body {
width: 210mm;
/* height: 297mm; */
height: 282mm;
font-size: 11px;
background: #FFF;
overflow:visible;
}
body {
padding-top:15mm;
}
}
Special case: Long Tables
When I needed to print a table over several pages, the margin:0
with the @page
was leading to bleeding edges:
I could solve this thanks to this answer with:
table { page-break-inside:auto }
tr { page-break-inside:avoid; page-break-after:auto }
thead { display:table-header-group; }
tfoot { display:table-footer-group; }
Plus setting the top-bottom-margins for @page
:
@page {
size: auto;
margin: 20mm 0 10mm 0;
}
body {
margin:0;
padding:0;
}
Result:
I would rather prefer a solution that is concise and works with all browser. For now, I hope the information above can help some developers with similar issues.
The element outerHTML
property (note: supported by Firefox after version 11) returns the HTML of the entire element.
<div id="new-element-1">Hello world.</div>
<script type="text/javascript"><!--
var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>
--></script>
Similarly, you can use innerHTML
to get the HTML contained within a given element, or innerText
to get the text inside an element (sans HTML markup).
public IList<Splitting> get(Guid companyId, long customrId) {
var res=from c in Customers_data_source
where c.CustomerId = customrId && c.CompanyID == companyId
from s in Splittings_data_srouce
where s.CustomerID = c.CustomerID
select s;
return res.ToList();
}
Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.
In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.
You can define a pointer to an array, for example this:
double (*p)[42];
defines p
as a pointer to a 42-element array of double
s. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.
A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator []
to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.
If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.
Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.
But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector>
and <array>
, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.
EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.
$('#dropdownid').val('selectedvalue');
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
_x000D_
Are you trying to get visitors to old.com/about.htm to go to new.com/about.htm? If so, you can do this with a mod_rewrite rule in .htaccess:
RewriteEngine on
RewriteRule ^(.*)$ http://www.thenewdomain.com/$1 [R=permanent,L]
I normally differentiate these two via this diagram:
Use PrimaryKeyJoinColumn
Use JoinColumn
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
<select required>
<option value="" disabled selected>None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You can avoid custom validation in this case.
There are subtle differences as to how the fileName
you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream()
and Class.getResourceAsStream()
. These two methods will locate the resource differently.
In Class.getResourceAsStream(path)
, the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt")
will look for a file in your classpath at the following location: "java/lang/myfile.txt"
. If your path starts with a /
, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt")
will look at the following location in your class path ./myfile.txt
.
ClassLoader.getResourceAsStream(path)
will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt")
and String.class.getClassLoader().getResourceAsStream("/myfile.txt")
will both look for a file in your classpath at the following location: ./myfile.txt
.
Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.
In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)
instead of this.getClass().getClassLoader().getResourceAsStream(fileName)
. this.getClass().getResourceAsStream()
will also work.
Read this article for more detailed information about that particular problem.
One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.
So I've looked at the source code of Tomcat's WebAppClassLoader
for several versions of Tomcat. The implementation of findResource(String name)
(which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.
In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt")
may not produce the same result as classLoader.getResourceAsStream("resource.txt")
event though it should (since that what the Javadoc specifies). [source code]
In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]
As a result, you have to be extra careful when using ClassLoader.getResourceAsStream()
or Class.getResourceAsStream()
on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt")
actually calls classLoader.getResourceAsStream("resource.txt")
(the leading /
is stripped).
BigJacko's Javascript code worked for me, but in my case I first had to add some JQuery "noconflict" code. Here's the revised version that worked on my site:
<script type="text/javascript">
var $j = jQuery.noConflict();
jQuery(document).ready(function($j){
$j('iframe').each(function() {
var url = $j(this).attr("src");
if ($j(this).attr("src").indexOf("?") > 0) {
$j(this).attr({
"src" : url + "&wmode=transparent",
"wmode" : "Opaque"
});
}
else {
$j(this).attr({
"src" : url + "?wmode=transparent",
"wmode" : "Opaque"
});
}
});
});
</script>
It's hard to say, but if I would check the actual version of the JDBC driver. Make sure it's 11.1.0.6.
Oracle doesn't include the database version in the filename. So the driver for 11.2 is the exact same name as the driver for 11.1 - ojdbc5.jar. I would extract the driver jar file, and find the MANIFEST.MF file, this will contain some version information. Make sure the version of the JDBC driver matches the version of your database. I suspect it may be a version issue, since there isn't a jar file named ojdbc14.jar on Oracle's 11.1.0.6 download page.
If the version matches - I'm out of ideas :)
You can use several methods for this issue like
Using line-height
#wrapper { line-height: 0px; }
Using display: flex
#wrapper { display: flex; }
#wrapper { display: inline-flex; }
Using display:
block
, table
, flex
and inherit
#wrapper img { display: block; }
#wrapper img { display: table; }
#wrapper img { display: flex; }
#wrapper img { display: inherit; }
It depends which platform.
On GCC it's pretty trivial, see this post for more details.
On MSVC then you can use the StackWalker library that handles all of the underlying API calls needed for Windows.
You'll have to figure out the best way to integrate this functionality into your app, but the amount of code you need to write should be minimal.
Interestingly:
_dbContext.Set<T>().AddOrUpdate(entityToBeUpdatedWithId);
Or if you still is not generic:
_dbContext.Set<UserEntity>().AddOrUpdate(entityToBeUpdatedWithId);
seems to solved my problem smoothly.
We nee to change the values of 'SMTP' in php.ini file php.ini file is located into
EasyPHP-DevServer-14.1VC11\binaries\php\php_runningversion\php.ini
There's now a new css3 property for this: text-decoration-color
So you can now have text in one color and a text-decoration underline - in a different color... without needing an extra 'wrap' element
p {_x000D_
text-decoration: underline;_x000D_
-webkit-text-decoration-color: red; /* safari still uses vendor prefix */_x000D_
text-decoration-color: red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
NB:
1) Browser Support is limited at the moment to Firefox and Chrome (fully supported as of V57) and Safari
2) You could also use the text-decoration shorthand property which looks like this:
<text-decoration-line> || <text-decoration-style> || <text-decoration-color>
...so using the text-decoration
shorthand - the example above would simply be:
p {
text-decoration: underline red;
}
p {_x000D_
text-decoration: underline red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
You can do like this also:
HTML:
<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ' onmouseover="somefunction();"></a>
In javascript:
function somefunction()
{
//Do somethisg.
}
?
A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.
Easiest Method:
Eclipse should be smart enough to figure out what's going on. After clicking next, it will show you all of the files it found in that directory. It will just automatically add those files to your project. Voilà!
Easy way to do
String[] listofIDS={"[email protected]","[email protected]"};
for(String cc:listofIDS) {
message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
}
A new list is created but the items in it are references to the orginal items (just like in the original list). Changes to the list itself are independent, but to the items will find the change in both lists.
In my opinion, uniqueidentifier
/ GUID is neither a varchar
nor an nvarchar
but a char(36)
. Therefore I use:
CAST(xyz AS char(36))
Use the next_url
object to get the next 20 images.
In the JSON response there is an pagination
array:
"pagination":{
"next_max_tag_id":"1411892342253728",
"deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id":"1411892342253728",
"next_min_id":"1414849145899763",
"min_tag_id":"1414849145899763",
"next_url":"https:\/\/api.instagram.com\/v1\/tags\/lemonbarclub\/media\/recent?client_id=xxxxxxxxxxxxxxxxxx\u0026max_tag_id=1411892342253728"
}
This is the information on specific API call and the object next_url
shows the URL to get the next 20 pictures so just take that URL and call it for the next 20 pictures.
For more information about the Instagram API check out this blogpost: Getting Friendly With Instagram’s API
You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically
from the main menu is unchecked.
My experience in August 2013 with a linux client and a simple AWS Beanstalk installation (single EC2 instance) is as follows (based on Community Wiki above)
awsweb...
security group and the details should show at the base of the pageGood luck
If something does not work, when coming thru the front-door, then take the back-door:
drop table if exists apples;
create table if not exists apples(variety char(10) primary key, price int);
insert into apples values('fuji', 5), ('gala', 6);
drop table if exists apples_new;
create table if not exists apples_new like apples;
insert into apples_new select * from apples;
update apples_new
set price = (select price from apples where variety = 'gala')
where variety = 'fuji';
rename table apples to apples_orig;
rename table apples_new to apples;
drop table apples_orig;
It's fast. The bigger the data, the better.
When you only need to check for equality, you can also simply use the in
operator to do a membership test in a sequence of accepted elements:
if message.value[0] in ('/', '\\'):
do_stuff()
You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write files, but that is it unfortunately.
If you are looking to save user information, you will most likely need to use cookies.
You can use a C-style for
loop:
foo=string
for (( i=0; i<${#foo}; i++ )); do
echo "${foo:$i:1}"
done
${#foo}
expands to the length of foo
. ${foo:$i:1}
expands to the substring starting at position $i
of length 1.
To 1): Yes, on most CPUs, SHA-256 is about only 40% as fast as MD5.
To 2): I would argue for a different algorithm than MD5 in such a case. I would definitely prefer an algorithm that is considered safe. However, this is more a feeling. Cases where this matters would be rather constructed than realistic, e.g. if your backup system encounters an example case of an attack on an MD5-based certificate, you are likely to have two files in such an example with different data, but identical MD5 checksums. For the rest of the cases, it doesn't matter, because MD5 checksums have a collision (= same checksums for different data) virtually only when provoked intentionally. I'm not an expert on the various hashing (checksum generating) algorithms, so I can not suggest another algorithm. Hence this part of the question is still open. Suggested further reading is Cryptographic Hash Function - File or Data Identifier on Wikipedia. Also further down on that page there is a list of cryptographic hash algorithms.
To 3): MD5 is an algorithm to calculate checksums. A checksum calculated using this algorithm is then called an MD5 checksum.
"Equivalent" is the word here
While...
$('#selectlist').val();
...is equivalent to...
document.getElementById("selectlist").value
...it's worth noting that...
$('#selectlist')
...although 'equivalent' is not the same as...
document.getElementById("selectlist")
...as the former returns a jQuery object, not a DOM object.
To get the DOM object(s) from the jQuery one, use the following:
$('#selectlist').get(); //get all DOM objects in the jQuery collection
$('#selectlist').get(0); //get the DOM object in the jQuery collection at index 0
$('#selectlist')[0]; //get the DOM objects in the jQuery collection at index 0
This is just a workaround solution:
In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting .gitattributes.
In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and there was no option to force to LF.
Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.
My solution:
Windows-Machines: Let everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: "There is no other system in the wide world, is it?"
Unix-Machines
Add following lines to a config's [alias]
section. This command lists all changed (i.e. modified/new) files:
lc = "!f() { git status --porcelain \
| egrep -r \"^(\?| ).\*\\(.[a-zA-Z])*\" \
| cut -c 4- ; }; f "
Convert all those changed files into dos format:
unix2dos $(git lc)
Optionally ...
Create a git hook for this action to automate this process
Use params and include it and modify the grep
function to match only particular filenames, e.g.:
... | egrep -r "^(\?| ).*\.(txt|conf)" | ...
Feel free to make it even more convenient by using an additional shortcut:
c2dos = "!f() { unix2dos $(git lc) ; }; f "
... and fire the converted stuff by typing
git c2dos
Ad this line inside the OnCreate event on MainActivity (Xamarin)
Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
Ctrl+D Difference for Windows and Linux
It turns out that as of Python 3.6, the Python interpreter handles Ctrl+C differently for Linux and Windows. For Linux, Ctrl+C would work mostly as expected however on Windows Ctrl+C mostly doesn't work especially if Python is running blocking call such as thread.join
or waiting on web response. It does work for time.sleep
, however. Here's the nice explanation of what is going on in Python interpreter. Note that Ctrl+C generates SIGINT
.
Solution 1: Use Ctrl+Break or Equivalent
Use below keyboard shortcuts in terminal/console window which will generate SIGBREAK
at lower level in OS and terminate the Python interpreter.
Mac OS and Linux
Ctrl+Shift+</kbd> or Ctrl+</kbd>
Windows:
Solution 2: Use Windows API
Below are handy functions which will detect Windows and install custom handler for Ctrl+C in console:
#win_ctrl_c.py
import sys
def handler(a,b=None):
sys.exit(1)
def install_handler():
if sys.platform == "win32":
import win32api
win32api.SetConsoleCtrlHandler(handler, True)
You can use above like this:
import threading
import time
import win_ctrl_c
# do something that will block
def work():
time.sleep(10000)
t = threading.Thread(target=work)
t.daemon = True
t.start()
#install handler
install_handler()
# now block
t.join()
#Ctrl+C works now!
Solution 3: Polling method
I don't prefer or recommend this method because it unnecessarily consumes processor and power negatively impacting the performance.
import threading
import time
def work():
time.sleep(10000)
t = threading.Thread(target=work)
t.daemon = True
t.start()
while(True):
t.join(0.1) #100ms ~ typical human response
# you will get KeyboardIntrupt exception
There are multiple ways you can handle this:
If you insist on using PUT
you can change the form action to POST
and add a hidden method_field
that has a value PUT
and a hidden csrf field (if you are using blade then you just need to add @csrf_field
and {{ method_field('PUT') }}
). This way the form would accept the request.
You can simply change the route and form method to POST
. It will work just fine since you are the one defining the route and not using the resource group.
empty()
needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.
However, the real problem you have is that you use empty()
at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for !isset($thing) || !$thing
. When the thing you're checking always exists (in PHP results of function calls always exist), the empty()
function is nothing but a negation operator.
PHP doesn't have concept of emptyness. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:
$x = something();
if (empty($x)) …
and this:
$x = something();
if (!$x) …
has always the same result, in all cases, for all datatypes (because $x
is defined empty()
is redundant).
Return value from the method always exists (even if you don't have return
statement, return value exists and contains null
). Therefore:
if (!empty($r->getError()))
is logically equivalent to:
if ($r->getError())
The range for datetime
will not change, as that would break backward compatibility. So you can hard code it.
jspdf and Angular 8
I generate a pdf and want to upload the pdf with POST request, this is how I do (For clarity, I delete some of the code and service layer)
import * as jsPDF from 'jspdf';
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient)
upload() {
const pdf = new jsPDF()
const blob = pdf.output('blob')
const formData = new FormData()
formData.append('file', blob)
this.http.post('http://your-hostname/api/upload', formData).subscribe()
}
Use ThenByDescending
:
var hold = MyList.OrderBy(x => x.StartDate)
.ThenByDescending(x => x.EndDate)
.ToList();
You can also use query syntax and say:
var hold = (from x in MyList
orderby x.StartDate, x.EndDate descending
select x).ToList();
ThenByDescending
is an extension method on IOrderedEnumerable
which is what is returned by OrderBy
. See also the related method ThenBy
.
If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:
alias df-gb='df -BG'
So if you type:
df-gb
into a terminal, you'll get your intended output of the disk usage in GB.
EDIT: or even use just df -h
to get it in a standard, human readable format.
You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.
This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.
So, which XML parsing module to pick?
Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.
Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.
Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692
You likely don't need to reinstall ggplot2
Solution: go back to plot that didn't work previously. Take the below console output for example. The figure margins (the window that displays your plots) were too small to display the pairs(MinusInner) plot. Then when I tried to make the next qplot, R was still hung up on previous error.
pairs(MinusInner) Error in plot.new() : figure margins too large qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot") Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : invalid graphics state
I fixed the first error by expanding the plot window and rerunning the pairs(MinusInner) plot. Then blam, it worked.
pairs(MinusInner) qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot")
The DECLARE GLOBAL TEMPORARY TABLE statement defines a temporary table for the current connection.
These tables do not reside in the system catalogs and are not persistent.
Temporary tables exist only during the connection that declared them and cannot be referenced outside of that connection.
When the connection closes, the rows of the table are deleted, and the in-memory description of the temporary table is dropped.
For your reference http://docs.oracle.com/javadb/10.6.2.1/ref/rrefdeclaretemptable.html
Try the solution from this question: How can I get an direct Instagram link from a twitter entity?
You can get just the image by appending /media/ to the URL. Using your
You can even specify a size,
One of t (thumbnail), m (medium), l (large). Defaults to m.
So for a thumbnail: http://instagr.am/p/QC8hWKL_4K/media/?size=t
comboBox1.SelectedItem = MyEnum.Something;
should work just fine ... How can you tell that SelectedItem
is null?
SELECT TOP 1 * FROM foo ORDER BY Dates DESC
Will return one result with the latest date.
SELECT * FROM foo WHERE foo.Dates = (SELECT MAX(Dates) FROM foo)
Will return all results that have the same maximum date, to the milissecond.
This is for SQL Server. I'll leave it up to you to use the DATEPART function if you want to use dates but not times.
This function runs in O(n log(n) + m log(m))
compared to O(n*m)
(as seen in the other solutions with loops/indexOf
) which can be useful if you are dealing with lots of values.
However, because neither "a" > 1
nor "a" < 1
, this only works for elements of the same type.
function intersect_arrays(a, b) {
var sorted_a = a.concat().sort();
var sorted_b = b.concat().sort();
var common = [];
var a_i = 0;
var b_i = 0;
while (a_i < a.length
&& b_i < b.length)
{
if (sorted_a[a_i] === sorted_b[b_i]) {
common.push(sorted_a[a_i]);
a_i++;
b_i++;
}
else if(sorted_a[a_i] < sorted_b[b_i]) {
a_i++;
}
else {
b_i++;
}
}
return common;
}
Example:
var array1 = ["cat", "sum", "fun", "hut"], //modified for additional match
array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
intersect_arrays(array1, array2);
>> ["cat", "hut"]
inline
and inline-block
elements are affected by whitespace in the HTML.
The simplest way to fix your problem is to remove the whitespace between </div>
and <div id="col2">
, see: http://jsfiddle.net/XCDsu/15/
There are other possible solutions, see: bikeshedding CSS3 property alternative?
I've been using line-height: normal for the superscript, which works fine for me in Safari, Chrome, and Firefox, but I'm not sure about IE.
This problem occurs when you dont have the gradle wrapper into your SDK tools.
Like the previous responses said, you can update to last cordova-android
version (it works), but if you want to keep working with [email protected]
and [email protected]
, just copy the folder from android studio ex.;
cd /Applications/Android\ Studio.app/Contents/plugins/android/lib/
cp -r templates/ $ANDROID_HOME/tools/templates
chmod +x $ANDROID_HOME/tools/templates/gradle/wrapper/gradlew
In my case, I am using the cordova-plugin-fcm
and it was tested with old version of cordova-android, so I can not use [email protected]
(not yet).
You have to include one more jar.
xmlbeans-2.3.0.jar
Add this and try.
Note: It is required for the files with .xlsx formats only, not for just .xls formats.
That seems to work for me:
<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>
The expected behaviour is to change the colour of the word "fruit".
Perhaps your document was not fully loaded when you called the routine?
Maybe you can try traversing upwards from __filename
until you find a package.json
, and decide that's the main directory your current file belongs to.
Here is what is going on.
First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)
All you have to do to make a module-global variable is just assign to a name.
Imagine a file called foo.py, containing this single line:
X = 1
Now imagine you import it.
import foo
print(foo.X) # prints 1
However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's default is to assume that function variables are local. You simply add a global
declaration in your function, before you try to use the global.
def initDB(name):
global __DBNAME__ # add this line!
if __DBNAME__ is None: # see notes below; explicit test for None
__DBNAME__ = name
else:
raise RuntimeError("Database name has already been set.")
By the way, for this example, the simple if not __DBNAME__
test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you can't just say if not variablename
; in that case, you should explicitly test for None
using the is
operator. I modified the example to add an explicit None
test. The explicit test for None
is never wrong, so I default to using it.
Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be "private" to the module. If you ever do an import * from mymodule
, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule
and then say dir(mymodule)
you will see the "private" variables in the list, and if you explicitly refer to mymodule.__DBNAME__
Python won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.
It is considered best practice in Python not to do import *
, but to minimize the coupling and maximize explicitness by either using mymodule.something
or by explicitly doing an import like from mymodule import something
.
EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the global
keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.
In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.
You can use a list
but your code will be ugly:
__DBNAME__ = [None] # use length-1 list as a mutable
# later, in code:
if __DBNAME__[0] is None:
__DBNAME__[0] = name
A dict
is better. But the most convenient is a class instance, and you can just use a trivial class:
class Box:
pass
__m = Box() # m will contain all module-level values
__m.dbname = None # database name global in module
# later, in code:
if __m.dbname is None:
__m.dbname = name
(You don't really need to capitalize the database name variable.)
I like the syntactic sugar of just using __m.dbname
rather than __m["DBNAME"]
; it seems the most convenient solution in my opinion. But the dict
solution works fine also.
With a dict
you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box
in the above.
Note that datalist
is not the same as a select
. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.
Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.
If you want to disallow user input entirely, maybe select
would be a better choice.
To show only the text value of the option
in the dropdown, we use the inner text for it and leave out the value
attribute. The actual value that we want to send along is stored in a custom data-value
attribute:
To submit this data-value
we have to use an <input type="hidden">
. In this case we leave out the name="answer"
on the regular input and move it to the hidden copy.
<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist
and fetch its data-value
. That value is inserted into the hidden input and submitted.
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
The id answer
and answer-hidden
on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple input
s on the same page with one or more datalist
s providing suggestions.
Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue
to hiddenInput.value = ""
Working jsFiddle examples: plain javascript and jQuery
You can do it for arbitrary refs. This is how to move a branch pointer:
git update-ref -m "reset: Reset <branch> to <new commit>" refs/heads/<branch> <commit>
where -m
adds a message to the reflog for the branch.
The general form is
git update-ref -m "reset: Reset <branch> to <new commit>" <ref> <commit>
You can pick nits about the reflog message if you like - I believe the branch -f
one is different from the reset --hard
one, and this isn't exactly either of them.
<style>
.form-cus {
width: 200px;
margin: auto;
position: relative;
}
.form-cus .putval, .form-cus .getval {
width: 100%;
}
.form-cus .putval {
position: absolute;
left: 0px;
top: 0;
color: transparent !important;
box-shadow: 0 0 0 0 !important;
background-color: transparent !important;
border: 0px;
outline: 0 none;
}
.form-cus .putval::selection {
color: transparent;
background: lightblue;
}
</style>
<link href="css/bootstrap.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<div class="form-group form-cus">
<input class="putval form-control" type="text" id="input" maxlength="16" oninput="xText();">
<input class="getval form-control" type="text" id="output" maxlength="16">
</div>
<script type="text/javascript">
function xText() {
var x = $("#input").val();
var x_length = x.length;
var a = '';
for (var i = 0; i < x_length; i++) {
a += "x";
}
$("#output").val(a);
}
$("#input").click(function(){
$("#output").trigger("click");
})
</script>
It is very easy - you could do it the hard way
.clearfix:after {_x000D_
content: " "; _x000D_
visibility: hidden;_x000D_
display: block;_x000D_
height: 0;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
#first, #second{_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
-webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
width: 500px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#first {_x000D_
border: 1px solid red;_x000D_
float:left;_x000D_
width:50%;_x000D_
}_x000D_
#second {_x000D_
border: 1px solid green;_x000D_
float:left;_x000D_
width:50%;_x000D_
}
_x000D_
<div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
<div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
or the easy way
#wrapper {_x000D_
display: flex;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#first {_x000D_
border: 1px solid red;_x000D_
}_x000D_
#second {_x000D_
border: 1px solid green;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
<div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
There's also like a million other ways.
But I'd just with the easy way.
I would also like to tell you that a lot of the answers here are incorrect
But both the ways that I have shown at least work in HTML 5.
You cannot change the Width and Height properties of the Form as they are readonly. You can change the form's size like this:
button1_Click(object sender, EventArgs e)
{
// This will change the Form's Width and Height, respectively.
this.Size = new Size(420, 200);
}
Find everythin with a dot and show only the suffix.
find . -type f -name "*.*" | awk -F. '{print $NF}' | sort -u
if you know all suffix have 3 characters then
find . -type f -name "*.???" | awk -F. '{print $NF}' | sort -u
or with sed shows all suffixes with one to four characters. Change {1,4} to the range of characters you are expecting in the suffix.
find . -type f | sed -n 's/.*\.\(.\{1,4\}\)$/\1/p'| sort -u
You can use javascript's document.evaluate to run an XPath expression on the DOM. I think it's supported in one way or another in browsers back to IE 6.
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
IE supports selectNodes instead.
MSDN: https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx
This way work for me with Eclipse in Android developer tool from Google -righ click - property - java build path - add external JAR
point to: android-support-v7-appcompat.jar in /sdk/extras/android/support/v7/appcompat/libs
Then
import android.support.v7.app.ActionBarActivity;
Using axes objects is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))
signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)
fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))
plt.show()
If you need the component to remain loaded but hidden you can set the opacity to 0. (I needed this for expo camera for instance)
//in constructor
this.state = {opacity: 100}
/in component
style = {{opacity: this.state.opacity}}
//when you want to hide
this.setState({opacity: 0})
There are differing opinions on whether accessing state in action creators is a good idea:
state.something.items
in an action creator is definitely an anti-pattern and is discouraged because it obscured the change history: if there is a bug and items
are incorrect, it is hard to trace where those incorrect values come from because they are already part of the action, rather than directly computed by a reducer in response to an action. So do this with care."getState
in thunks - that's why it exists. He discusses the pros and cons of accessing state in action creators in his blog post Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability.If you find that you need this, both approaches you suggested are fine. The first approach does not require any middleware:
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
However you can see that it relies on store
being a singleton exported from some module. We don’t recommend that because it makes it much harder to add server rendering to your app because in most cases on the server you’ll want to have a separate store per request. So while technically this approach works, we don’t recommend exporting a store from a module.
This is why we recommend the second approach:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return (dispatch, getState) => {
const {items} = getState().otherReducer;
dispatch(anotherAction(items));
}
}
It would require you to use Redux Thunk middleware but it works fine both on the client and on the server. You can read more about Redux Thunk and why it’s necessary in this case here.
Ideally, your actions should not be “fat” and should contain as little information as possible, but you should feel free to do what works best for you in your own application. The Redux FAQ has information on splitting logic between action creators and reducers and times when it may be useful to use getState
in an action creator.
If your class Question contains only primitives, Serializeble or String fields you can implement him Serializable. ArrayList is implement Serializable, that's why you can put it like Bundle.putSerializable(key, value) and send it to another Activity. IMHO, Parcelable - it's very long way.
I read all the clunky solutions on the net about how to mask passwords in a batch file, the ones from using a hide.com solution and even the ones that make the text and the background the same color. The hide.com solution works decent, it isn't very secure, and it doesn't work in 64-bit Windows. So anyway, using 100% Microsoft utilities, there is a way!
First, let me explain my use. I have about 20 workstations that auto logon to Windows. They have one shortcut on their desktop - to a clinical application. The machines are locked down, they can't right click, they can't do anything but access the one shortcut on their desktop. Sometimes it is necessary for a technician to kick up some debug applications, browse windows explorer and look at log files without logging the autolog user account off.
So here is what I have done.
Do it however you wish, but I put my two batch files on a network share that the locked down computer has access to.
My solution utilizes 1 main component of Windows - runas. Put a shortcut on the clients to the runas.bat you are about to create. FYI, on my clients I renamed the shortcut for better viewing purposes and changed the icon.
You will need to create two batch files.
I named the batch files runas.bat and Debug Support.bat
runas.bat contains the following code:
cls
@echo off
TITLE CHECK CREDENTIALS
goto menu
:menu
cls
echo.
echo ....................................
echo ~Written by Cajun Wonder 4/1/2010~
echo ....................................
echo.
@set /p un=What is your domain username?
if "%un%"=="PUT-YOUR-DOMAIN-USERNAME-HERE" goto debugsupport
if not "%un%"=="PUT-YOUR-DOMAIN-USERNAME-HERE" goto noaccess
echo.
:debugsupport
"%SYSTEMROOT%\system32\runas" /netonly /user:PUT-YOUR-DOMAIN-NAME-HERE\%un% "\\PUT-YOUR-NETWORK-SHARE-PATH-HERE\Debug Support.bat"
@echo ACCESS GRANTED! LAUNCHING THE DEBUG UTILITIES....
@ping -n 4 127.0.0.1 > NUL
goto quit
:noaccess
cls
@echo.
@echo.
@echo.
@echo.
@echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
@echo \\ \\
@echo \\ Insufficient privileges \\
@echo \\ \\
@echo \\ Call Cajun Wonder \\
@echo \\ \\
@echo \\ At \\
@echo \\ \\
@echo \\ 555-555-5555 \\
@echo \\ \\
@echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
@ping -n 4 127.0.0.1 > NUL
goto quit
@pause
:quit
@exit
You can add as many if "%un%" and if not "%un%" for all the users you want to give access to. The @ping is my coonass way of making a seconds timer.
So that takes care of the first batch file - pretty simple eh?
Here is the code for Debug Support.bat:
cls
@echo off
TITLE SUPPORT UTILITIES
goto menu
:menu
cls
@echo %username%
echo.
echo .....................................
echo ~Written by Cajun Wonder 4/1/2010~
echo .....................................
echo.
echo What do you want to do?
echo.
echo [1] Launch notepad
echo.
:choice
set /P C=[Option]?
if "%C%"=="1" goto notepad
goto choice
:notepad
echo.
@echo starting notepad....
@ping -n 3 127.0.0.1 > NUL
start notepad
cls
goto menu
I'm not a coder and really just started getting into batch scripting about a year ago, and this round about way that I discovered of masking a password in a batch file is pretty awesome!
I hope to hear that someone other than me is able to get some use out of it!
SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.
There are a few third-party extensions that provide that capability - check out e.g.:
Dirk's method above will absolutely work, but if you're looking for a way to bring in a long string where whitespace/structure is important to preserve (example: a SQL query using RODBC) there is a two step solution.
1) Bring the text string in across multiple lines
long_string <- "this
is
a
long
string
with
whitespace"
2) R will introduce a bunch of \n
characters. Strip those out with strwrap()
, which destroys whitespace, per the documentation:
strwrap(long_string, width=10000, simplify=TRUE)
By telling strwrap to wrap your text to a very, very long row, you get a single character vector with no whitespace/newline characters.
In command prompt go to the main directory you want the list for ... and type the command tree /f
You cannot concatenate a string
with an int
. You would need to convert your int
to a string
using the str
function, or use formatting
to format your output.
Change: -
print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")
to: -
print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))
or: -
print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")
or as per the comment, use ,
to pass different strings to your print
function, rather than concatenating using +
: -
print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
Could it work declaring the filter the following way?
app.filter('dateUTC', function ($filter) {
return function (input, format) {
if (!angular.isDefined(format)) {
format = 'dd/MM/yyyy';
}
var date = new Date(input);
return $filter('date')(date.toISOString().slice(0, 23), format);
};
});
Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app
module, call mod_login.mod_login
app.py
from flask import Flask
import mod_login
# ...
do_stuff_with(mod_login.mod_login)
mod_login.py
from app import app
mod_login = something
Found a very easy way to do this.
Paste following php script in box. In php script set API_ACCESS_KEY, set device ids separated by coma.
Press F9 or click Run.
Have fun ;)
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );
$registrationIds = array("YOUR DEVICE IDS WILL GO HERE" );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
?>
For FCM, google url would be: https://fcm.googleapis.com/fcm/send
For FCM v1 google url would be: https://fcm.googleapis.com/v1/projects/YOUR_GOOGLE_CONSOLE_PROJECT_ID/messages:send
Note: While creating API Access Key on google developer console, you have to use 0.0.0.0/0 as ip address. (For testing purpose).
In case of receiving invalid Registration response from GCM server, please cross check the validity of your device token. You may check the validity of your device token using following url:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_DEVICE_TOKEN
Some response codes:
Following is the description of some response codes you may receive from server.
{ "message_id": "XXXX" } - success
{ "message_id": "XXXX", "registration_id": "XXXX" } - success, device registration id has been changed mainly due to app re-install
{ "error": "Unavailable" } - Server not available, resend the message
{ "error": "InvalidRegistration" } - Invalid device registration Id
{ "error": "NotRegistered"} - Application was uninstalled from the device
In my case use VS 2013, and It's not support MVC 3 natively (even of you change ./Views/web.config): https://stackoverflow.com/a/28155567/1536197
Using sed
Use sed with basic regular expression's nested subexpressions to capture and reorder the column content. This approach is best suited when there are a limited number of cuts to reorder columns, as in this case.
The basic idea is to surround interesting portions of the search pattern with \(
and \)
, which can be played back in the replacement pattern with \#
where #
represents the sequential position of the subexpression in the search pattern.
For example:
$ echo "foo bar" | sed "s/\(foo\) \(bar\)/\2 \1/"
yields:
bar foo
Text outside a subexpression is scanned but not retained for playback in the replacement string.
Although the question did not discuss fixed width columns, we will discuss here as this is a worthy measure of any solution posed. For simplicity let's assume the file is space delimited although the solution can be extended for other delimiters.
Collapsing Spaces
To illustrate the simplest usage, let's assume that multiple spaces can be collapsed into single spaces, and the the second column values are terminated with EOL (and not space padded).
File:
bash-3.2$ cat f
Column1 Column2
str1 1
str2 2
str3 3
bash-3.2$ od -a f
0000000 C o l u m n 1 sp sp sp sp C o l u m
0000020 n 2 nl s t r 1 sp sp sp sp sp sp sp 1 nl
0000040 s t r 2 sp sp sp sp sp sp sp 2 nl s t r
0000060 3 sp sp sp sp sp sp sp 3 nl
0000072
Transform:
bash-3.2$ sed "s/\([^ ]*\)[ ]*\([^ ]*\)[ ]*/\2 \1/" f
Column2 Column1
1 str1
2 str2
3 str3
bash-3.2$ sed "s/\([^ ]*\)[ ]*\([^ ]*\)[ ]*/\2 \1/" f | od -a
0000000 C o l u m n 2 sp C o l u m n 1 nl
0000020 1 sp s t r 1 nl 2 sp s t r 2 nl 3 sp
0000040 s t r 3 nl
0000045
Preserving Column Widths
Let's now extend the method to a file with constant width columns, while allowing columns to be of differing widths.
File:
bash-3.2$ cat f2
Column1 Column2
str1 1
str2 2
str3 3
bash-3.2$ od -a f2
0000000 C o l u m n 1 sp sp sp sp C o l u m
0000020 n 2 nl s t r 1 sp sp sp sp sp sp sp 1 sp
0000040 sp sp sp sp sp nl s t r 2 sp sp sp sp sp sp
0000060 sp 2 sp sp sp sp sp sp nl s t r 3 sp sp sp
0000100 sp sp sp sp 3 sp sp sp sp sp sp nl
0000114
Transform:
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f2
Column2 Column1
1 str1
2 str2
3 str3
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f2 | od -a
0000000 C o l u m n 2 sp C o l u m n 1 sp
0000020 sp sp nl 1 sp sp sp sp sp sp sp s t r 1 sp
0000040 sp sp sp sp sp nl 2 sp sp sp sp sp sp sp s t
0000060 r 2 sp sp sp sp sp sp nl 3 sp sp sp sp sp sp
0000100 sp s t r 3 sp sp sp sp sp sp nl
0000114
Lastly although the question's example does not have strings of unequal length, this sed expression support this case.
File:
bash-3.2$ cat f3
Column1 Column2
str1 1
string2 2
str3 3
Transform:
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f3
Column2 Column1
1 str1
2 string2
3 str3
bash-3.2$ sed "s/\([^ ]*\)\([ ]*\) \([^ ]*\)\([ ]*\)/\3\4 \1\2/" f3 | od -a
0000000 C o l u m n 2 sp C o l u m n 1 sp
0000020 sp sp nl 1 sp sp sp sp sp sp sp s t r 1 sp
0000040 sp sp sp sp sp nl 2 sp sp sp sp sp sp sp s t
0000060 r i n g 2 sp sp sp nl 3 sp sp sp sp sp sp
0000100 sp s t r 3 sp sp sp sp sp sp nl
0000114
Comparison to other methods of column reordering under shell
Surprisingly for a file manipulation tool, awk is not well-suited for cutting from a field to end of record. In sed this can be accomplished using regular expressions, e.g. \(xxx.*$\)
where xxx
is the expression to match the column.
Using paste and cut subshells gets tricky when implementing inside shell scripts. Code that works from the commandline fails to parse when brought inside a shell script. At least this was my experience (which drove me to this approach).
Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.
Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".
In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.
Step1: recognize the Arduino device unplug your Arduino and list /dev files:
#ls -l /dev
plug your Arduino and go and list /dev files
#ls -l /dev
Find the new file (device) that was not before plugging, for example:
ttyACM0 or ttyUSB1
Read this properties:
ls -l /dev/ttyACM0
crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0
the first c mean that Arduino is a character device.
user owner: root
group owner: dialout
mayor number: 166
minor number: 0
Step2: set your user as group owner.
If you do:
groups <yourUser>
And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:
usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>
restart the pc, and set /dev/<yourDeviceFile>
as your serial port before upload.
Compile means that you need the JAR for compiling and running the app. For a web application, as an example, the JAR will be placed in the WEB-INF/lib directory.
Provided means that you need the JAR for compiling, but at run time there is already a JAR provided by the environment so you don't need it packaged with your app. For a web app, this means that the JAR file will not be placed into the WEB-INF/lib directory.
For a web app, if the app server already provides the JAR (or its functionality), then use "provided" otherwise use "compile".
In my case I was processing a set of jar files contained in a directory. After I processed them I tried to delete them from that directory, but they wouldn't delete. I was using JarFile to process them and the problem was that I forgot to close the JarFile when I was done.
textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));
It will give the color exactly what you have made in html editor , just set the textview and concat it with the textview value. Android does not support span color, change it to font color in editor and you are all set to go.
There's at least 7 different ways to test if a number is odd or even. But, if you read through these benchmarks, you'll find that as TGH mentioned above, the modulus operation is the fastest:
if (x % 2 == 0)
//even number
else
//odd number
Here are a few other methods (from the website) :
//bitwise operation
if ((x & 1) == 0)
//even number
else
//odd number
//bit shifting
if (((x >> 1) << 1) == x)
//even number
else
//odd number
//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
//even number
else
//odd number
When you set to install it "for all users" (not for the current user only), you won't need to route Android Studio for the JAVA_HOME. Of course, have JDK installed.
Numpy arrays have an astype
method. Just do y.astype(int)
.
Note that it might not even be necessary to do this, depending on what you're using the array for. Bool will be autopromoted to int in many cases, so you can add it to int arrays without having to explicitly convert it:
>>> x
array([ True, False, True], dtype=bool)
>>> x + [1, 2, 3]
array([2, 2, 4])
This would restore focus to the previous application and exit the script if the answer was empty.
a=$(osascript -e 'try
tell app "SystemUIServer"
set answer to text returned of (display dialog "" default answer "")
end
end
activate app (path to frontmost application as text)
answer' | tr '\r' ' ')
[[ -z "$a" ]] && exit
If you told System Events to display the dialog, there would be a small delay if it wasn't running before.
For documentation about display dialog, open the dictionary of Standard Additions in AppleScript Editor or see the AppleScript Language Guide.
I envision that maybe you have a parent page with a timer and after a certain amount of time or a task is completed, you forward the user to a new page. Now you want the cursor position, and because they are waiting, they aren't necessarily touching the mouse. So track the mouse on the parent page using standard events and pass the last value to the new page in a get or a post variable.
You can use JHarding's code on your parent page so that the latest position is always available in a global variable:
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;
}
This won't help users that navigate to this page by means other than your parent page.
I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html
His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.
In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this
create type exch_row as object (
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
create type exch_tbl as table of exch_row;
And then you can use it in SQL with TABLE operator, for example:
declare
l_row exch_row;
exch_rt exch_tbl;
begin
l_row := exch_row('PLN', 100, 100);
exch_rt := exch_tbl(l_row);
for r in (select i.*
from item i, TABLE(exch_rt) rt
where i.currency = rt.currency_cd) loop
-- your code here
end loop;
end;
/
SQL> alter session set "_ORACLE_SCRIPT"=true;
SQL> create user sec_admin identified by "Chutinhbk123@!";
I used a combination of the above solutions and some trial and error to come to this solution. Took me an annoying amount of time so I hope this can help someone else in the future. I also noticed that the date picker input is not at all supported by Safari...
I am using styled-components to render a transparent date picker input as shown in the image below:
const StyledInput = styled.input`
appearance: none;
box-sizing: border-box;
border: 1px solid black;
background: transparent;
font-size: 1.5rem;
padding: 8px;
::-webkit-datetime-edit-text { padding: 0 2rem; }
::-webkit-datetime-edit-month-field { text-transform: uppercase; }
::-webkit-datetime-edit-day-field { text-transform: uppercase; }
::-webkit-datetime-edit-year-field { text-transform: uppercase; }
::-webkit-inner-spin-button { display: none; }
::-webkit-calendar-picker-indicator { background: transparent;}
`
Last insert id means you can get inserted auto increment id by using this method in active record,
$this->db->insert_id()
// it can be return insert id it is
// similar to the mysql_insert_id in core PHP
You can refer this link you can find some more stuff.
The issue is that even though we add a folder to skip list it will be deleted if it does not exist.
The solution is to add both the destination and the source folder with full path.
I will try to explain the different scenarios and what happens below, based on my experience.
Starting folder structure:
d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
Command:
robocopy D:\Temp\source D:\Temp\dest /MIR
This will copy over all the files and folders that are missing and deletes all the files and folders that cannot be found in the source
Let's add a new folder and then add it to the command to skip it.
New structure:
d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
d:\Temp\source\3\3.txt
Command:
robocopy D:\Temp\source D:\Temp\dest /MIR /XD "D:\Temp\source\3"
If I add /XD with the source folder and run the command it all seems good the command it wont copy it over.
Now add a folder to the destination to get this setup:
d:\Temp\source\1.txt
d:\Temp\source\2\2.txt
d:\Temp\source\3\3.txt
d:\Temp\dest\1.txt
d:\Temp\dest\2\2.txt
d:\Temp\dest\3\4.txt
If I run the command it is still fine, 4.txt stays there 3.txt is not copied over. All is fine.
But, if I delete the source folder "d:\Temp\source\3" then the destination folder and the file are deleted even though it is on the skip list
1 D:\Temp\source\
*EXTRA Dir -1 D:\Temp\dest\3\
*EXTRA File 4 4.txt
1 D:\Temp\source\2\
If I change the command to skip the destination folder instead then the folder is not deleted, when the folder is missing from the source.
robocopy D:\Temp\source D:\Temp\dest /MIR /XD "D:\Temp\dest\3"
On the other hand if the folder exists and there are files it will copy them over and delete them:
1 D:\Temp\source\3\
*EXTRA File 4 4.txt
100% New File 4 3.txt
To make sure the folder is always skipped and no files are copied over even if the source or destination folder is missing we have to add both to the skip list:
robocopy D:\Temp\source D:\Temp\dest /MIR /XD "d:\Temp\source\3" "D:\Temp\dest\3"
After this no matters if the source folder is missing or the destination folder is missing, robocopy will leave it as it is.
One possibility might be:
If you run $ heroku logs
you may get a "hint" to what the problem is. For me, Heroku could not detect what type of app I was creating. It required me to set the buildpack. Since I was creating a Node.js app, I just had to run $ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-nodejs
. You can read more about it here: https://devcenter.heroku.com/articles/buildpacks. No pushing issues after that.
I know this is an old question, but still posting this here incase someone else gets stuck.
sudo apt-get install libmysqlclient-dev sudo apt-get install python-dev sudo apt-get install MySQL-python
NOtice you should install python-dev as well, the packages like MySQL-python are compiled from source. The pythonx.x-dev packages contain the necessary header files for linking against python. Why does installing numpy require python-dev in Kubuntu 12.04
// Get pixel data
var imageData = context.getImageData(x, y, width, height);
// Color at (x,y) position
var color = [];
color['red'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 0];
color['green'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 1];
color['blue'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 2];
color['alpha'] = imageData.data[((y*(imageData.width*4)) + (x*4)) + 3];
For my case, I had an Angular SLA project template with ASP.NET Core.
I was trying to run the IIS Express from the Visual Studio WebUI solution, triggering the "Actively refused it" error.
The problem, in this case, wasn't connected with the Firewall blocking the connection.
It turned out that I had to run the Angular server independently of the Kestrel run because the Server was expecting the UI to run on a specific port but wasn't actually.
For more information, check the official Microsoft documentation.
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).
The concrete code is by Michal Migurski and by Matt Knapp:
you need to give:
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
inside fragment.
i think Access is a best choice for your case. But you have to split database, see: http://accessblog.net/2005/07/how-to-split-database-into-be-and-fe.html
•How can we make sure that the write-user can make changes to the table data while other users use the data? Do the read-users put locks on tables? Does the write-user have to put locks on the table? Does Access do this for us or do we have to explicitly code this?
there are no read locks unless you put them explicitly. Just use "No Locks"
•Are there any common problems with "MS Access transactions" that we should be aware of?
should not be problems with 1-2 write users
•Can we work on forms, queries etc. while they are being used? How can we "program" without being in the way of the users?
if you split database - then no problem to work on FE design.
•Which settings in MS Access have an influence on how things are handled?
What do you mean?
•Our background is mostly in Oracle, where is Access different in handling multiple users? Is there such thing as "isolation levels" in Access?
no isolation levels in access. BTW, you can then later move data to oracle and keep access frontend, if you have lot of users and big database.
Or, you can install the GNU version of sed in your Mac, called gsed, and use it using the standard Linux syntax.
For that, install gsed
using ports (if you don't have it, get it at http://www.macports.org/) by running sudo port install gsed
. Then, you can run sed -i 's/old_link/new_link/g' *
There is no guarantee that a GUID contains alpha characters. FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF
is a valid GUID so is 00000000-0000-0000-0000-000000000000
and anything in between.
If you are using .NET 4.0, you can use the answer above for the Guid.Parse and Guid.TryParse. Otherwise, you can do something like this:
public static bool TryParseGuid(string guidString, out Guid guid)
{
if (guidString == null) throw new ArgumentNullException("guidString");
try
{
guid = new Guid(guidString);
return true;
}
catch (FormatException)
{
guid = default(Guid);
return false;
}
}
See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
This explains that Unicode versions of Windows APIs have higher limits, and how to enable that.
You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:
Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
.thenComparingInt(SomeEntity::getProperty2)
.thenComparing(SomeEntity::getProperty3, reverseOrder());
At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4
is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.
Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin
https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr
contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.
Initializing the Canvas like below works for TypeScript/Angular solutions.
const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId");
const context = canvas.getContext("2d");
No pseudo-element, no additional element. Only single div:
I used some CSS variables to control easily.
div {
--border-height: 2px;
--border-color: #000;
background: linear-gradient(var(--border-color),var(--border-color)) 0% 50%/ calc(50% - (var(--space) / 2)) var(--border-height),
linear-gradient(var(--border-color),var(--border-color)) 100% 50%/ calc(50% - (var(--space) / 2)) var(--border-height);
background-repeat:no-repeat;
text-align:center;
}
_x000D_
<div style="--space: 100px">Title</div>
<div style="--space: 50px;--border-color: red;--border-height:1px;">Title</div>
<div style="--space: 150px;--border-color: green;">Longer Text</div>
_x000D_
But the above method is not dynamic. You have to change the --space
variable according to the text length.
Further refinig Sglasses method, the above lines force the use of SQLCMD mode, and either treminates the scirpt if not using SQLCMD mode or uses :on error exit
to exit on any error
CONTEXT_INFO is used to keep track of the state.
SET CONTEXT_INFO 0x1 --Just to make sure everything's ok
GO
--treminate the script on any error. (Requires SQLCMD mode)
:on error exit
--If not in SQLCMD mode the above line will generate an error, so the next line won't hit
SET CONTEXT_INFO 0x2
GO
--make sure to use SQLCMD mode ( :on error needs that)
IF CONTEXT_INFO()<>0x2
BEGIN
SELECT CONTEXT_INFO()
SELECT 'This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!'
RAISERROR('This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!',16,1) WITH NOWAIT
WAITFOR DELAY '02:00'; --wait for the user to read the message, and terminate the script manually
END
GO
----------------------------------------------------------------------------------
----THE ACTUAL SCRIPT BEGINS HERE-------------
Put the following in your ~/.bashrc :
function unixts() { date -d "@$1"; }
Example usage:
$ unixts 1551276383
Wed Feb 27 14:06:23 GMT 2019
This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.
from tkinter import *
master = Tk()
def change_text():
my_var.set("Second click")
my_var = StringVar()
my_var.set("First click")
label = Label(mas,textvariable=my_var,fg="red")
button = Button(mas,text="Submit",command = change_text)
button.pack()
label.pack()
master.mainloop()
@Timmmm, about your edit :
GET /timeline_posts // could return the N first posts, with links to fetch the next/previous N posts
This would dramatically reduce the number of calls
And nothing prevents you from designing a server that accepts HTTP parameters to denote the field values your clients may want...
But this is a detail.
Much more important is the fact that you did not mention huge advantages of the REST architectural style (much better scalability, due to server statelessness; much better availability, due to server statelessness also; much better use of the standard services, such as caching for instance, when using a REST architectural style; much lower coupling between client and server, due to the use of a uniform interface; etc. etc.)
As for your remark
"Not all actions easily map to CRUD (create, read/retrieve, update, delete)."
: an RDBMS uses a CRUD approach, too (SELECT/INSERT/DELETE/UPDATE), and there is always a way to represent and act upon a data model.
Regarding your sentence
"You may not even be dealing with object type resources"
: a RESTful design is, by essence, a simple design - but this does NOT mean that designing it is simple. Do you see the difference ? You'll have to think a lot about the concepts your application will represent and handle, what must be done by it, if you prefer, in order to represent this by means of resources. But if you do so, you will end up with a more simple and efficient design.
This code is tested and working.
public void dumpMe(Map m) { dumpMe(m, ""); }
private void dumpMe(Map m, String padding) {
Set s = m.keySet();
java.util.Iterator ir = s.iterator();
while (ir.hasNext()) {
String key = (String) ir.next();
Object value = m.get(key);
if (value == null) continue;
if (value instanceof Map) {
System.out.println (padding + key + " = {");
dumpMe((Map)value, padding + " ");
System.out.println(padding + "}");
}
else if (value instanceof String ||
value instanceof Integer ||
value instanceof Double ||
value instanceof Float ||
value instanceof Long ) {
System.out.println(padding + key + " = " + value.toString());
}
else {
System.out.println(padding + key + " = UNKNOWN OBJECT: " + value.toString());
// You could also throw an exception here
}
} // while
} // dumpme
Charles.
JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
JSONObject secObject = (JSONObject) jsonChildArray.get(1);
I think this should work, but i do not have the possibility to test it at the moment..
the answers here are correct and i liked @Jyo the Whiff idea of a show and hide fragment implementation except the way he has it currently would hide the fragment on the first run so i added a slight change in that i added the isAdded check and show the fragment if its not already
public void showHideCardPreview(int id) {
FragmentManager fm = getSupportFragmentManager();
Bundle b = new Bundle();
b.putInt(Constants.CARD, id);
cardPreviewFragment.setArguments(b);
FragmentTransaction ft = fm.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
if (!cardPreviewFragment.isAdded()){
ft.add(R.id.full_screen_container, cardPreviewFragment);
ft.show(cardPreviewFragment);
} else {
if (cardPreviewFragment.isHidden()) {
Log.d(TAG,"++++++++++++++++++++ show");
ft.show(cardPreviewFragment);
} else {
Log.d(TAG,"++++++++++++++++++++ hide");
ft.hide(cardPreviewFragment);
}
}
ft.commit();
}
To access the tomcat manager from different machine you have to follow bellow steps:
1. Update conf/tomcat-users.xml file with user and some roles:
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".
Here tomcat user and password is : admin
2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):
Default configuration:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
<Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>
Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .
2.a : Allow specefic IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />
Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address
2.b : Allow all IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow=".*" />
Here using allow=".*" you are allowing all IP.
Thanks :)
"... and am finding that my code would be more re-usable if I were able to use variables instead of Select functions."
While I cannot think of any more than an isolated handful of situations where .Select
would be a better choice than direct cell referencing, I would rise to the defense of Selection
and point out that it should not be thrown out for the same reasons that .Select
should be avoided.
There are times when having short, time-saving macro sub routines assigned to hot-key combinations available with the tap of a couple of keys saves a lot of time. Being able to select a group of cells to enact the operational code on works wonders when dealing with pocketed data that does not conform to a worksheet-wide data format. Much in the same way that you might select a group of cells and apply a format change, selecting a group of cells to run special macro code against can be a major time saver.
Examples of Selection-based sub framework:
Public Sub Run_on_Selected()
Dim rng As Range, rSEL As Range
Set rSEL = Selection 'store the current selection in case it changes
For Each rng In rSEL
Debug.Print rng.Address(0, 0)
'cell-by-cell operational code here
Next rng
Set rSEL = Nothing
End Sub
Public Sub Run_on_Selected_Visible()
'this is better for selected ranges on filtered data or containing hidden rows/columns
Dim rng As Range, rSEL As Range
Set rSEL = Selection 'store the current selection in case it changes
For Each rng In rSEL.SpecialCells(xlCellTypeVisible)
Debug.Print rng.Address(0, 0)
'cell-by-cell operational code here
Next rng
Set rSEL = Nothing
End Sub
Public Sub Run_on_Discontiguous_Area()
'this is better for selected ranges of discontiguous areas
Dim ara As Range, rng As Range, rSEL As Range
Set rSEL = Selection 'store the current selection in case it changes
For Each ara In rSEL.Areas
Debug.Print ara.Address(0, 0)
'cell group operational code here
For Each rng In ara.Areas
Debug.Print rng.Address(0, 0)
'cell-by-cell operational code here
Next rng
Next ara
Set rSEL = Nothing
End Sub
The actual code to process could be anything from a single line to multiple modules. I have used this method to initiate long running routines on a ragged selection of cells containing the filenames of external workbooks.
In short, don't discard Selection
due to its close association with .Select
and ActiveCell
. As a worksheet property it has many other purposes.
(Yes, I know this question was about .Select
, not Selection
but I wanted to remove any misconceptions that novice VBA coders might infer.)
In my case, it's a typo caused this issue:
<VirtualHost *.8080>
should be
<VirtualHost *:8080>
textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;
WPF Foreground and Background is of type System.Windows.Media.Brush
. You can set another color like this:
using System.Windows.Media;
textBox1.Background = Brushes.White;
textBox1.Background = new SolidColorBrush(Colors.White);
textBox1.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0));
textBox1.Background = System.Windows.SystemColors.MenuHighlightBrush;
Edit
Solution mentioned by @leftclickben is also effective. We can also use a stored procedure for the same.
CREATE PROCEDURE get_tree(IN id int)
BEGIN
DECLARE child_id int;
DECLARE prev_id int;
SET prev_id = id;
SET child_id=0;
SELECT col3 into child_id
FROM table1 WHERE col1=id ;
create TEMPORARY table IF NOT EXISTS temp_table as (select * from table1 where 1=0);
truncate table temp_table;
WHILE child_id <> 0 DO
insert into temp_table select * from table1 WHERE col1=prev_id;
SET prev_id = child_id;
SET child_id=0;
SELECT col3 into child_id
FROM TABLE1 WHERE col1=prev_id;
END WHILE;
select * from temp_table;
END //
We are using temp table to store results of the output and as the temp tables are session based we wont there will be not be any issue regarding output data being incorrect.
SQL FIDDLE Demo
Try this query:
SELECT
col1, col2, @pv := col3 as 'col3'
FROM
table1
JOIN
(SELECT @pv := 1) tmp
WHERE
col1 = @pv
SQL FIDDLE Demo
:| COL1 | COL2 | COL3 |
+------+------+------+
| 1 | a | 5 |
| 5 | d | 3 |
| 3 | k | 7 |
Note
parent_id
value should be less than thechild_id
for this solution to work.
To bring more confusion in this already rich thread, I happened to bump in the same unresolved external on fprintf
main.obj : error LNK2019: unresolved external symbol __imp__fprintf referenced in function _GenerateInfoFile
Even if in my case it was in a rather different context : under Visual Studio 2005 (Visual Studio 8.0) and the error was happening in my own code (the very same I was compiling), not a third party.
It happened that this error was triggered by /MD option in my compiler flags. Switching to /MT removed the issue. This is weird because usually, linking statically (MT) raises more problem than dynamically (MD)... but just in case it serves other, I put it there.