No, there isn't. The designers of Java are on record as saying they didn't like unsigned ints. Use a BigInteger instead. See this question for details.
I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...)
but it would not work in my case.
I actually had a String
in a JSON format, but I feel like it is literally transforming the toString()
method of every field into JSON. In my case, a date LocalDate
field would end up as:
"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}
which is not the best date format to send in a request ...
In the end, the simplest solution in my case is to use the Spring ObjectMapper
. Its behaviour is better since it uses Jackson to build your JSON with complex types.
@Autowired
private ObjectMapper objectMapper;
and I simply used it in mytest:
mockMvc.perform(post("/api/")
.content(objectMapper.writeValueAsString(...))
.contentType(MediaType.APPLICATION_JSON)
);
Building on Mark Byers's answer.
The 3rd project could be a WCF project, hosted as a Windows Service. If all programs listened to that service, one application could call the service. The service passes the message on to all listening clients and they can perform an action if suitable.
Good WCF videos here - http://msdn.microsoft.com/en-us/netframework/dd728059
You can do this:
gdb --args path/to/executable -every -arg you can=think < of
The magic bit being --args
.
Just type run
in the gdb command console to start debugging.
I always wanted to do this and found a nice and easy way of doing it. I wrote down the complete procedure just in case anyone else needs it.
First install a 16 kB program called xclip
:
sudo apt-get install xclip
You can then pipe the output into xclip
to be copied into the clipboard:
cat file | xclip
To paste the text you just copied, you shall use:
xclip -o
To simplify life, you can set up an alias in your .bashrc file as I did:
alias "c=xclip"
alias "v=xclip -o"
To see how useful this is, imagine I want to open my current path in a new terminal window (there may be other ways of doing it like Ctrl+T on some systems, but this is just for illustration purposes):
Terminal 1:
pwd | c
Terminal 2:
cd `v`
Notice the ` `
around v
. This executes v
as a command first and then substitutes it in-place for cd
to use.
Only copy the content to the X
clipboard
cat file | xclip
If you want to paste somewhere else other than a X
application, try this one:
cat file | xclip -selection clipboard
Another solution in urllib2
and Python 2.7:
req = urllib2.Request('http://www.example.com/')
req.add_unredirected_header('User-Agent', 'Custom User-Agent')
urllib2.urlopen(req)
This works for me
Open the folder which contains the project file project.xcworkspace
from the terminal.
Write this command: git rm --cached *xcuserstate
This will remove the file.
Just stick in a file and call it "ServiceModelSamples.bat" or something.
You could add "@echo off" as line one, so the command doesn't get printed to the screen:
@echo off
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
Perhaps this should be the select (if I understand the question correctly)
select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before
On Linux, I used the following params:
-Djavax.management.builder.initial=
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
and also I edited /etc/hosts
so that the hostname resolves to the host address (192.168.0.x) rather than the loopback address (127.0.0.1)
Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().
from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])
sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']
tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')
We are selecting the last index (-1) of the tuple
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
In case anyone wanted more of a visual reference:
Decimal approximations reference table:
+----------------------------------------------------------------------------+
¦ aspect ratio ¦ decimal approx. ¦ decimal approx. ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦ 19.5 x 9 ¦ 0.462... ¦ 2.167... ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 9 ¦ 0.474... ¦ 2.11... ¦
¦--------------------------+------------------------+------------------------¦
¦ ~18.7 x 9 ¦ 0.482... ¦ 2.074... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18.5 x 9 ¦ 0.486... ¦ 2.056... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18 x 9 ¦ 0.5 ¦ 2 ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 10 ¦ 0.526... ¦ 1.9 ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 9 ¦ 0.5625 ¦ 1.778... ¦
¦--------------------------+------------------------+------------------------¦
¦ 5 x 3 ¦ 0.6 ¦ 1.667... ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 10 ¦ 0.625 ¦ 1.6 ¦
¦--------------------------+------------------------+------------------------¦
¦ 3 x 2 ¦ 0.667... ¦ 1.5 ¦
¦--------------------------+------------------------+------------------------¦
¦ 4 x 3 ¦ 0.75 ¦ 1.333... ¦
+----------------------------------------------------------------------------+
Changelog:
56x27 === ~18.7x9
(Huawei P20), 19x9
(Nokia X6 2018) and 19.5x9
(LG G7 ThinQ)19x10
(Essential Phone)18.5x9
(Samsung Galaxy S8) and 18x9
(LG G6)In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.
Just as a random example:
// The callback interface
interface MyCallback {
void callbackCall();
}
// The class that takes the callback
class Worker {
MyCallback callback;
void onEvent() {
callback.callbackCall();
}
}
// Option 1:
class Callback implements MyCallback {
void callbackCall() {
// callback code goes here
}
}
worker.callback = new Callback();
// Option 2:
worker.callback = new MyCallback() {
void callbackCall() {
// callback code goes here
}
};
I probably messed up the syntax in option 2. It's early.
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
With the latest Firefox, I must use:
<script type="text/javascript">...</script>
Or else the script may not run properly.
I, for example, use fail()
to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.
This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.
#!/bin/bash
# loop*figures.bash
for i in 1 2 3 4 5 # First loop.
do
for j in $(seq 1 $i)
do
echo -n "*"
done
echo
done
echo
# outputs
# *
# **
# ***
# ****
# *****
for i in 5 4 3 2 1 # First loop.
do
for j in $(seq -$i -1)
do
echo -n "*"
done
echo
done
# outputs
# *****
# ****
# ***
# **
# *
for i in 1 2 3 4 5 # First loop.
do
for k in $(seq -5 -$i)
do
echo -n ' '
done
for j in $(seq 1 $i)
do
echo -n "* "
done
echo
done
echo
# outputs
# *
# * *
# * * *
# * * * *
# * * * * *
for i in 1 2 3 4 5 # First loop.
do
for j in $(seq -5 -$i)
do
echo -n "* "
done
echo
for k in $(seq 1 $i)
do
echo -n ' '
done
done
echo
# outputs
# * * * * *
# * * * *
# * * *
# * *
# *
exit 0
The YourKit Java profiler is an excellent commercial solution. You can find further information in the docs on CPU profiling and memory profiling.
All this git reset, hard, soft, and everything else mentioned here is probably working (it didn't for me) if you do the steps correctly and some sort of a genie.
If you are the average Joe smo, try this:
How to use git merge --squash?
Saved my life, and will be my go to squash, been using this 4 times since I found out about it. Simple, clean and basically 1 comamnd.
In short:
If you are on a branch lets call it "my_new_feature" off develop and your pull request has 35 commits (or however many) and you want it to be 1.
A. Make sure your branch is up to date, Go on develop, get latest and merge and resolve any conflicts with "my_new_feature"
(this step really you should take as soon as you can all the time anyway)
B. Get latest of develop and branch out to a new branch call it
"my_new_feature_squashed"
C. magic is here.
You want to take your work from "my_new_feature" to "my_new_feature_squashed"
So just do (while on your new branch we created off develop):
git merge --squash my_new_feature
All your changes will now be on your new branch, feel free to test it, then just do your 1 single commit, push, new PR of that branch - and wait for repeat the next day.
Don't you love coding? :)
First of all, return
is a keyword and exit
is a function.
That said, here's a simplest of explanations.
return
It returns a value from a function.
exit
It exits out of or abandons the current shell.
I quickly found out there's someone already made a helper: slack-cleaner for this.
And for me it's just:
slack-cleaner --token=<TOKEN> --message --channel jenkins --user "*" --perform
For others who'd like to debug the two JSON objects (usually, there is a reference and a target), here is a solution you may use. It will list the "path" of different/mismatched ones from target to the reference.
level
option is used for selecting how deep you would like to look into.
show_variables
option can be turned on to show the relevant variable.
def compareJson(example_json, target_json, level=-1, show_variables=False):
_different_variables = _parseJSON(example_json, target_json, level=level, show_variables=show_variables)
return len(_different_variables) == 0, _different_variables
def _parseJSON(reference, target, path=[], level=-1, show_variables=False):
if level > 0 and len(path) == level:
return []
_different_variables = list()
# the case that the inputs is a dict (i.e. json dict)
if isinstance(reference, dict):
for _key in reference:
_path = path+[_key]
try:
_different_variables += _parseJSON(reference[_key], target[_key], _path, level, show_variables)
except KeyError:
_record = ''.join(['[%s]'%str(p) for p in _path])
if show_variables:
_record += ': %s <--> MISSING!!'%str(reference[_key])
_different_variables.append(_record)
# the case that the inputs is a list/tuple
elif isinstance(reference, list) or isinstance(reference, tuple):
for index, v in enumerate(reference):
_path = path+[index]
try:
_target_v = target[index]
_different_variables += _parseJSON(v, _target_v, _path, level, show_variables)
except IndexError:
_record = ''.join(['[%s]'%str(p) for p in _path])
if show_variables:
_record += ': %s <--> MISSING!!'%str(v)
_different_variables.append(_record)
# the actual comparison about the value, if they are not the same, record it
elif reference != target:
_record = ''.join(['[%s]'%str(p) for p in path])
if show_variables:
_record += ': %s <--> %s'%(str(reference), str(target))
_different_variables.append(_record)
return _different_variables
I've seen 3 other fixes so far:
The solution boils down to clean up the .metadata folder with correct contents
var is not a member of inner class.
To access var, a pointer or reference to an outer class instance should be used. e.g. pOuter->var will work if the inner class is a friend of outer, or, var is public, if one follows C++ standard strictly.
Some compilers treat inner classes as the friend of the outer, but some may not. See this document for IBM compiler:
"A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class. Unless you use explicit pointers, references, or object names, declarations in a nested class can only use visible constructs, including type names, static members, and enumerators from the enclosing class and global variables.
Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes. Member functions of the enclosing class have no special access to members of a nested class."
If what you need is to post data instead of adding the info in the url.
public Request post(String url, String username, String password,
Listener listener, ErrorListener errorListener) {
JSONObject params = new JSONObject();
params.put("user", username);
params.put("pass", password);
Request req = new Request(
Method.POST,
url,
params.toString(),
listener,
errorListener
);
return req;
}
If what you want to do is edit the headers in the request this is what you want to do:
// could be any class that implements Map
Map<String, String> mHeaders = new ArrayMap<String, String>();
mHeaders.put("user", USER);
mHeaders.put("pass", PASSWORD);
Request req = new Request(url, postBody, listener, errorListener) {
public Map<String, String> getHeaders() {
return mHeaders;
}
}
Oracle 10g Express Edition ships with Oracle Application Express (Apex) built-in. You're running this in its SQL Commands window, which doesn't support SQL*Plus syntax.
That doesn't matter, because (as you have discovered) the BEGIN...END syntax does work in Apex.
To run Java code as daemon (service) you can write JNI based stub.
http://jnicookbook.owsiak.org/recipe-no-022/
for a sample code that is based on JNI. In this case you daemonize the code that was started as Java and main loop is executed in C. But it is also possible to put main, daemon's, service loop inside Java.
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo029
Have fun with JNI!
Try this:
SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
it will display the schema+table name for all tables in the current database.
Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:
SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
,@SQL nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''
INSERT INTO @AllTables (CompleteTableName)
EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1
set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.
That's the vi editor. Try ESC
:q!
.
It's all about the input seed. Same seed give the same results all the time. Even you re-run your program again and again it's the same output.
public static void main(String[] args) {
randomString(-229985452);
System.out.println("------------");
randomString(-229985452);
}
private static void randomString(int i) {
Random ran = new Random(i);
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
}
Output
-755142161
-1073255141
-369383326
1592674620
-1524828502
------------
-755142161
-1073255141
-369383326
1592674620
-1524828502
Try the Offstage
widget
if attribute offstage:true
the not occupy the physical space and invisible,
if attribute offstage:false
it will occupy the physical space and visible
Offstage(
offstage: true,
child: Text("Visible"),
),
git pull origin master --allow-unrelated-histories
You might want to use this if your histories doesnt match and want to merge it anyway..
refer here
You can use VBScript regular expression features using OLE Automation. This is way better than the overhead of creating and maintaining an assembly. Please make sure you go through the comments section to get a better modified version of the main one.
http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx
DECLARE @obj INT, @res INT, @match BIT;
DECLARE @pattern varchar(255) = '<your regex pattern goes here>';
DECLARE @matchstring varchar(8000) = '<string to search goes here>';
SET @match = 0;
-- Create a VB script component object
EXEC @res = sp_OACreate 'VBScript.RegExp', @obj OUT;
-- Apply/set the pattern to the RegEx object
EXEC @res = sp_OASetProperty @obj, 'Pattern', @pattern;
-- Set any other settings/properties here
EXEC @res = sp_OASetProperty @obj, 'IgnoreCase', 1;
-- Call the method 'Test' to find a match
EXEC @res = sp_OAMethod @obj, 'Test', @match OUT, @matchstring;
-- Don't forget to clean-up
EXEC @res = sp_OADestroy @obj;
If you get SQL Server blocked access to procedure 'sys.sp_OACreate'...
error, use sp_reconfigure
to enable Ole Automation Procedures
. (Yes, unfortunately that is a server level change!)
More information about the Test
method is available here
Happy coding
Recently I am working with the 1.8.0_25 JDK version on Windows 8.1 and I had the same problem with this. But as PankaJ Jakhar said
The real solution for me was pretty simple:
The path I introduced for this variable was:
C:\Program Files\Java\jdk1.8.0_25\
And it works for me!
I found a way that seems to work better for me:
ssh-keygen -y -f <private key file>
That command will output the public key for the given private key, so then just compare the output to each *.pub file.
This operation is a complement, not a negation.
Consider that ~0 = -1, and work from there.
The algorithm for negation is, "complement, increment".
Did you know? There is also "one's complement" where the inverse numbers are symmetrical, and it has both a 0 and a -0.
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
If you want to work with JAX-RS (e.g. RESTEasy) try this:
@Path("/pic")
public Response get(@QueryParam("url") final String url) {
String picUrl = URLDecoder.decode(url, "UTF-8");
return Response.ok(sendPicAsStream(picUrl))
.header(HttpHeaders.CONTENT_TYPE, "image/jpg")
.build();
}
private StreamingOutput sendPicAsStream(String picUrl) {
return output -> {
try (InputStream is = (new URL(picUrl)).openStream()) {
ByteStreams.copy(is, output);
}
};
}
using javax.ws.rs.core.Response
and com.google.common.io.ByteStreams
Internet Explorer (under version 9) does not natively support rounded corners.
There's an amazing script that will magically add it for you: CSS3 PIE.
I've used it a lot of times, with amazing results.
String
s in java are objects, so when comparing with ==
, you are comparing references, rather than values. The correct way is to use equals()
.
However, there is a way. If you want to compare String
objects using the ==
operator, you can make use of the way the JVM copes with strings. For example:
String a = "aaa";
String b = "aaa";
boolean b = a == b;
b
would be true
. Why?
Because the JVM has a table of String
constants. So whenever you use string literals (quotes "
), the virtual machine returns the same objects, and therefore ==
returns true
.
You can use the same "table" even with non-literal strings by using the intern()
method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:
String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
Wrong port number in my case. Check if port number when starting Selenium server is the same as in your script.
I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:
@{
var htmlAttr = new Dictionary<string, object>();
htmlAttr.Add("id", strElementId);
if (!CSSClass.IsEmpty())
{
htmlAttr.Add("class", strCSSClass);
}
}
@* ... *@
@Html.TextBox("somename", "", htmlAttr)
If this way will be useful for you i recommend to define dictionary htmlAttr
in your model so your view doesn't need any @{ }
logic blocks (be more clear).
The formula for the number of binary bits required to store n integers (for example, 0 to n - 1) is:
and round up.
For example, for values -128 to 127 (signed byte) or 0 to 255 (unsigned byte), the number of integers is 256, so n is 256, giving 8 from the above formula.
For 0 to n, use n + 1 in the above formula (there are n + 1 integers).
On your calculator, loge may just be labelled log or ln (natural logarithm).
EDIT: Since the answer is not valid with newer versions of jquery As jQuery.browser is deprecated in ver 1.9, So Use Jquery Migrate Plugin for that matter.
Original Answer
jQuery.browser
and
jQuery.browser.version
is your way to go...
my example:
companyNamesFirst = this.model.CustomerDisplayList.Where(a => a.CompanyFirst != null ? a.CompanyFirst.StartsWith(typedChars.ToLower())) : false).Select(b => b.CompanyFirst).Distinct().ToList();
Here is my problem and the solution that what worked for me.
I added a new controller with a single action returning a string to an existing application. But when I navigated to that controller via browser, I was getting the same error as mentioned above.
After doing lot of googling, I found out that I simply had to modify my Global.asax.cs file for it to recognize the new controller. All I did was added a space to Global.asax.cs file so that it is modified and it worked
Simply, double shift then type Assets Folder
choose it to be created in the correct place
use myString.c_str()
if you want a c-like string (const char*
) to use with printf
thanks
Why should you need manipulations with packages.config or .csproj files?
The error explicitly says: Use NuGet Package Restore to download them.
Use it accordingly this instruction: https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore-troubleshooting:
Quick solution for Visual Studio users
1.Select the Tools > NuGet Package Manager > Package Manager Settings menu command.
2.Set both options under Package Restore.
3.Select OK.
4.Build your project again.
You can use a ValueConverter that inverts a bool property for you.
XAML:
IsEnabled="{Binding Path=IsReadOnly, Converter={StaticResource InverseBooleanConverter}}"
Converter:
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter: IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;
So 2 basic things to get string visible in the different class:
//make sure you are importing the right R class
import your.namespace.R;
//don't forget about the context
public void some_method(Context context) {
context.getString(R.string.YOUR_STRING);
}
You can do it with regular JavaScript this way:
document.getElementById('h1_id').innerHTML = 'h1 content here';
Here is the doc for getElementById and the innerHTML property.
The innerHTML
property description:
A DOMString containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.
SELECT * FROM NOTES ORDER BY UPPER(title)
Try this..
Download the Sqlite Manager jar file here.
Add it to your eclipse > dropins Directory.
Restart eclipse.
Launch the compatible emulator or device
Run your application.
Go to Window > Open Perspective > DDMS >
Choose the running device.
Go to File Explorer tab.
Select the directory called databases under your application's package.
Select the .db file under the database directory.
Then click Sqlite manager icon like this .
Now you're able to see the .db file.
Happy coding.....
You have a JSON Lines format text file. You need to parse your file line by line:
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.
Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.
If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.
you can use:
overflow-x: auto;
If you set 'auto' in overflow-x, scroll will appear only when inner size is biggest that DIV area
First: As it currently stands, the $User
variable does not have a .Users
property. In your code, $User
simply represents one line (the "current" line in the foreach loop) from the text file.
$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof
Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:
Get-ADUser
for each domain (you may have to specify alternate credentials via the -Credential
parameterThirdly, to get a list of groups that a user is a member of:
$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins
Fourthly: To get the final, desired string format, simply add the $User.Name
, a semicolon, and the $GroupMembership
string together:
$User.SamAccountName + ';' + $GroupMembership;
LIKE
is used for pattern matching and =
is used for equality test (as defined by the COLLATION
in use).
=
can use indexes while LIKE
queries usually require testing every single record in the result set to filter it out (unless you are using full text search) so =
has better performance.
Recent versions of Cordova have the version number in www/cordova.js.
I'm also struck with this same problem, finally i got simple solution. just added one line to action bar style.
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">@color/colorAccent</item>
<item name="android:colorBackground">@color/colorAppWhite</item>
</style>
"android:colorBackground" is enough to change option menu background
public Date addMonths(String dateAsString, int nbMonths) throws ParseException {
String format = "MM/dd/yyyy" ;
SimpleDateFormat sdf = new SimpleDateFormat(format) ;
Date dateAsObj = sdf.parse(dateAsString) ;
Calendar cal = Calendar.getInstance();
cal.setTime(dateAsObj);
cal.add(Calendar.MONTH, nbMonths);
Date dateAsObjAfterAMonth = cal.getTime() ;
System.out.println(sdf.format(dateAsObjAfterAMonth));
return dateAsObjAfterAMonth ;
}`
You can set any pointer to NULL
, though NULL
is simply defined as 0 in C++:
myObject *foo = NULL;
Also note that NULL
is defined if you include standard headers, but is not built into the language itself. If NULL
is undefined, you can use 0 instead, or include this:
#ifndef NULL
#define NULL 0
#endif
As an aside, if you really want to set an object, not a pointer, to NULL
, you can read about the Null Object Pattern.
There is timeline.sty floating around.
The syntax is simpler than using tikz:
%%% In LaTeX:
%%% \begin{timeline}{length}(start,stop)
%%% .
%%% .
%%% .
%%% \end{timeline}
%%%
%%% in plain TeX
%%% \timeline{length}(start,stop)
%%% .
%%% .
%%% .
%%% \endtimeline
%%% in between the two, we may have:
%%% \item{date}{description}
%%% \item[sortkey]{date}{description}
%%% \optrule
%%%
%%% the options to timeline are:
%%% length The amount of vertical space that the timeline should
%%% use.
%%% (start,stop) indicate the range of the timeline. All dates or
%%% sortkeys should lie in the range [start,stop]
%%%
%%% \item without the sort key expects date to be a number (such as a
%%% year).
%%% \item with the sort key expects the sort key to be a number; date
%%% can be anything. This can be used for log scale time lines
%%% or dates that include months or days.
%%% putting \optrule inside of the timeline environment will cause a
%%% vertical rule to be drawn down the center of the timeline.
I've used python's datetime.data.toordinal to convert dates to 'sort keys' in the context of the package.
I thought I would put a note here that explains a basic misconception for a lot of people who are using these Text Editors... Sublime Text in particular (or at least that's the one I use, so I don't know how it works for other editors):
There are "Themes" and there are "Color Schemes". They are similar but affect different things. "Themes" actively change the entire UI, and can include a Color Scheme if you set it up that way. This typically includes the sidebar, and can also include options for the file tabs, and some even include icons for the sidebar as well. And then we have "Color Schemes" which only change the coding windows and nothing else... not the Sidebar, nor the File tabs, etc.
The confusion happens because some people call Color Schemes "Themes" which makes folks think that their "Theme" is going to change everything.... when technically, it's just a color scheme.
And an additional note: Themes don't automatically install for all users. When I install a Theme, I have to open my User preferences (under "preferences > Settings - User"), and then you have to add the line which says something like:
"theme": "Theme-Name.sublime-theme"
(where "Theme-Name" is the name of your theme).
This is different than just activating a color scheme. If you've chosen a color scheme via the dropdown menus in Sublime Text, you will see a line in there like this:
"color_scheme": "Packages/Color-Scheme-Name.tmTheme"
(where "Color-Scheme-Name" is the name of your color scheme).
One can also use the following class while using bootstrap modal class (v 3.3.7) ... help-inline and help-block did not work in modal.
<span class="error text-danger">Some Errors related to something</span>
Output looks like something below:
<object>.__class__.__name__
You don't have a field named user_email
in the members table
... as for why, I'm not sure as the code "looks" like it should try to join on different fields
Does the Auth::attempt method perform a join of the schema?
Run grep -Rl 'class Auth' /path/to/framework
and find where the attempt
method is and what it does.
As mentioned in a comment above, you can have expressions within the template strings/literals. Example:
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
My solution in Header parameters with example is user="test" is:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){
System.out.println(headers.get("user"));
}
With PDO:
$pdo->lastInsertId();
With Mysqli:
$mysqli->insert_id;
Please, don't use mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
If you're using C# 7.1 or later, go with the nawfal's answer and just change the return type of your Main method to Task
or Task<int>
. If you are not:
async Task MainAsync
like Johan said..GetAwaiter().GetResult()
to catch the underlying exception like do0g said.CTRL+C
should terminate the process immediately. (Thanks binki!)OperationCancelledException
- return an appropriate error code.The final code looks like:
private static int Main(string[] args)
{
var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
{
e.Cancel = !cts.IsCancellationRequested;
cts.Cancel();
};
try
{
return MainAsync(args, cts.Token).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
return 1223; // Cancelled.
}
}
private static async Task<int> MainAsync(string[] args, CancellationToken cancellationToken)
{
// Your code...
return await Task.FromResult(0); // Success.
}
Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()
For more detail, see Class LinkedHashMap
interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:
readonly DateTime a = DateTime.Now;
I agree, if you have a const pre-defined array you might as well make it static. At that point you can use this interesting syntax:
//in header file
class a{
static const int SIZE;
static const char array[][10];
};
//in cpp file:
const int a::SIZE = 5;
const char array[SIZE][10] = {"hello", "cruel","world","goodbye", "!"};
however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.
Simply Use in Laravel Eloquent:
$a='foo', $b='bar', $c='john', $d='doe';
Coder::where(function ($query) use ($a, $b) {
$query->where('a', '=', $a)
->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
$query->where('c', '=', $c)
->orWhere('d', '=', $d);
})->get();
Will produce a query like:
SELECT * FROM <table> WHERE (a='foo' or b='bar') AND (c='john' or d='doe');
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
Step over the next function(F10)
button beside Resume(F8)
in the upper top center of the chrome until you freeze the popup you want to see. Try
os.path.getsize(filename)
It should return the size of a file, reported by os.stat().
This works pretty well
List<string> list = new List<string>();
list.Add("Hello");
list.Add("Who");
list.Add("Are");
list.Add("You");
foreach (String s in list)
{
Console.WriteLine(list[list.Count - list.IndexOf(s) - 1]);
}
Request timed out means that the local host did not receive a response from the destination host, but it was able to reach it. Destination host unreachable means that there was no valid route to the requested host.
This solves the problem on my end.
var files = sftp.ListDirectory(remoteVendorDirectory).Where(f => !f.IsDirectory);
foreach (var file in files)
{
var filename = $"{LocalDirectory}/{file.Name}";
if (!File.Exists(filename))
{
Console.WriteLine("Downloading " + file.FullName);
var localFile = File.OpenWrite(filename);
sftp.DownloadFile(file.FullName, localFile);
}
}
A simple solution to this console.log problem is to define the following at the beginning of your JS code:
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.
If the primary key happens to be an auto_increment value, you have to remove the auto increment, then drop the primary key then re-add the auto-increment
ALTER TABLE `xx`
MODIFY `auto_increment_field` INT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (new_primary_key);
then add back the auto increment
ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;
then set auto increment back to previous value
ALTER TABLE `xx` AUTO_INCREMENT = 5;
Bootstrap Modal Events:
<script type="text/javascript">
$("#salesitems_modal").on('hide.bs.modal', function () {
//actions you want to perform after modal is closed.
});
</script>
I hope this will Help.
Short answer:
:%s/string-to-be-searched//gn
For learning:
There are 3 modes in VI editor as below
:
you are entering from Command
to Command-line
mode. Now, whatever you write after :
is on CLI(Command Line Interface)%s
specifies all lines. Specifying the range as %
means do substitution in the entire file. Syntax for all occurrences substitution is :%s/old-text/new-text/g
g
specifies all occurrences in the line. With the g
flag , you can make the whole line to be substituted. If this g
flag is not used then only first occurrence in the line only will be substituted.n
specifies to output number of occurrences //
double slash represents omission of replacement text
. Because we just want to find.Once got the number of occurrences, you can Press N
Key to see occurrences one-by-one.
For finding and counting in particular range of line number 1 to 10:
:1,10s/hello//gn
%
for whole file is repleaced by ,
separated line numbers. For finding and replacing in particular range of line number 1 to 10:
:1,10s/helo/hello/gn
You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ]
will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ]
.
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)
In your case, I would use shell form
ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"
With this solution you can fully enable/disable the security by activating a specific profile by command line. I defined the profile in a file application-nosecurity.yaml
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Then I modified my custom WebSecurityConfigurerAdapter
by adding the @Profile("!nosecurity")
as follows:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Profile("!nosecurity")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {...}
To fully disable the security it's enough to start the application up by specifying the nosecurity profile, i.e.:
java -jar target/myApp.jar --spring.profiles.active=nosecurity
The following code assumes that your table has the ID 'MyTable'
<script language="JavaScript"> <!-- var oRows = document.getElementById('MyTable').getElementsByTagName('tr'); var iRowCount = oRows.length; alert('Your table has ' + iRowCount + ' rows.'); //--> </script>
Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)
I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net
Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.
My recomendation is to keep the getRuntime().exec
because exec
uses the ProcessBuilder
.
Try
p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);
I believe this is what you're looking for. It automatically scaled the video to fit the container.
DEMO: http://jsfiddle.net/t8qhgxuy/
Video need to have height and width always set to 100% of the parent.
HTML:
<div class="one"> CONTENT OVER VIDEO
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>
<div class="two">
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>
CSS:
body {
overflow: scroll;
padding: 60px 20px;
}
.one {
width: 90%;
height: 30vw;
overflow: hidden;
border: 15px solid red;
margin-bottom: 40px;
position: relative;
}
.two{
width: 30%;
height: 300px;
overflow: hidden;
border: 15px solid blue;
position: relative;
}
.video-background { /* class name used in javascript too */
width: 100%; /* width needs to be set to 100% */
height: 100%; /* height needs to be set to 100% */
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
JS:
function scaleToFill() {
$('video.video-background').each(function(index, videoTag) {
var $video = $(videoTag),
videoRatio = videoTag.videoWidth / videoTag.videoHeight,
tagRatio = $video.width() / $video.height(),
val;
if (videoRatio < tagRatio) {
val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
} else if (tagRatio < videoRatio) {
val = videoRatio / tagRatio * 1.02;
}
$video.css('transform','scale(' + val + ',' + val + ')');
});
}
$(function () {
scaleToFill();
$('.video-background').on('loadeddata', scaleToFill);
$(window).resize(function() {
scaleToFill();
});
});
Version 1 is preferable because it is shorter and the compiler will in fact turn it into version 2 - no performance difference whatsoever.
More importantly given we have only 3 properties it might not make a difference, but at what point do you switch from concat to builder?
At the point where you're concatenating in a loop - that's usually when the compiler can't substitute StringBuilder
by itself.
To rename an image, you give it a new tag, and then remove the old tag using the ‘rmi’ command:
$ docker tag $ docker rmi
This second step is scary, as ‘rmi’ means “remove image”. However, docker won’t actually remove the image if it has any other tags. That is, if you were to immediately follow this with: docker rmi , then it would actually remove the image (assuming there are no other tags assigned to the image)
The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization
header with the Bearer
authentication scheme.
This scheme is described by the RFC6750.
Example:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ
If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.
Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.
Unlike the custom JWT
scheme you mention in your question, the Bearer
one is registered at the IANA.
Concerning the Basic
and Digest
authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.
For me, this error was happening on localhost, but it disappeared when routing it through ngrok and was replaced with a MUCH more helpful error (net::ERR_INCOMPLETE_CHUNKED_ENCODING) that led me here:
https://stackoverflow.com/a/29969400
Basically, the Kestrel server I was using was saying it was chunked output, but not terminating it properly. I double checked it with Fiddler which confirmed the error.
Really, there isn't. there are about a half-zillion different regex syntaxes; they seem to come down to Perl, EMACS/GNU, and AT&T in general, but I'm always getting surprised too.
var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'
$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);
I put them on two separate lines to make the code a little more clear.
Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z
.
I have tried to rename the repository on the web page:
setting
, click it and then you can find the Repositories
under the Personal setting
. Repositories
and enter your directories of Repositories, choose the Repository that you want to rename. setting
is added to the top line, just click it and enter the new name then click Rename
. Done, so easy.
int count = 0;
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
connection.Open();
count = (int32)cmd.ExecuteScalar();
}
In case of circle all you need is one div, but in case of hollow square you need to have 2 divs. The divs are having a display of inline-block which you can change accordingly. Live Codepen link: Click Me
In case of circle all you need to change is the border properties and the dimensions(width and height) of circle. If you want to change color just change the border color of hollow-circle.
In case of the square background-color property needs to be changed depending upon the background of page or the element upon which you want to place the hollow-square. Always keep the inner-circle dimension small as compared to the hollow-square. If you want to change color just change the background-color of hollow-square. The inner-circle is centered upon the hollow-square using the position, top, left, transform properties just don't mess with them.
Code is as follows:
/* CSS Code */_x000D_
_x000D_
.hollow-circle {_x000D_
width: 4rem;_x000D_
height: 4rem;_x000D_
background-color: transparent;_x000D_
border-radius: 50%;_x000D_
display: inline-block;_x000D_
_x000D_
/* Use this */_x000D_
border-color: black;_x000D_
border-width: 5px;_x000D_
border-style: solid;_x000D_
/* or */_x000D_
/* Shorthand Property */_x000D_
/* border: 5px solid #000; */_x000D_
}_x000D_
_x000D_
.hollow-square {_x000D_
position: relative;_x000D_
width: 4rem;_x000D_
height: 4rem;_x000D_
display: inline-block;_x000D_
background-color: black;_x000D_
}_x000D_
_x000D_
.inner-circle {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
width: 3rem;_x000D_
height: 3rem;_x000D_
border-radius: 50%;_x000D_
background-color: white;_x000D_
}
_x000D_
<!-- HTML Code -->_x000D_
_x000D_
<div class="hollow-circle">_x000D_
</div>_x000D_
_x000D_
<br/><br/><br/>_x000D_
_x000D_
<div class="hollow-square">_x000D_
<div class="inner-circle"></div>_x000D_
</div>
_x000D_
I do like this:
var dados = from d in dc.tbl_News.Take(4)
orderby d.idNews descending
select new
{
d.idNews,
d.titleNews,
d.textNews,
d.dateNews,
d.imgNewsThumb
};
This is by far the best SQLite library that I've used in Swift: https://github.com/stephencelis/SQLite.swift
Look at the code examples. So much cleaner than the C API:
import SQLite
let db = try Connection("path/to/db.sqlite3")
let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")
try db.run(users.create { t in
t.column(id, primaryKey: true)
t.column(name)
t.column(email, unique: true)
})
// CREATE TABLE "users" (
// "id" INTEGER PRIMARY KEY NOT NULL,
// "name" TEXT,
// "email" TEXT NOT NULL UNIQUE
// )
let insert = users.insert(name <- "Alice", email <- "[email protected]")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', '[email protected]')
for user in try db.prepare(users) {
print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
// id: 1, name: Optional("Alice"), email: [email protected]
}
// SELECT * FROM "users"
let alice = users.filter(id == rowid)
try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
// WHERE ("id" = 1)
try db.run(alice.delete())
// DELETE FROM "users" WHERE ("id" = 1)
try db.scalar(users.count) // 0
// SELECT count(*) FROM "users"
The documentation also says that "SQLite.swift also works as a lightweight, Swift-friendly wrapper over the C API," and follows with some examples of that.
Have you used the variable sum
anywhere else? That would explain it.
>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
The name sum
doesn't point to the function anymore now, it points to an integer.
Solution: Don't call your variable sum
, call it total
or something similar.
AppStore >> iosAPP >> Build (scroll down)
click the red icon as seen in the picture
Have you tried to edit to see what's wrong (I had the wrong image location)
kubectl edit pods arix-3-yjq9w
or even delete your pod?
kubectl delete arix-3-yjq9w
<input type= "image" id=" " onclick=" " src=" " />
it works.
There newer ways to connect Node.js and C++. Please, loot at Nan.
EDIT
The fastest and easiest way is nbind. If you want to write asynchronous add-on you can combine Asyncworker
class from nan.
None of those answers are working for me (either generating a 500 error or doing nothing). That is probably due to the fact that I'm working on a hosted server where I can't have access to Apache configuration.
But this worked for me :
RewriteRule ^.*\.php$ - [F,L]
This line will generate a 403 Forbidden error for any URL that ends with .php
and ends up in this subdirectory.
@Oussama lead me to the right direction here, thanks to him.
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
@BrenBarn's answer says it all, but if you're like me it might take a while to understand. Here's my case and how @BrenBarn's answer applies to it, perhaps it will help you.
The case
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleA.py
Using our familiar example, and add to it that moduleX.py has a relative import to ..moduleA. Given that I tried writing a test script in the subpackage1 directory that imported moduleX, but then got the dreaded error described by the OP.
Solution
Move test script to the same level as package and import package.subpackage1.moduleX
Explanation
As explained, relative imports are made relative to the current name. When my test script imports moduleX from the same directory, then module name inside moduleX is moduleX. When it encounters a relative import the interpreter can't back up the package hierarchy because it's already at the top
When I import moduleX from above, then name inside moduleX is package.subpackage1.moduleX and the relative import can be found
When I experienced this error, it was due to having been in Keychain Access, and choosing 'Disallow' when asked whether I wanted to let the program access a saved password. Going back in and selecting 'Allow' and typing my system password fixed the problem in XCode.
Use this way,
int orientation = getResources().getConfiguration().orientation;
String Orintaion = "";
switch (orientation)
{
case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
case Configuration.ORIENTATION_PORTRAIT: Orintaion = "Portrait"; break;
default: Orintaion = "Square";break;
}
in the String you have the Oriantion
A simple rewrite of @Landons MY_Loader, to include multiple files for the body, e.i. page unique sidebars...
<?php
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
$content = $this->view('frontend/templates/header', $vars, $return);
if(is_array($template_name)) { //return all values in contents
foreach($template_name as $file_to_load) {
$content .= $this->view('frontend/'.$file_to_load, $vars, $return);
}
}
else {
$content .= $this->view('frontend/'.$template_name, $vars, $return);
}
$content .= $this->view('frontend/templates/footer', $vars, $return);
if ($return)
{
return $content;
}
}
}
This works both ways...
Including one file to template:
$data['moo'] = 'my data'];
$this->load->template('home', $data);
Include multiple files to template:
$data['catalog'] = 'catalog load 1';
$data['sidebar'] = 'sidebar load 2';
$load = array('catalog/catalog', 'catalog/sidebar');
$this->load->template($load, $data);
Note your code contains Dir("thesentence")
which should be Dir(thesentence)
.
Change your code to this
Sub test()
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
A simple Expect script:
#!/usr/bin/expect
set user [lindex $argv 1]
set ip [lindex $argv 0]
set password [lindex $argv 2]
spawn ssh $user@$ip
expect "password"
send "$password\r"
interact
Example:
./Remotelogin.exp <ip> <user name> <password>
What about:
select *, max(id) from messages group by name
I have tested it on sqlite and it returns all columns and max id value for all names.
Using HTML5 and the File API
The images sources will be a URL representing the Blob object
<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">
const EL_browse = document.getElementById('browse');_x000D_
const EL_preview = document.getElementById('preview');_x000D_
_x000D_
const readImage = file => {_x000D_
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);_x000D_
_x000D_
const img = new Image();_x000D_
img.addEventListener('load', () => {_x000D_
EL_preview.appendChild(img);_x000D_
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);_x000D_
window.URL.revokeObjectURL(img.src); // Free some memory_x000D_
});_x000D_
img.src = window.URL.createObjectURL(file);_x000D_
}_x000D_
_x000D_
EL_browse.addEventListener('change', ev => {_x000D_
EL_preview.innerHTML = ''; // Remove old images and data_x000D_
const files = ev.target.files;_x000D_
if (!files || !files[0]) return alert('File upload not supported');_x000D_
[...files].forEach( readImage );_x000D_
});
_x000D_
#preview img { max-height: 100px; }
_x000D_
<input id="browse" type="file" multiple>_x000D_
<div id="preview"></div>
_x000D_
In case you need images sources as long Base64 encoded data strings
<img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">
const EL_browse = document.getElementById('browse');_x000D_
const EL_preview = document.getElementById('preview');_x000D_
_x000D_
const readImage = file => {_x000D_
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )_x000D_
return EL_preview.insertAdjacentHTML('beforeend', `<div>Unsupported format ${file.type}: ${file.name}</div>`);_x000D_
_x000D_
const reader = new FileReader();_x000D_
reader.addEventListener('load', () => {_x000D_
const img = new Image();_x000D_
img.addEventListener('load', () => {_x000D_
EL_preview.appendChild(img);_x000D_
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);_x000D_
});_x000D_
img.src = reader.result;_x000D_
});_x000D_
reader.readAsDataURL(file); _x000D_
};_x000D_
_x000D_
EL_browse.addEventListener('change', ev => {_x000D_
EL_preview.innerHTML = ''; // Clear Preview_x000D_
const files = ev.target.files;_x000D_
if (!files || !files[0]) return alert('File upload not supported');_x000D_
[...files].forEach( readImage );_x000D_
});
_x000D_
#preview img { max-height: 100px; }
_x000D_
<input id="browse" type="file" multiple>_x000D_
<div id="preview"></div>_x000D_
_x000D_
You should install this Apache mod, http://httpd.apache.org/docs/2.0/mod/mod_info.html, it basically gives you a run down of the mods you're using and the Apache settings. I have this enabled on my Apache and it gives me this info for my website,
Server Version: Apache/2.2.3 (Debian) mod_jk/1.2.18 PHP/5.2.0-8+etch13 mod_ssl/2.2.3 OpenSSL/0.9.8c mod_perl/2.0.2 Perl/v5.8.8
If you need the functionality if a index for a column exists (here at first place in sequence) as a database function you can use/adopt this code. If you want to check if an index exists at all regardless of the position in a multi-column-index, then just delete the part "AND SEQ_IN_INDEX = 1".
DELIMITER $$
CREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(
`IN_SCHEMA` VARCHAR(255),
`IN_TABLE` VARCHAR(255),
`IN_COLUMN` VARCHAR(255)
)
RETURNS tinyint(4)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'
BEGIN
-- Check if index exists at first place in sequence for a given column in a given table in a given schema.
-- Returns -1 if schema does not exist.
-- Returns -2 if table does not exist.
-- Returns -3 if column does not exist.
-- If the index exists in first place it returns 1, otherwise 0.
-- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');
-- check if schema exists
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
INFORMATION_SCHEMA.SCHEMATA
WHERE
SCHEMA_NAME = IN_SCHEMA
;
IF @COUNT_EXISTS = 0 THEN
RETURN -1;
END IF;
-- check if table exists
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
;
IF @COUNT_EXISTS = 0 THEN
RETURN -2;
END IF;
-- check if column exists
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
AND COLUMN_NAME = IN_COLUMN
;
IF @COUNT_EXISTS = 0 THEN
RETURN -3;
END IF;
-- check if index exists at first place in sequence
SELECT
COUNT(*) INTO @COUNT_EXISTS
FROM
information_schema.statistics
WHERE
TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN
AND SEQ_IN_INDEX = 1;
IF @COUNT_EXISTS > 0 THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
END$$
DELIMITER ;
There are some good answers already with explanations of why the mixture of the non-static Context
method getText()
can't be used with your static final String
.
A good question to ask is: why do you want to do this? You are attempting to load a String
from your strings
resource, and populate its value into a public static
field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context
into your other classes and call context.getText(R.string.TTT)
from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity
:
NonActivity.doStuff(this);
This will allow you to access your String
resource without needing to use a public static
field.
Some people suggested to use an awesome tool - Reference Assistant for Visual Studio. The problem is that VS2012 is the latest supported Visual Studio. But there is the way to make it work in VS2013 as well ;)
And here is how:
1) Download Lardite.RefAssistant.11.0.vsix
2) Change the extension to zip: Lardite.RefAssistant.11.0.vsix
-> Lardite.RefAssistant.11.0.zip
3) Unzip and open the extension.vsixmanifest
file in the text editor
4) Find all occurences of InstallationTarget Version="[11.0,12.0)"
and replace them with InstallationTarget Version="[11.0,12.0]"
(note the closing bracket)
5) Save the file and zip all files so they are on the root zip level
6) Change the extension of the new zip
to vsix
7) Install and enjoy :)
I've tested it with VS2013, thanks source for the tutorial
EDIT Add to support VS 2015 Community Edition
<InstallationTarget Version="[14.0,15.0]" Id="Microsoft.VisualStudio.Community" />
Meaning of the brackets
[ – minimum version inclusive.
] – maximum version inclusive.
( – minimum version exclusive.
) – maximum version exclusive.
You can do this by using asynchronous Javascript SDK provided by facebook
Have a look at the following code
FB Javascript SDK initialization
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Note: Remember to replace YOUR APP ID with your facebook AppId. If you don't have facebook AppId and you don't know how to create please check this
Add JQuery Library, I would preferred Google Library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
Add share dialog box (You can customize this dialog box by setting up parameters
<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'http://www.groupstudy.in/articlePost.php?id=A_111213073144',
picture: 'http://www.groupstudy.in/img/logo3.jpeg',
caption: 'Top 3 reasons why you should care about your finance',
description: "What happens when you don't take care of your finances? Just look at our country -- you spend irresponsibly, get in debt up to your eyeballs, and stress about how you're going to make ends meet. The difference is that you don't have a glut of taxpayers…",
message: ""
});
});
});
</script>
Now finally add image button
<img src = "share_button.png" id = "share_button">
For more detailed kind of information. please click here
Copy to a Date variable then transform it into Text with format()
. Example:
Function GetMyTimeField()
Dim myTime As Date, myStrTime As String
myTime = [A1]
myStrTime = Format(myTime, "hh:mm")
Debug.Print myStrTime & " Nice!"
End Function
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
Don't forget to go to your device and enable Settings->Developer Options->USB debugging.
For the best practice - use style="display:"
it will work every where..
If you have custom defines and want to save them before cleaning, run the following in your build directory:
sed -ne '/variable specified on the command line/{n;s/.*/-D \0 \\/;p}' CMakeCache.txt
Then create a new build directory (or remove the old build directory and recreate it) and finally run cmake
with the arguments you'll get with the script above.
I was looking to do exactly the same thing (RESTful web service), and I stumbled upon this firefox addon, which lets you modify the accept headers (actually, any request headers) for requests. It works perfectly.
So what is the URL that Yii::app()->params['pdfUrl']
gives? You say it should be https, but the log shows it's connecting on port 80... which almost no server is setup to accept https connections on. cURL is smart enough to know https should be on port 443... which would suggest that your URL has something wonky in it like: https://196.41.139.168:80/serve/?r=pdf/generatePdf
That's going to cause the connection to be terminated, when the Apache at the other end cannot do https communication with you on that port.
You realize your first $body
definition gets replaced when you set $body
to an array two lines later? {Probably just an artifact of you trying to solve the problem} You're also not encoding the client_url
and client_id
values (the former quite possibly containing characters that need escaping!) Oh and you're appending to $body_str
without first initializing it.
From your verbose output we can see cURL is adding a content-length
header, but... is it correct? I can see some comments out on the internets of that number being wrong (especially with older versions)... if that number was to small (for example) you'd get a connection-reset before all the data is sent. You can manually insert the header:
curl_setopt ($c, CURLOPT_HTTPHEADER,
array("Content-Length: ". strlen($body_str)));
Oh and there's a handy function http_build_query
that'll convert an array of name/value pairs into a URL encoded string for you.
All this rolls up into the final code:
$post=http_build_query(array(
"client_url"=>Yii::app()->params['pdfClientURL'],
"client_id"=>Yii::app()->params['pdfClientID'],
"title"=>$title,
"content"=>$content));
//Open to URL
$c=curl_init(Yii::app()->params['pdfUrl']);
//Send post
curl_setopt ($c, CURLOPT_POST, true);
//Optional: [try with/without]
curl_setopt ($c, CURLOPT_HTTPHEADER, array("Content-Length: ".strlen($post)));
curl_setopt ($c, CURLOPT_POSTFIELDS, $post);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT , 20);
//Collect result
$pdf = curl_exec ($c);
$curlInfo = curl_getinfo($c);
curl_close($c);
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
Documentation: Convert JSON to a Type
Concat
returns a new sequence without modifying the original list. Try myList1.AddRange(myList2)
.
<sonar.language>java</sonar.language>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.jacoco.reportPath>${user.dir}/target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.jacoco.itReportPath>${user.dir}/target/jacoco-it.exec</sonar.jacoco.itReportPath>
<sonar.exclusions>
file:**/target/generated-sources/**,
file:**/target/generated-test-sources/**,
file:**/target/test-classes/**,
file:**/model/*.java,
file:**/*Config.java,
file:**/*App.java
</sonar.exclusions>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
<append>true</append>
<propertyName>surefire.argLine</propertyName>
</configuration>
</execution>
<execution>
<id>default-prepare-agent-integration</id>
<goals>
<goal>prepare-agent-integration</goal>
</goals>
<configuration>
<destFile>${sonar.jacoco.itReportPath}</destFile>
<append>true</append>
<propertyName>failsafe.argLine</propertyName>
</configuration>
</execution>
<execution>
<id>default-report</id>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-report-integration</id>
<goals>
<goal>report-integration</goal>
</goals>
</execution>
</executions>
</plugin>
Include both class strings in a single class attribute value, with a space in between.
<a class="c1 c2" > aa </a>
using system ping command to ping a list of hosts:
import re
from subprocess import Popen, PIPE
from threading import Thread
class Pinger(object):
def __init__(self, hosts):
for host in hosts:
pa = PingAgent(host)
pa.start()
class PingAgent(Thread):
def __init__(self, host):
Thread.__init__(self)
self.host = host
def run(self):
p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
m = re.search('Average = (.*)ms', p.stdout.read())
if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
else: print 'Error: Invalid Response -', self.host
if __name__ == '__main__':
hosts = [
'www.pylot.org',
'www.goldb.org',
'www.google.com',
'www.yahoo.com',
'www.techcrunch.com',
'www.this_one_wont_work.com'
]
Pinger(hosts)
A simple JavaScript function will do the job.
function ClearFields() {
document.getElementById("textfield1").value = "";
document.getElementById("textfield2").value = "";
}
And just have your button call it:
<button type="button" onclick="ClearFields();">Clear</button>
If you knew the Class
of ImplementationType
you could create an instance of it. So what you are trying to do is not possible.
Here's a more technical and thorough answer to an old question: Visual Basic for Applications (VBA) and Visual Basic (pre-.NET) are not just similar languages, they are the same language. Specifically:
In an old VB reference book I came across last year, the author (Paul Lomax) even asserted that 'VBA' has always been the name of the language itself, whether used in stand-alone applications or in embedded contexts (such as MS Office):
"Before we go any further, let's just clarify on fundamental point. Visual Basic for Applications (VBA) is the language used to program in Visual Basic (VB). VB itself is a development environment; the language element of that environment is VBA."
The minor differences
Hosted vs. stand-alone: In practical, terms, when most people say "VBA" they specifically mean "VBA when used in MS Office", and they say "VB6" to mean "VBA used in the last version of the standalone VBA compiler (i.e. Visual Studio 6)". The IDE and compiler bundled with MS Office is almost identical to Visual Studio 6, with the limitation that it does not allow compilation to stand-alone dll or exe files. This in turns means that classes defined in embedded VBA projects are not accessible from non-embedded COM consumers, because they cannot be registered.
Continued development: Microsoft stopped producing a stand-alone VBA compiler with Visual Studio 6, as they switched to the .NET runtime as the platform of choice. However, the MS Office team continues to maintain VBA, and even released a new version (VBA7) with a new VM (now just called VBA7.dll) starting with MS Office 2010. The only major difference is that VBA7 has both a 32- and 64-bit version and has a few enhancements to handle the differences between the two, specifically with regards to external API invocations.
They can be considered as equivalent. The limits in size are the same:
There is also the DBCLOBs, for double byte characters.
References:
There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
which pip2.7
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
Now, you should be all set, and
which pip2.7
should return the correct output.
"Select your text, right click, then choose
Style Token
and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."
It should be default, but it might be hidden.
"It might be that something happened to your
contextMenu.xml
so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\
) if thecontextMenu.xml
is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at thecontextmenu.xml
itself - because you're allowed to change it to your own needs."
See this for more information
Try to use this , it works perfectly for me
//
varb = new List<object>();
// Example
varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});
// JSON + Serializ
public string Json()
{
return (new JavaScriptSerializer()).Serialize(varb);
}
// Jquery SIDE
var datasets = {
"Products": {
label: "Products",
data: <%= getJson() %>
}
In most languages i am aware of, the actual regex for validating should be
^[0-9]{1,10}$
; otherwise the matcher will also return positive matches if the to be validated number is part of a longer string.
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
You can cut the url and use response.sendredirect(new url), this will bring you to the same page with the new url
Use "E"
See the section on Date and Time Patterns:
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
In the same spirit as https://stackoverflow.com/a/6943976/7154924:
cat -A
-A, --show-all
equivalent to -vET
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
-E, --show-ends
display $ at end of each line
-T, --show-tabs
display TAB characters as ^I
Alternatively, or at the same time, you can pipe to tr
to substitute arbitrary characters to the desired ones for display, before piping to a pager like less
if desired.
Use and empty()
whit negation (for test if not empty)
if(!empty($_GET['id'])) {
// if get id is not empty
}
Scenario:
I have a navigation menu like this. Note: Link <a> is child of list item <li>
. I wanted to change the background of the selected list item and remove the background color of unselected list item.
<nav>
<ul>
<li><a href="#">Intro</a></li>
<li><a href="#">Size</a></li>
<li><a href="#">Play</a></li>
<li><a href="#">Food</a></li>
</ul>
<div class="clear"></div>
</nav>
I tried to add a class .active into the list item using jQuery but it was not working
.active
{
background-color: #480048;
}
$("nav li a").click(function () {
$(this).parent().addClass("active");
$(this).parent().siblings().removeClass("active");
});
Solution:
Basically, using .active class changing the background-color of list item does not work. So I changed the css class name from .active to "nav li.active a" so using the same javascript it will add the .active class into the selected list item. Now if the list item <li>
has .active class then css will change the background color of the child of that list item <a>.
nav li.active a
{
background-color: #480048;
}
If you have this:
<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>
And you only want to select the elements which have .x
and (.a
or .b
), you could write:
.x:not(.c) { ... }
but that's convenient only when you have three "sub-classes" and you want to select two of them.
Selecting only one sub-class (for instance .a
): .a.x
Selecting two sub-classes (for instance .a
and .b
): .x:not(.c)
Selecting all three sub-classes: .x
In general use serialize()
on the form element.
Please be mindful that multiple <select> options are serialized under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.
int myInt = (int)round( [@"1.6" floatValue] );
NSString* myString = [@(myInt) description];
(Boxes it up as a NSNumber and converts to a string using the NSObjects' description method)
Looking for similar problem I found this - http://www.indigorose.com/forums/archive/index.php/t-13334.html
A4 is a document format, as a screen image that's going to depend on the image resolution, for example an A4 document resized to:
For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:
.
For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
Note: Observe Daniel Galasko's comment below regarding naming
First add Dimension component:
import { AppRegistry, Text, View,Dimensions } from 'react-native';
Second define Variables:
var height = Dimensions.get('window').height;
var width = Dimensions.get('window').width;
Third put it in your stylesheet:
textOutputView: {
flexDirection:'row',
paddingTop:20,
borderWidth:1,
borderColor:'red',
height:height*0.25,
backgroundColor:'darkgrey',
justifyContent:'flex-end'
}
Actually in this example I wanted to make responsive view and wanted to view only 0.25 of the screen view so I multiplied it with 0.25, if you wanted 100% of the screen don't multiply it with any thing like this:
textOutputView: {
flexDirection:'row',
paddingTop:20,
borderWidth:1,
borderColor:'red',
height:height,
backgroundColor:'darkgrey',
justifyContent:'flex-end'
}
The simplest method is just to use the +
operator, which returns the concatenation of the lists:
concat = first_list + second_list
One disadvantage of this method is that twice the memory is now being used . For very large lists, depending on how you're going to use it once it's created, itertools.chain
might be your best bet:
>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)
This creates a generator for the items in the combined list, which has the advantage that no new list needs to be created, but you can still use c
as though it were the concatenation of the two lists:
>>> for i in c:
... print i
1
2
3
4
5
6
If your lists are large and efficiency is a concern then this and other methods from the itertools
module are very handy to know.
Note that this example uses up the items in c
, so you'd need to reinitialise it before you can reuse it. Of course you can just use list(c)
to create the full list, but that will create a new list in memory.
we have to enable TCP/IP property in sql server configuration manager
install json-loader
:
npm i json-loader --save
create data
folder in src
:
mkdir data
put your file(s) there
load your file
var data = require('json!../data/yourfile.json');
You can also use scipy.signal.welch to estimate the power spectral density using Welch’s method. Here is an comparison between np.fft.fft and scipy.signal.welch:
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
fs = 10e3
N = 1e5
amp = 2*np.sqrt(2)
freq = 1234.0
noise_power = 0.001 * fs / 2
time = np.arange(N) / fs
x = amp*np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
# np.fft.fft
freqs = np.fft.fftfreq(time.size, 1/fs)
idx = np.argsort(freqs)
ps = np.abs(np.fft.fft(x))**2
plt.figure()
plt.plot(freqs[idx], ps[idx])
plt.title('Power spectrum (np.fft.fft)')
# signal.welch
f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum')
plt.figure()
plt.semilogy(f, np.sqrt(Pxx_spec))
plt.xlabel('frequency [Hz]')
plt.ylabel('Linear spectrum [V RMS]')
plt.title('Power spectrum (scipy.signal.welch)')
plt.show()
It has to do with BASE: the BASE jumper kind is always Basically Available (to new relationships), in a Soft state (none of his relationship last very long) and Eventually consistent (one day he will get married).
You can put an @ in front of your function call to suppress all error messages.
@yourFunctionHere();
Based on a comment in another answer, here's my shell function.
# mvp = move + create parents
function mvp () {
source="$1"
target="$2"
target_dir="$(dirname "$target")"
mkdir --parents $target_dir; mv $source $target
}
Include this in .bashrc or similar so you can use it everywhere.
Seems like this sounds more complicated than it is...
Dim myArray As String() = TextBox1.Lines
'First we count how many null elements there are...
Dim Counter As Integer = 0
For x = 0 To myArray.Count - 1
If Len(myArray(x)) < 1 Then
Counter += 1
End If
Next
'Then we dimension an array to be the size of the last array
'minus the amount of nulls found...
Dim tempArr(myArray.Count - Counter) As String
'Indexing starts at zero, so let's set the stage for that...
Counter = -1
For x = 0 To myArray.Count - 1
'Set the conditions for the new array as in
'It .contains("word"), has no value, length is less than 1, ect.
If Len(myArray(x)) > 1 Then
Counter += 1
'So if a value is present, we move that value over to
'the new array.
tempArr(Counter) = myArray(x)
End If
Next
Now you can assign tempArr back to the original or what ever you need done with it as in...
TextBox1.Lines = tempArr (You now have a textbox void of blank lines)
select()
is a bit too low-level for convenience. I suggest you use the ncurses
library to put the terminal in cbreak mode and delay mode, then call getch()
, which will return ERR
if no character is ready:
WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);
At that point you can call getch
without blocking.
Consider this:
file a.txt:
abcd
efgh
file b.txt:
abcd
You can find the difference with:
diff -a --suppress-common-lines -y a.txt b.txt
The output will be:
efgh
You can redirict the output in an output file (c.txt) using:
diff -a --suppress-common-lines -y a.txt b.txt > c.txt
This will answer your question:
"...which contains the lines in file1 which are not present in file2."
Could they make it any harder? Here's what I did: open system properties, click on advanced, add the environment variable, shut down visual studio and start it up again.
The simplest way to display last element in python is
>>> list[-1:] # returns indexed value
[3]
>>> list[-1] # returns value
3
there are many other method to achieve such a goal but these are short and sweet to use.
I think op wants to know what the font that is used on a webpage is, and hoped that info might be findable in the 'inspect' pane.
Try adding the Whatfont Chrome extension.
I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.
As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.
My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(i) & set(c1)) for i in c2]
c3
[[32, 13], [28, 13, 7], [1, 6]]
For me this is very elegant and quick way to to it :)
Java doesn't support default parameters. You will need to have two constructors to do what you want.
An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.
e.g.
public class Foo {
private final String param1;
private final String param2;
private Foo(Builder builder) {
this.param1 = builder.param1;
this.param2 = builder.param2;
}
public static class Builder {
private String param1 = "defaultForParam1";
private String param2 = "defaultForParam2";
public Builder param1(String param1) {
this.param1 = param1;
return this;
}
public Builder param2(String param1) {
this.param2 = param2;
return this;
}
public Foo build() {
return new Foo(this);
}
}
}
which allows you to say:
Foo myFoo = new Foo.Builder().param1("myvalue").build();
which will have a default value for param2
.
document.getElementsByName("name")
will get several elements called by same name .
document.getElementsByName("name")[Number]
will get one of them.
document.getElementsByName("name")[Number].value
will get the value of paticular element.
The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.
When you use mysql_fetch_object
, you get an object (of class stdClass) with all fields for the row inside of it.
Use mysql_fetch_field
instead of mysql_fetch_object
, that will give you the first field of the result set (id
in your case). The docs are here
Comparing 2 arrays:
var arr1 = [1,2,3];
var arr2 = [1,2,3];
function compare(arr1,arr2)
{
if((arr1 == arr2) && (arr1.length == arr2.length))
return true;
else
return false;
}
calling function
var isBool = compare(arr1.sort().join(),arr2.sort().join());
the class is called:
.form-control { border-radius: 0; }
be sure to insert the override after including bootstraps css.
If you ONLY want to remove the radius on select form-controls use
select.form-control { ... }
instead
EDIT: works for me on chrome, firefox, opera, and safari, IE9+ (all running on linux/safari & IE on playonlinux)
window.location.href = "webpage.htm";
hash_map
was a common extension provided by many library implementations. That is exactly why it was renamed to unordered_map
when it was added to the C++ standard as part of TR1. map is generally implemented with a balanced binary tree like a red-black tree (implementations vary of course). hash_map
and unordered_map
are generally implemented with hash tables. Thus the order is not maintained. unordered_map
insert/delete/query will be O(1) (constant time) where map will be O(log n) where n is the number of items in the data structure. So unordered_map
is faster, and if you don't care about the order of the items should be preferred over map
. Sometimes you want to maintain order (ordered by the key) and for that map
would be the choice.
this works:
window.onscroll = function (e) {
// called when the window is scrolled.
}
edit:
you said this is a function in a TimeInterval..
Try doing it like so:
userHasScrolled = false;
window.onscroll = function (e)
{
userHasScrolled = true;
}
then inside your Interval insert this:
if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}
WARNING: slaveOk() is deprecated and may be removed in the next major release. Please use secondaryOk() instead. rs.secondaryOk()
Run msbuild Foo.sln /t:Rebuild /v:diag
(from C:\Program Files (x86)\MSBuild\12.0\bin
) to build your solution from command line and get a bit more details, then find the .csproj.
that logs the warning and check its references and references of other projects that use the same common assembly that differs in version.
Edit: You can also set the build verbosity directly in VS2013. Go to Tools
> Options
menu then go to Projects and Solutions
and set MSBuild verbosity to Diagnostic
.
Edit: Few clarifications as I just got one myself. In my case warning was due to me adding a reference using Resharper prompt as opposed to the Add Reference dialog, which did it versionless even though both v4 and v12 are available to choose from.
<Reference Include="Microsoft.Build, Version=12.0.0.0, ..." />
<Reference Include="Microsoft.Build.Framework" />
vs
<Reference Include="Microsoft.Build, Version=12.0.0.0, ..." />
<Reference Include="Microsoft.Build.Framework, Version=12.0.0.0, ..." />
In the MSBuild log with /v:diag
verbosity it looked like the following. giving details which two references conflicted:-
There was a conflict between
"Microsoft.Build.Framework, Version=4.0.0.0, ..." and
"Microsoft.Build.Framework, Version=12.0.0.0, ...". (TaskId:16)
"Microsoft.Build.Framework, Version=4.0.0.0, ..." was chosen because it was primary and
"Microsoft.Build.Framework, Version=12.0.0.0, ..." was not. (TaskId:16)
References which depend on "Microsoft.Build.Framework, Version=4.0.0.0, ..."
[C:\...\v4.5.1\Microsoft.Build.Framework.dll]. (TaskId:16)
C:\...\v4.5.1\Microsoft.Build.Framework.dll (TaskId:16)
Project file item includes which caused reference "C:\...\v4.5.1\Microsoft.Build.Framework.dll". (TaskId:16)
Microsoft.Build.Framework (TaskId:16)
References which depend on "Microsoft.Build.Framework, Version=12.0.0.0, ..."
[C:\...\v12.0\Microsoft.Build.Framework.dll]. (TaskId:16)
C:\...\v12.0\Microsoft.Build.dll (TaskId:16)
Project file item includes which caused reference "C:\...\v12.0\Microsoft.Build.dll". (TaskId:16)
Microsoft.Build, Version=12.0.0.0, ... (TaskId:16)
C:\...\v12.0\Microsoft.Build.Engine.dll (TaskId:16)
Project file item includes which caused reference "C:\...\v12.0\Microsoft.Build.Engine.dll". (TaskId:16)
Microsoft.Build, Version=12.0.0.0, ... (TaskId:16)
C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(1697,5): warning MSB3277:
Found conflicts between different versions of the same dependent assembly that could not be resolved.
These reference conflicts are listed in the build log when log verbosity is set to detailed.
[C:\Users\Ilya.Kozhevnikov\Dropbox\BuildTree\BuildTree\BuildTree.csproj]
I was facing the same problem. Removing the bin\
from the HADOOP_HOME path solved it for me. The path for HADOOP_HOME variable should look something like.
C:\dev\hadoop2.6\
System restart may be needed. In my case, restarting the IDE was sufficient.
The solution that worked for me is:
suptitle()
for the actual titletitle()
for the subtitle and adjust it using the optional parameter y
: import matplotlib.pyplot as plt
"""
some code here
"""
plt.title('My subtitle',fontsize=16)
plt.suptitle('My title',fontsize=24, y=1)
plt.show()
There can be some nasty overlap between the two pieces of text. You can fix this by fiddling with the value of y
until you get it right.
The easiest way:
Step 1: Open AndroidManifest.xml file
Step 2: Locate android:theme="@style/AppTheme" >
Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >
Step 4: Then Add ImageView & Image
Step 4: That's it!
You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.
Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it
After these configurations, you can manage your console with control characters like:
\t - tab.
\b - backspace (a step backward in the text or deletion of a single character).
\n - new line.
\r - carriage return. ()
\f - form feed.
More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php
Unicode codepoints U+D800 to U+DFFF must be avoided: they are invalid in Unicode because they are reserved for UTF-16 surrogate pairs. Some JSON encoders/decoders will replace them with U+FFFD. See for example how the Go language and its JSON library deals with them.
So avoid "\uD800" to "\uDFFF" alone (not in surrogate pairs).
if you already have the directory, check the dir permissions or try to restart mongo with sudo. sudo brew services start mongodb
One more dict style clean syntax:
df["new_column"] = df.apply(lambda x: x["A"] * x["B"], axis = 1)
or,
df["new_column"] = df["A"] * df["B"]
The exact wording of the latest published standard (C++14) is:
An implementation shall allow both
a function of
()
returningint
anda function of
(int
, pointer to pointer tochar)
returningint
as the type of
main
.
This makes it clear that alternative spellings are permitted so long as the type of main
is the type int()
or int(int, char**)
. So the following are also permitted:
int main(void)
auto main() -> int
int main ( )
signed int main()
typedef char **a; typedef int b, e; e main(b d, a c)
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
For example:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
That means sql group by 1st column in your select clause, we always use this GROUP BY 1
together with ORDER BY 1
, besides you can also use like this GROUP BY 1,2,3..
, of course it is convenient for us but you need to pay attention to that condition the result may be not what you want if some one has modified your select columns, and it's not visualized
In my case, I could not even open "References" in the Visual Basic window. I even tried reinstalling Office 365 and that didn't work. Finally, I tried disabling macros in the "Trust Center" settings. When I restarted Excel, I got the warning message that macros were disabled, and when I clicked on "enable" I no longer got the error message.
Later I re-enabled all macros in the "Trust Center" settings, and the error message didn't show up!
Hey, if nothing else works for you, try the above; it worked for me! :)
Update: The issue returned, and this is how I "fixed" it the second time:
I opened my workbook in Excel online (Office 365, in the browser, which doesn't support macros anyway), saved it with a new file name (still using .xlsm file extension), and reopened in the desktop software. It worked.
Multiprocessing and pickling is broken and limited unless you jump outside the standard library.
If you use a fork of multiprocessing
called pathos.multiprocesssing
, you can directly use classes and class methods in multiprocessing's map
functions. This is because dill
is used instead of pickle
or cPickle
, and dill
can serialize almost anything in python.
pathos.multiprocessing
also provides an asynchronous map function… and it can map
functions with multiple arguments (e.g. map(math.pow, [1,2,3], [4,5,6])
)
See discussions: What can multiprocessing and dill do together?
and: http://matthewrocklin.com/blog/work/2013/12/05/Parallelism-and-Serialization
It even handles the code you wrote initially, without modification, and from the interpreter. Why do anything else that's more fragile and specific to a single case?
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> class calculate(object):
... def run(self):
... def f(x):
... return x*x
... p = Pool()
... return p.map(f, [1,2,3])
...
>>> cl = calculate()
>>> print cl.run()
[1, 4, 9]
Get the code here: https://github.com/uqfoundation/pathos
And, just to show off a little more of what it can do:
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>>
>>> p = Pool(4)
>>>
>>> def add(x,y):
... return x+y
...
>>> x = [0,1,2,3]
>>> y = [4,5,6,7]
>>>
>>> p.map(add, x, y)
[4, 6, 8, 10]
>>>
>>> class Test(object):
... def plus(self, x, y):
... return x+y
...
>>> t = Test()
>>>
>>> p.map(Test.plus, [t]*4, x, y)
[4, 6, 8, 10]
>>>
>>> res = p.amap(t.plus, x, y)
>>> res.get()
[4, 6, 8, 10]
on linux ctrl+m should work but it doesn't for solving the problem click on the (...) (its extended controls) and then close that window.now you can open menu by ctrl+m. then:
click on the (...) (its extended controls)
close extended controls
ctrl+m
Select Case parameter
' does something here.
' does something here.
Case "userID", "packageID", "mvrType"
' does something here.
If otherFactor Then
Else
goto case default
End If
Case Else
' does some processing...
Exit Select
End Select