We can eliminate the unnecessary file read/write by using text
. My complete solution is the following:
proc1 = ['/bin/bash', '-c',
"/usr/bin/git ls-remote --heads ssh://repo_url.git"].execute()
proc2 = ['/bin/bash', '-c',
"/usr/bin/awk ' { gsub(/refs\\/heads\\//, \"\"); print \$2 }' "].execute()
all = proc1 | proc2
choices = all.text
return choices.split().toList();
You cannot use a select statement that assigns values to variables to also return data to the user The below code will work fine, because i have declared 1 local variable and that variable is used in select statement.
Begin
DECLARE @name nvarchar(max)
select @name=PolicyHolderName from Table
select @name
END
The below code will throw error "A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations" Because we are retriving data(PolicyHolderAddress) from table, but error says data-retrieval operation is not allowed when you use some local variable as part of select statement.
Begin
DECLARE @name nvarchar(max)
select
@name = PolicyHolderName,
PolicyHolderAddress
from Table
END
The the above code can be corrected like below,
Begin
DECLARE @name nvarchar(max)
DECLARE @address varchar(100)
select
@name = PolicyHolderName,
@address = PolicyHolderAddress
from Table
END
So either remove the data-retrieval operation or add extra local variable. This will resolve the error.
You can set tag of the button and access it from sender in action
[btnHome addTarget:self action:@selector(btnMenuClicked:) forControlEvents:UIControlEventTouchUpInside];
btnHome.userInteractionEnabled = YES;
btnHome.tag = 123;
In the called function
-(void)btnMenuClicked:(id)sender
{
[sender tag];
if ([sender tag] == 123) {
// Do Anything
}
}
If you are a linux user Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
i have tried this article Code Project, it is working fine for me. I have used the code too. article is excellent in explanation with screenshot.
I am adding necessary explanation to this scenario
You have just booted up your computer and are about to log on. When you log on, the system assigns you a unique Session ID. In Windows Vista, the first User to log on to the computer is assigned a Session ID of 1 by the OS. The next User to log on will be assigned a Session ID of 2. And so on and so forth. You can view the Session ID assigned to each logged on User from the Users tab in Task Manager.
But your windows service is brought under session ID of 0. This session is isolated from other sessions. This ultimately prevent the windows service to invoke the application running under user session's like 1 or 2.
In order to invoke the application from windows service you need to copy the control from winlogon.exe which acts as present logged user as shown in below screenshot.
Important codes
// obtain the process id of the winlogon process that
// is running within the currently active session
Process[] processes = Process.GetProcessesByName("winlogon");
foreach (Process p in processes)
{
if ((uint)p.SessionId == dwSessionId)
{
winlogonPid = (uint)p.Id;
}
}
// obtain a handle to the winlogon process
hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
// obtain a handle to the access token of the winlogon process
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
{
CloseHandle(hProcess);
return false;
}
// Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
// I would prefer to not have to use a security attribute variable and to just
// simply pass null and inherit (by default) the security attributes
// of the existing token. However, in C# structures are value types and therefore
// cannot be assigned the null value.
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
// copy the access token of the winlogon process;
// the newly created token will be a primary token
if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
{
CloseHandle(hProcess);
CloseHandle(hPToken);
return false;
}
STARTUPINFO si = new STARTUPINFO();
si.cb = (int)Marshal.SizeOf(si);
// interactive window station parameter; basically this indicates
// that the process created can display a GUI on the desktop
si.lpDesktop = @"winsta0\default";
// flags that specify the priority and creation method of the process
int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
// create a new process in the current User's logon session
bool result = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
applicationName, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
dwCreationFlags, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out procInfo // receives information about new process
);
You can either define the right default value into the model you want to edit with this form or you can specify an empty_data option so your code become:
$form = $this
->createFormBuilder($breed)
->add(
'species',
'entity',
array(
'class' => 'BFPEduBundle:Item',
'property' => 'name',
'empty_data' => 123,
'query_builder' => function(ItemRepository $er) {
return $er
->createQueryBuilder('i')
->where("i.type = 'species'")
->orderBy('i.name', 'ASC')
;
}
)
)
->add('breed', 'text', array('required'=>true))
->add('size', 'textarea', array('required' => false))
->getForm()
;
Use this:
static int RandomNumber(int min, int max)
{
Random random = new Random(); return random.Next(min, max);
}
This is example for you to modify and use in your application.
Is this acceptable?
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);
But, Neil's answer is a better solution.
I just did the same. I did it in helper controller, my code is:
def get_controller_name
controller_name
end
def get_action_name
action_name
end
These methods will return current contoller and action name. Hope it helps
Perhaps the console is clearing. Try:
Console.WriteLine("Test");
Console.ReadLine();
And it will hopefully stay there until you press enter.
It works with Spring Boot 2.1.0 and Hibernate 5
@PersistenceContext
private EntityManager entityManager;
Then you can create new Session by using entityManager.unwrap(Session.class)
Session session = null;
if (entityManager == null
|| (session = entityManager.unwrap(Session.class)) == null) {
throw new NullPointerException();
}
example create query:
session.createQuery("FROM Student");
application.properties:
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
Yes, presumably it wants the path to the javadoc
command line tool that comes with the JDK (in the bin directory, same as java
and javac
).
Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.
Open this folder "C:\ProgramData\" and right-click on "\Anaconda3". go to properties -> security and check all the boxes for each user. This worked for me.
Put the following lines into a file called ColourText.bas
on your desktop.
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Public Module MyApplication
Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" (ByVal nStdHandle As Long) As Long
Public Declare Function SetConsoleTextAttribute Lib "kernel32" Alias "SetConsoleTextAttribute" (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
Public Const STD_ERROR_HANDLE = -12&
Public Const STD_INPUT_HANDLE = -10&
Public Const STD_OUTPUT_HANDLE = -11&
Sub Main()
Dim hOut as Long
Dim Ret as Long
Dim Colour As Long
Dim Colour1 As Long
Dim Text As String
hOut = GetStdHandle(STD_OUTPUT_HANDLE)
Colour = CLng("&h" & Split(Command(), " ")(0))
Colour1 = Clng("&h" & Split(Command(), " ")(1))
Text = Mid(Command(), 7)
Ret = SetConsoleTextAttribute(hOut, Colour)
Console.Out.WriteLine(text)
Ret = SetConsoleTextAttribute(hOut, Colour1)
End Sub
End Module
Save it and type the following in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%userprofile%\desktop\ColourText.exe" "%userprofile%\desktop\ColourText.bas" /verbose
A file called ColourText.exe will appear on your desktop. Move it to the Windows folder.
To use you must use two character codes to set colour eg 01
not 1
.
ColourText ColourOfText ColourOfTextWhenFinished Text
EG To set blue on white by not passing any text, then red on white text, finishing with blue on grey.
ColourText F1 F1
ColourText F2 71 This is green on white
or
ColourText F1 F1
cls
ColourText F4 F4
Echo Hello
Echo Hello today
ColourText F1 F1
Also the CLS
command becomes interesting. Color
command without parameters resets all colours to startup colours.
To get the colour code add the following numbers together. Use Calculator in programmers mode. These are hex numbers. They can be added together eg Red + Blue + FG Intensity = 13 = D. As 10+ wasn't used the background will be black. Colour codes MUST be two characters, eg 08
not 8
.
FOREGROUND_RED = &H4 ' text color contains red.
FOREGROUND_INTENSITY = &H8 ' text color is intensified.
FOREGROUND_GREEN = &H2 ' text color contains green.
FOREGROUND_BLUE = &H1 ' text color contains blue.
BACKGROUND_BLUE = &H10 ' background color contains blue.
BACKGROUND_GREEN = &H20 ' background color contains green.
BACKGROUND_INTENSITY = &H80 ' background color is intensified.
BACKGROUND_RED = &H40 ' background color contains red.
Better to just use .addClass()
and .removeClass()
even if you have 1 or more styles to change. It's more maintainable and readable.
If you really have the urge to do multiple CSS properties, then use the following:
.css({
'font-size' : '10px',
'width' : '30px',
'height' : '10px'
});
NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.
Most are saying killall -9 dart
but nobody mentioned pkill -f dart
which worked for me.
The difference between the 2 is explained here.
I tried the below and it worked well,
Install Dimensions Data Model and OLE DB Access
and follow the below steps in excel
Data->Get External Data ->From Other sources -> From Data Connection Wizard -> Other/Advanced-> SPSS MR DM-2 OLE DB Provider-> Metadata type as SPSS File(SAV)-> SPSS data file in Metadata Location->Finish
If RAND_MAX
is 32767, you can double the number of bits easily.
int BigRand()
{
assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);
return rand() * (RAND_MAX+1) + rand();
}
final Handler handler = new Handler() {
@Override
public void handleMessage(final Message msgs) {
//write your code hear which give error
}
}
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
//this will call handleMessage function and hendal all error
}
}).start();
To extract a single number from a string you can use re.search()
, which returns the first match (or None
):
>>> import re
>>> string = '3158 reviews'
>>> int(re.search(r'\d+', string).group(0))
3158
In Python 3.6+ you can also index into a match object instead of using group()
:
>>> int(re.search(r'\d+', string)[0])
3158
Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)
var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
// do something
}
Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.
Consider using needle - tool for automated visual comparison https://github.com/bfirsh/needle , which has built-in functionality that allows to take screenshots of specific elements (selected by CSS selector). The tool works on Selenium's WebDriver and it's written in Python.
And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.
In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.
The way you are adding headers is the right way to do it.
It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.
Here’s how you can find the details of your transaction:
Sign in to your Google Payments account at https://payments.google.com.
On the left menu, select the “Subscriptions and services” page.
On the “Other purchase activity” card, click View purchases.
Click the “Google Play” registration transaction to see your payment method.
You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.
To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).
final static String EXTRA_MESSAGE = "edit.list.message";
Context context;
public void onClick (View view)
{
Intent intent = new Intent(this,display.class);
RelativeLayout relativeLayout = (RelativeLayout) view.getParent();
TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
String message = textView.getText().toString();
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
As an addendum, if you are using this technique to define strings in your target, this is how I had to define and use them:
In Build Settings -> Preprocessor Macros, and yes backslashes are critical in the definition:
APPURL_NSString=\@\"www.foobar.org\"
And in the source code:
objectManager.client.baseURL = APPURL_NSString;
This is an interesting task and and here is my contribution. It's very simple and fast. If interested please bear with me and read on.
If you would like to this job fast, you definitely have to get yourself into dynamical programming. Which means you should forget about recursive approaches. That's for sure...
OK le_m's code which uses the Heap's method seems to be the fastest so far. Well i haven't got a name for my algorithm, i don't know if it's already been implemented or not but it's very simple and fast. As with all dynamical programming approaches we will start with the simplest problem and go for the final result.
Assuming that we have an array of a = [1,2,3]
we will start with
r = [[1]]; // result
t = []; // interim result
Then follow these three steps;
r
(result) array we will add the next item of the input array.t
. (well except for the first one not to waste time with 0 rotation)r
the interim array t
should hold the next level of results so we make r = t; t = [];
and carry on up until the length of the input array a
.So the following are our steps;
r array | push next item to | get length many rotations
| each sub array | of each subarray
-----------------------------------------------------------
[[1]] | [[1,2]] | [[1,2],[2,1]]
----------|-------------------|----------------------------
[[1,2], | [[1,2,3], | [[1,2,3],[2,3,1],[3,1,2],
[2,1]] | [2,1,3]] | [2,1,3],[1,3,2],[3,2,1]]
----------|-------------------|----------------------------
previous t| |
-----------------------------------------------------------
So here is the code
function perm(a){_x000D_
var r = [[a[0]]],_x000D_
t = [],_x000D_
s = [];_x000D_
if (a.length <= 1) return a;_x000D_
for (var i = 1, la = a.length; i < la; i++){_x000D_
for (var j = 0, lr = r.length; j < lr; j++){_x000D_
r[j].push(a[i]);_x000D_
t.push(r[j]);_x000D_
for(var k = 1, lrj = r[j].length; k < lrj; k++){_x000D_
for (var l = 0; l < lrj; l++) s[l] = r[j][(k+l)%lrj];_x000D_
t[t.length] = s;_x000D_
s = [];_x000D_
}_x000D_
}_x000D_
r = t;_x000D_
t = [];_x000D_
}_x000D_
return r;_x000D_
}_x000D_
_x000D_
var arr = [0,1,2,4,5];_x000D_
console.log("The length of the permutation is:",perm(arr).length);_x000D_
console.time("Permutation test");_x000D_
for (var z = 0; z < 2000; z++) perm(arr);_x000D_
console.timeEnd("Permutation test");
_x000D_
In multiple test i have seen it resolving the 120 permutations of [0,1,2,3,4] for 2000 times in 25~35ms.
The Spring Framework has a class which allows to recursively search through the classpath:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");
More clarified version of above answers:
IEnumerable<IGrouping<int, ClassA>> groups = list.GroupBy(x => x.PropertyIntOfClassA);
foreach (var groupingByClassA in groups)
{
int propertyIntOfClassA = groupingByClassA.Key;
//iterating through values
foreach (var classA in groupingByClassA)
{
int key = classA.PropertyIntOfClassA;
}
}
Sometimes the easiest way to fix this issue is to make a new branch from the place where you know the code is good. Then you can leave the errant branch history alone in case you need to cherry-pick other commits from it later. This also ensures you did not lose any commit history.
From your local errant branch:
git log
copy the commit hash that you wanted the branch to be at and exit the git log
git checkout theHashYouJustCopied
git checkout -b your_new_awesome_branch
Now you have a new branch just the way you want it.
If you also needed to keep a specific commit from the errant branch that is not on your new branch, you can just cherry-pick that specific commit you need:
git checkout the_errant_branch
git log
Copy the commit hash of the one commit you need to pull into the good branch and exit the git log.
git checkout your_new_awesome_branch
git cherry-pick theHashYouJustCopied
Pat yourself on the back.
We open source a tool that removes all the unused resources in your android project based on the lint output. It can be found here: https://github.com/KeepSafe/android-resource-remover
Applying the recursive function on numpy arrays will be faster than the current answer.
df = pd.DataFrame(np.repeat(np.arange(2, 6),3).reshape(4,3), columns=['A', 'B', 'D'])
new = [df.D.values[0]]
for i in range(1, len(df.index)):
new.append(new[i-1]*df.A.values[i]+df.B.values[i])
df['C'] = new
Output
A B D C
0 1 1 1 1
1 2 2 2 4
2 3 3 3 15
3 4 4 4 64
4 5 5 5 325
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows:
with a drop down with a few options. I'm thinking yours may be set to Always
. Bottom line is you can't rely on a browser opening a new window.
I think this should work:
#open file for reading
fn = input("Enter file to open: ")
try:
fh = open(fn,'r')
except:
# if file does not exist, create it
fh = open(fn,'w')
Also, you incorrectly wrote fh = open ( fh, "w")
when the file you wanted open was fn
do you want to write code for that or just use command-line feature 'command redirection' as follows:
app.exe >> output.txt
as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)
EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm
I will recommend to use an alternative method using seaborn
which more powerful tool for data plotting. You can use seaborn scatterplot
and define colum 3 as hue
and size
.
Working code:
import pandas as pd
import seaborn as sns
import numpy as np
#creating sample data
sample_data={'col_name_1':np.random.rand(20),
'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")
Please make sure there is no linebreak or space after , it's to make sure there is no whitespace or tab, just copy and paste this code :) I had fix it for you
<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?php if($siteLink_val) echo trim($siteLink_val);?></textarea>
In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:
const tampax = require('tampax');
const yamlString = `
dude:
name: Arthur
weapon:
favorite: Excalibur
useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;
const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);
// output : "Arthur use Excalibur. The goal is to kill Mordred."
Editor's Note: poster is also the author of this package.
You have to add the below permission in Info.plist. More Referance
Camera :
Key : Privacy - Camera Usage Description
Value : $(PRODUCT_NAME) camera use
Photo :
Key : Privacy - Photo Library Usage Description
Value : $(PRODUCT_NAME) photo use
The database.yml
is a file that is created with new rails applications in /config
and defines the database configurations that your application will use in different environments. Read this for details.
Example database.yml:
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: mysql
encoding: utf8
database: your_db
username: root
password: your_pass
socket: /tmp/mysql.sock
host: your_db_ip #defaults to 127.0.0.1
port: 3306
npm install package_x --save
The given package (package_x) will be saved in package.json inside dependencies. if you add
npm install <<package_x>> --save-dev
then it will be saved inside devDependencies.
you can try this:
<input type="textbox" id="confirmEmail" onselectstart="return false" onpaste="return false;" oncopy="return false" oncut="return false" ondrag="return false" ondrop="return false" autocomplete="off">
For people who are using wordpress plugin Advanced Access Manager to open up the JWT Authentication.
The Header field should put Authentication instead of Authorization
AAM mentioned it inside their documentation,
Note! AAM does not use standard Authorization header as it is skipped by most Apache servers. ...
Hope it helps someone! Thanks for other answers helped me alot too!!
Because of the definition of the semantics of nth-child
, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit - thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child
gives you.
This was too good of an answer not to post it here. It's from a Gilles, a fellow user from askubuntu:
The clipboard is provided by the X server. It doesn't matter whether the server is headless or not, what matters is that your local graphical session is available to programs running on the remote machine. Thanks to X's network-transparent design, this is possible.
I assume that you're connecting to the remote server with SSH from a machine running Linux. Make sure that X11 forwarding is enabled both in the client configuration and in the server configuration. In the client configuration, you need to have the line
ForwardX11 yes
in~/.ssh/config
to have it on by default, or pass the option-X
to thessh
command just for that session. In the server configuration, you need to have the lineX11Forwarding yes
in/etc/ssh/sshd_config
(it is present by default on Ubuntu).To check whether X11 forwarding is enabled, look at the value of the
DISPLAY
environment variable:echo $DISPLAY
. You should see a value likelocalhost:10
(applications running on the remote machine are told to connect to a display running on the same machine, but that display connection is in fact forwarded by SSH to your client-side display). Note that ifDISPLAY
isn't set, it's no use setting it manually: the environment variable is always set correctly if the forwarding is in place. If you need to diagnose SSH connection issues, pass the option-vvv
tossh
to get a detailed trace of what's happening.If you're connecting through some other means, you may or may not be able to achieve X11 forwarding. If your client is running Windows, PuTTY supports X11 forwarding; you'll have to run an X server on the Windows machine such as Xming.
By Gilles from askubuntu
document.form.p_id.length
... not count().
You really should give your form an id
<form id="myform">
Then refer to it using:
var theForm = document.getElementById("myform");
Then refer to the elements like:
for(var i = 0; i < theForm.p_id.length; i++){
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
Yes, this sort of thing is possible without Flash:
However, only very modern browsers supports HTML5 videos, and this should be your consideration when deploying in HTML 5, and you should provide a fallback (probably Flash or just omit the transparency).
><
by >\n<
with Regular Expressions enabled%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.
Now you can use insert
method instead add
' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")
To see command-line flags, use:
gcc -march=native -E -v - </dev/null 2>&1 | grep cc1
If you want to see the compiler/precompiler defines set by certain parameters, do this:
echo | gcc -dM -E - -march=native
I'm using Ubuntu and I tried as @Arie said above but with this line only in terminal:
sudo apt-get install tcl-dev tk-dev python-tk python3-tk
And it worked!
If PHP's allow_url_fopen
ini directive is set to true, and if curl
doesn't work either (see this answer for an example of how to use it instead of file_get_contents
), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).
I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.
As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.
Don't make anonymous subclasses of Fragment :-)
Use Counter
>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})
Not exactly elegant, but the best (and quickest) solution i could find was using OnError. This will be significantly faster than iteration for any medium to large collection.
Public Function InCollection(col As Collection, key As String) As Boolean
Dim var As Variant
Dim errNumber As Long
InCollection = False
Set var = Nothing
Err.Clear
On Error Resume Next
var = col.Item(key)
errNumber = CLng(Err.Number)
On Error GoTo 0
'5 is not in, 0 and 438 represent incollection
If errNumber = 5 Then ' it is 5 if not in collection
InCollection = False
Else
InCollection = True
End If
End Function
This page on the official mongodb site addresses exactly this question:
When we display our list of stories, we'll need to show the name of the user who posted the story. If we were using a relational database, we could perform a join on users and stores, and get all our objects in a single query. But MongoDB does not support joins and so, at times, requires bit of denormalization. Here, this means caching the 'username' attribute.
Relational purists may be feeling uneasy already, as if we were violating some universal law. But let’s bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.
Jacob Wright's Date.format()
library implements date formatting in the style of PHP's date()
function and supports the ISO-8601 week number:
new Date().format('W');
It may be a bit overkill for just a week number, but it does support PHP style formatting and is quite handy if you'll be doing a lot of this.
better use quoted `data`
and `date`
. AFAIR these may be reserved words
my version is:
INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);
I got a solution in python, I modified the webdriver class bassed on PersistenBrowser class that I found.
https://github.com/axelPalmerin/personal/commit/fabddb38a39f378aa113b0cb8d33391d5f91dca5
replace the webdriver module /usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py
Ej. to use:
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
runDriver = sys.argv[1]
sessionId = sys.argv[2]
def setBrowser():
if eval(runDriver):
webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME,
)
else:
webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME,
session_id=sessionId)
url = webdriver.command_executor._url
session_id = webdriver.session_id
print url
print session_id
return webdriver
According to Java Persistence with Hibernate
mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard
If you were using Hibernate, you could do something like:
@org.hibernate.annotations.CollectionOfElements(
targetElement = java.lang.String.class
)
@JoinTable(
name = "foo",
joinColumns = @JoinColumn(name = "foo_id")
)
@org.hibernate.annotations.IndexColumn(
name = "POSITION", base = 1
)
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();
Update: Note, this is now available in JPA2.
You can simply use RaisedButton
Padding(
padding: EdgeInsets.only(left: 150.0, right: 0.0),
child: RaisedButton(
textColor: Colors.white,
color: Colors.black,
child: Text("Search"),
onPressed: () {},
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
),
)
Output:
More info: RSCoder
It depends on what exactly you want to achieve.
If you just want to have it on the right, then I'd recommend against using position absolute, because it opens a whole can of worms down the line.
The HTML can also be unchanged:
HTML
<div>
<h1> Ok </h1>
<button type='button'>Button</button>
</div>
the CSS then should be something along the lines of:
CSS
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
display: inline-block;
width: 100%;
margin-right: -50%;
}
div button {
float: right;
}
You can see it in action here: http://jsfiddle.net/azhH5/
If you can change the HTML, then it gets a bit simpler:
HTML
<div>
<button type='button'>Button</button>
<h1> Ok </h1>
</div>
CSS
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
}
div button {
float: right;
margin-left: -50%;
}
You can see it in action: http://jsfiddle.net/8WA3k/1/
If you want to have the button on the same line as the Text, you can achieve it by doing this:
HTML
<div>
<button type='button'>Button</button>
<h1> Ok </h1>
</div>
CSS
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
}
div button {
float: right;
margin-left: -50%;
margin-top: 2em;
}
You an see that in action here: http://jsfiddle.net/EtqVh/1/
Cleary in the lest example you'd have to adjust the margin-top for the specified font-size of the <h1>
EDIT:
As you can see, it doesn't get popped out of the <div>
, it's till inside. this is achieved by two things: the negative margin on the <button>
, and the overflow: hidden;
on the <div>
EDIT 2:
I just saw that you also want it to be a bit away from the margin on the right. That's easily achievable with this method. Just add margin-right: 1em;
to the <button>
, like this:
div {
background: purple;
overflow: hidden;
}
div h1 {
text-align: center;
}
div button {
float: right;
margin-left: -50%;
margin-top: 2em;
margin-right: 1em;
}
You can see it in action here: http://jsfiddle.net/QkvGb/
If you are using Angular 1.3 or above, I recommend that you use "track by" in your ng-repeat. Angular doesn't add a "$$hashKey" property to the objects in your array if you use "track by". You also get performance benefits, if something in your array changes, angular doesn't recreate the entire DOM structure for your ng-repeat, it instead recreates the part of the DOM for the values in your array that have changed.
It does nothing because no events have been bound to the event. If I recall correctly, jQuery maintains its own list of event handlers that are bound to NodeLists for performance and other purposes.
I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x
Set the property of your DataGridView:
Anchor: Top,Left
AutoSizeColumn: Fill
Dock: Fill
You can also install simplejson.
If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:
pip install simplejson
This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".
Look at the picture, it's a result set of a query select * from employee
and the next() method of ResultSet class help to move the cursor to the next row of a returned result set which is rs in your example.
:)
Another solution, using another great feature:
:'<,'>norm A,
See :help :normal
.
I don't see why you shouldn't be able to send html content via a post.
if you encounter any issues, you could perhaps use some kind of encoding / decoding - but I don't see that you will.
Here is example code showing how to compute a centered moving average and a trailing moving average using the rollmean
function from the zoo package.
library(tidyverse)
library(zoo)
some_data = tibble(day = 1:10)
# cma = centered moving average
# tma = trailing moving average
some_data = some_data %>%
mutate(cma = rollmean(day, k = 3, fill = NA)) %>%
mutate(tma = rollmean(day, k = 3, fill = NA, align = "right"))
some_data
#> # A tibble: 10 x 3
#> day cma tma
#> <int> <dbl> <dbl>
#> 1 1 NA NA
#> 2 2 2 NA
#> 3 3 3 2
#> 4 4 4 3
#> 5 5 5 4
#> 6 6 6 5
#> 7 7 7 6
#> 8 8 8 7
#> 9 9 9 8
#> 10 10 NA 9
A Date doesn't have any time zone. What you're seeing is only the formatting of the date by the Date.toString()
method, which uses your local timezone, always, to transform the timezone-agnostic date into a String that you can understand.
If you want to display the timezone-agnostic date as a string using the UTC timezone, then use a SimpleDateFormat with the UTC timezone (as you're already doing in your question).
In other terms, the timezone is not a property of the date. It's a property of the format used to transform the date into a string.
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace
which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove()
from the resulting List
. For an actual ArrayList
you must further use new ArrayList<String>
.
Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.
public new EventsDataTable Events
{
..
}
If you don't wish to override it change your properties' name to something else.
If it's a 3.x version then just simply use:
variantname = input()
For example, you want to input 8:
x = input()
8
x will equal 8 but it's going to be a string except if you define it otherwise.
So you can use the convert command, like:
a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
You can do it like this:
class UsersController < ApplicationController
## Exception Handling
class NotActivated < StandardError
end
rescue_from NotActivated, :with => :not_activated
def not_activated(exception)
flash[:notice] = "This user is not activated."
Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
redirect_to "/"
end
def show
// Do something that fails..
raise NotActivated unless @user.is_activated?
end
end
What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.
Best wishes,
Fabian
To answer, you question you could provide a service that wraps the original Http
object from Angular. Something like described below.
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
@Injectable()
export class HttpClient {
constructor(private http: Http) {}
createAuthorizationHeader(headers: Headers) {
headers.append('Authorization', 'Basic ' +
btoa('username:password'));
}
get(url) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get(url, {
headers: headers
});
}
post(url, data) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.post(url, data, {
headers: headers
});
}
}
And instead of injecting the Http
object you could inject this one (HttpClient
).
import { HttpClient } from './http-client';
export class MyComponent {
// Notice we inject "our" HttpClient here, naming it Http so it's easier
constructor(http: HttpClient) {
this.http = httpClient;
}
handleSomething() {
this.http.post(url, data).subscribe(result => {
// console.log( result );
});
}
}
I also think that something could be done using multi providers for the Http
class by providing your own class extending the Http
one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.
You could also use the store library which performs it for you with crossbrowser ability.
example :
// Store current user
store.set('user', { name:'Marcus' })
// Get current user
store.get('user')
// Remove current user
store.remove('user')
// Clear all keys
store.clearAll()
// Loop over all stored values
store.each(function(value, key) {
console.log(key, '==', value)
})
The JSON data can be written to a file as follows
hist1 = [{'val_loss': [0.5139984398465246],
'val_acc': [0.8002029867684085],
'loss': [0.593220705309384],
'acc': [0.7687131817929321]},
{'val_loss': [0.46456472964199463],
'val_acc': [0.8173602046780344],
'loss': [0.4932038113037539],
'acc': [0.8063946213802453]}]
Write to a file:
with open('text1.json', 'w') as f:
json.dump(hist1, f)
A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.
You denote that fact by appending the "= 0" to the declaration, like this:
class AbstractBase
{
virtual void PureVirtualFunction() = 0;
}
Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:
class Derived : public AbstractBase
{
virtual void PureVirtualFunction() override { }
}
By adding the override
keyword, the compiler will ensure that there is a base class virtual function with the same signature.
Press Ctl+T
will open a search box. Delete # symbol and enter your file name.
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
The only thing I would suggest is caching the result of values()
because each call copies an array. Also, don't create a Random
every time. Keep one. Other than that what you're doing is fine. So:
public enum Letter {
A,
B,
C,
//...
private static final List<Letter> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Letter randomLetter() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
I have created a working regular expression myself:
str=str.replace(/(<\?[a-z]*(\s[^>]*)?\?(>|$)|<!\[[a-z]*\[|\]\]>|<!DOCTYPE[^>]*?(>|$)|<!--[\s\S]*?(-->|$)|<[a-z?!\/]([a-z0-9_:.])*(\s[^>]*)?(>|$))/gi, '');
You can wrap it up to workaround the compiler but please remember that side effects in lambdas are discouraged.
To quote the javadoc
Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement A small number of stream operations, such as forEach() and peek(), can operate only via side-effects; these should be used with care
git config user.email "[email protected]"
Doing that one inside a repo will set the configuration on THAT repo, and not globally.
Seems like that's pretty much what you're after, unless I'm misreading you.
A more recent way to do this is to use the .to_numpy() function.
If I have a dataframe with a column 'price', I can convert it as follows:
priceArray = df['price'].to_numpy()
You can also pass the data type, such as float or object, as an argument of the function
Thanks to Alloush,
Following parameter must be included in model.fit()
:
validation_data = (x_test, y_test)
If it is not defined, val_acc
and val_loss
will not
be exist at output.
Another way to solve with Reflection, but without marshalling:
I have this abstract helper class:
public abstract class MvcIntegrationTestUtils {
public static MockHttpServletRequestBuilder postForm(String url,
Object modelAttribute, String... propertyPaths) {
try {
MockHttpServletRequestBuilder form = post(url).characterEncoding(
"UTF-8").contentType(MediaType.APPLICATION_FORM_URLENCODED);
for (String path : propertyPaths) {
form.param(path, BeanUtils.getProperty(modelAttribute, path));
}
return form;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
You use it like this:
// static import (optional)
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
// in your test method, populate your model attribute object (yes, works with nested properties)
BlogSetup bgs = new BlogSetup();
bgs.getBlog().setBlogTitle("Test Blog");
bgs.getUser().setEmail("[email protected]");
bgs.getUser().setFirstName("Administrator");
bgs.getUser().setLastName("Localhost");
bgs.getUser().setPassword("password");
// finally put it together
mockMvc.perform(
postForm("/blogs/create", bgs, "blog.blogTitle", "user.email",
"user.firstName", "user.lastName", "user.password"))
.andExpect(status().isOk())
I have deduced it is better to be able to mention the property paths when building the form, since I need to vary that in my tests. For example, I might want to check if I get a validation error on a missing input and I'll leave out the property path to simulate the condition. I also find it easier to build my model attributes in a @Before method.
The BeanUtils is from commons-beanutils:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
<scope>test</scope>
</dependency>
yes you can ... you just need to know the exact package name of the application:
And you can create the intent like this
Intent intent = context.getPackageManager().getLaunchIntentForPackage(application);
if (intent != null) {
// The application exists
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage(application);
shareIntent.putExtra(android.content.Intent.EXTRA_TITLE, title);
shareIntent.putExtra(Intent.EXTRA_TEXT, description);
// Start the specific social application
context.startActivity(shareIntent);
} else {
// The application does not exist
// Open GooglePlay or use the default system picker
}
My preferred method for centering blocks of information while maintaining responsiveness (mobile compatibility) is to place two empty span1
divs before and after the content you wish to center.
<div class="row-fluid">
<div class="span1">
</div>
<div class="span10">
<div class="hero-unit">
<h1>Reading Resources</h1>
<p>Read here...</p>
</div>
</div><!--/span-->
<div class="span1">
</div>
</div><!--/row-->
The accurate way is to use the __FUNCTION__
predefined magic constant.
Example:
class Test {
function MethodA(){
echo __FUNCTION__;
}
}
Result: MethodA
.
You can try using Chrome Web Extension TruePath which dynamically generates the relative XPath on right click on the web page and display all the XPath as menu items.
In Swift 4:
let formatString = "12345"
if let number = Decimal(string:formatString){
print("String contains only number")
}
else{
print("String doesn't contains only number")
}
What you need is called attribute selector. An example, using your html structure, is the following:
div[class^="tocolor-"], div[class*=" tocolor-"] {
color:red
}
In the place of div
you can add any element or remove it altogether, and in the place of class
you can add any attribute of the specified element.
[class^="tocolor-"]
— starts with "tocolor-".
[class*=" tocolor-"]
— contains the substring "tocolor-" occurring directly after a space character.
Demo: http://jsfiddle.net/K3693/1/
More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs
This article have very good explanation and it solved my problem.
git config --global http.postBuffer 157286400
Yes, it means "not equal", either less than or greater than. e.g
If x <> y Then
can be read as
if x is less than y or x is greater than y then
The logical outcome being "If x is anything except equal to y"
UPDATE c11
SET
c11.completed= c6.completed,
c11.complete_date = c6.complete_date,
-- rest of columns to be copied
FROM courses c11 inner join courses c6 on
c11.userID = c6.userID
and c11.courseID = 11 and c6.courseID = 6
-- and any other checks
I have always viewed the From clause of an update, like one of a normal select. Actually if you want to check what will be updated before running the update, you can take replace the update parts with a select c11.*. See my comments on the lame duck's answer.
Chrome does not allow autoplay if the video is not muted. Try using this:
<video width="440px" loop="true" autoplay="autoplay" controls muted>
<source src="http://www.tuscorlloyds.com/CorporateVideo.mp4" type="video/mp4" />
<source src="http://www.tuscorlloyds.com/CorporateVideo.ogv" type="video/ogv" />
<source src="http://www.tuscorlloyds.com/CorporateVideo.webm" type="video/webm" />
</video>
I discovered that the order of adding roles and features is important. On a fresh system I activate the role "application server" and there check explicitly .net, web server support and finally process activation service Then automatically a dialogue comes up that the role "Web server" needs to be added also.
Bind to the change
event instead of click
. However, you will probably still need to check whether or not the checkbox is checked:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the Redacted in commentschange
event over the click
event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change
event.
Also note that I've used this.checked
instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the :checkbox
pseudo-selector:
$(":checkbox")
Or you could use an attribute equals selector:
$("input[type='checkbox']")
There are many answers here but I couldn't find something simple that covers all cases so allow me to suggest my solution too:
import pathlib_x000D_
import os_x000D_
_x000D_
def get_project_root():_x000D_
"""_x000D_
There is no way in python to get project root. This function uses a trick._x000D_
We know that the function that is currently running is in the project._x000D_
We know that the root project path is in the list of PYTHONPATH_x000D_
look for any path in PYTHONPATH list that is contained in this function's path_x000D_
Lastly we filter and take the shortest path because we are looking for the root._x000D_
:return: path to project root_x000D_
"""_x000D_
apth = str(pathlib.Path().absolute())_x000D_
ppth = os.environ['PYTHONPATH'].split(':')_x000D_
matches = [x for x in ppth if x in apth]_x000D_
project_root = min(matches, key=len)_x000D_
return project_root
_x000D_
Here is a guide that resolved a lot of these issues for me.
http://www.steveworkman.com/node-js/2012/installing-jsdom-on-windows/
I remember in particular the python version as important. Make sure you install 2.7.3 instead of 3's.
jQuery:
$("#tbodyid").empty();
HTML:
<table>
<tbody id="tbodyid">
<tr>
<td>something</td>
</tr>
</tbody>
</table>
Works for me
http://jsfiddle.net/mbsh3/
Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.
If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:
sudo add-apt-repository ppa:jonathonf/python-3.6 # (only for 16.04 LTS)
Then, run the following (this works out-of-the-box on 16.10 and 17.04):
sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3
# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python
When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1
(or a more recent version of Python 3.6):
python --version # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version
Opening a file in "write" mode clears it, you don't specifically have to write to it:
open("filename", "w").close()
(you should close it as the timing of when the file gets closed automatically may be implementation specific)
To whomever may have this issue. My problem was border-collapse. It was set to:
border-collapse: collapse;
I set it to:
border-collapse: separate;
and it fixed the issue.
see this is pure css bases dropdown menu:-
HTML
<ul id="menu">
<li><a href="">Home</a></li>
<li><a href="">About Us</a>
<ul>
<li><a href="">The Team</a></li>
<li><a href="">History</a></li>
<li><a href="">Vision</a></li>
</ul>
</li>
<li><a href="">Products</a>
<ul>
<li><a href="">Cozy Couch</a></li>
<li><a href="">Great Table</a></li>
<li><a href="">Small Chair</a></li>
<li><a href="">Shiny Shelf</a></li>
<li><a href="">Invisible Nothing</a></li>
</ul>
</li>
<li><a href="">Contact</a>
<ul>
<li><a href="">Online</a></li>
<li><a href="">Right Here</a></li>
<li><a href="">Somewhere Else</a></li>
</ul>
</li>
</ul>
CSS
ul
{
font-family: Arial, Verdana;
font-size: 14px;
margin: 0;
padding: 0;
list-style: none;
}
ul li
{
display: block;
position: relative;
float: left;
}
li ul
{
display: none;
}
ul li a
{
display: block;
text-decoration: none;
color: #ffffff;
border-top: 1px solid #ffffff;
padding: 5px 15px 5px 15px;
background: #2C5463;
margin-left: 1px;
white-space: nowrap;
}
ul li a:hover
{
background: #617F8A;
}
li:hover ul
{
display: block;
position: absolute;
}
li:hover li
{
float: none;
font-size: 11px;
}
li:hover a
{
background: #617F8A;
}
li:hover li a:hover
{
background: #95A9B1;
}
see the demo:- http://jsfiddle.net/XPE3w/7/
There is no direct option to export a single request from Postman.
You can create and export collections. Here is a link to help with that.
Regarding the single request thing, you can try a workaround. I tried with the RAW body parameters and it worked.
What you can do is,
Here's some status code, which you should know for your kind of knowledge.
- 100 Continue
- 101 Switching Protocols
- 102 Processing
- 103 Early Hints
- 200 OK
- 201 Created
- 202 Accepted
- 203 Non-Authoritative Information
- 204 No Content
- 205 Reset Content
- 206 Partial Content
- 207 Multi-Status
- 208 Already Reported
- 226 IM Used
- 300 Multiple Choices
- 301 Moved Permanently
- 302 Found
- 303 See Other
- 304 Not Modified
- 305 Use Proxy
- 306 Switch Proxy
- 307 Temporary Redirect
- 308 Permanent Redirect
- 400 Bad Request
- 401 Unauthorized
- 402 Payment Required
- 403 Forbidden
- 404 Not Found
- 405 Method Not Allowed
- 406 Not Acceptable
- 407 Proxy Authentication Required
- 408 Request Timeout
- 409 Conflict
- 410 Gone
- 411 Length Required
- 412 Precondition Failed
- 413 Payload Too Large
- 414 URI Too Long
- 415 Unsupported Media Type
- 416 Range Not Satisfiable
- 417 Expectation Failed
- 418 I'm a teapot
- 420 Method Failure
- 421 Misdirected Request
- 422 Unprocessable Entity
- 423 Locked
- 424 Failed Dependency
- 426 Upgrade Required
- 428 Precondition Required
- 429 Too Many Requests
- 431 Request Header Fields Too Large
- 451 Unavailable For Legal Reasons
- 500 Internal Server error
- 501 Not Implemented
- 502 Bad Gateway
- 503 Service Unavailable
- 504 gateway Timeout
- 505 Http version not supported
- 506 Varient Also negotiate
- 507 Insufficient Storage
- 508 Loop Detected
- 510 Not Extended
- 511 Network Authentication Required
They are binary large objects, you can use them to store binary data such as images or serialized objects among other things.
Many of these answers will only give you new records and not updates and/or are extremely ineffecient
The only reliable, performant way to do this is to create a tailable cursor on local db: oplog.rs collection to get ALL changes to MongoDB and do with it what you will. (MongoDB even does this internally more or less to support replication!)
Explanation of what the oplog contains: https://www.compose.com/articles/the-mongodb-oplog-and-node-js/
Example of a Node.js library that provides an API around what is available to be done with the oplog: https://github.com/cayasso/mongo-oplog
I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.
c := append(a, b...)
This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.
To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:
"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."
append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.
Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.
la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)
la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)
var inputString = "this is home";_x000D_
var findme = "home";_x000D_
_x000D_
if ( inputString.indexOf(findme) > -1 ) {_x000D_
alert( "found it" );_x000D_
} else {_x000D_
alert( "not found" );_x000D_
}
_x000D_
Use regular expression:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
output:
i=123;
j=123;
k=123;
I think you want something like
var count = context.MyTable.Count(t => t.MyContainer.ID == '1');
(edited to reflect comments)
I had the same problem and fixed it by clicking File>Invalidate caches/ restart
I have also discovered that, when using JNI, invoking a Java method from C++, if you pass parameters to the invoked Java method in the wrong order, you will get this error when you attempt to use the parameters inside the called method (because they won't be the right type). I was initially taken aback that JNI does not do this checking for you as part of the class signature checking when you invoke the method, but I assume they don't do this kind of checking because you may be passing polymorphic parameters and they have to assume you know what you are doing.
Example C++ JNI Code:
void invokeFooDoSomething() {
jobject javaFred = FredFactory::getFred(); // Get a Fred jobject
jobject javaFoo = FooFactory::getFoo(); // Get a Foo jobject
jobject javaBar = FooFactory::getBar(); // Get a Bar jobject
jmethodID methodID = getDoSomethingMethodId() // Get the JNI Method ID
jniEnv->CallVoidMethod(javaFoo,
methodID,
javaFred, // Woops! I switched the Fred and Bar parameters!
javaBar);
// << Insert error handling code here to discover the JNI Exception >>
// ... This is where the IncompatibleClassChangeError will show up.
}
Example Java Code:
class Bar { ... }
class Fred {
public int size() { ... }
}
class Foo {
public void doSomething(Fred aFred, Bar anotherObject) {
if (name.size() > 0) { // Will throw a cryptic java.lang.IncompatibleClassChangeError
// Do some stuff...
}
}
}
Using foreach would be shorter code, but probably do exactly the same steps at runtime after JIT optimization recognizes the comparison to Length in the for-loop controlling expression.
if you are using razor engine template then do the following
in your view write :
<script> var myJsVariable = '@ViewBag.MyVariable' </script>
UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```
<head>
<script>
var AppConfig = @Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
And you can use it in your JavaScript code as follow:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
Use df.to_dict('records')
-- gives the output without having to transpose externally.
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
type=submit
it is a Submit Button type=button
it is just a button, It does not submit your form inputs. and also you don't want to use both of these
My manual workaround, which involves manually updating model.options
when a new radio button is selected:
template: `
<label *ngFor="let item of radioItems">
<input type="radio" name="options" (click)="model.options = item"
[checked]="item === model.options">
{{item}}
</label>`
class App {
radioItems = 'one two three'.split(' ');
model = { options: 'two' };
}
This Plunker demonstrates the above, as well as how to use a button to change the selected radio button -- i.e., to prove that the data binding is two-way:
<button (click)="model.options = 'one'">set one</button>
As you may have already figured, Asp.Net MVC is a different paradigm than Asp.Net (webforms). Accessing form elements between the server and client take a different approach in Asp.Net MVC.
You can google more reading material on this on the web. For now, I would suggest using Ajax to get or post data to the server. You can still employ input type="hidden"
, but initialize it with a value from the ViewData
or for Razor, ViewBag
.
For example, your controller may look like this:
public ActionResult Index()
{
ViewBag.MyInitialValue = true;
return View();
}
In your view, you can have an input elemet that is initialized by the value in your ViewBag
:
<input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@ViewBag.MyInitialValue" />
Then you can pass data between the client and server via ajax. For example, using jQuery:
$.get('GetMyNewValue?oldValue=' + $('#myHiddenInput').val(), function (e) {
// blah
});
You can alternatively use $.ajax
, $.getJSON
, $.post
depending on your requirement.
Originally, I mentioned in 2012 git archive
(see Jared Forsyth's answer and Robert Knight's answer), since git1.7.9.5 (March 2012), Paul Brannan's answer:
git archive --format=tar --remote=origin HEAD:path/to/directory -- filename | tar -O -xf -
But: in 2013, that was no longer possible for remote https://github.com URLs.
See the old page "Can I archive a repository?"
The current (2018) page "About archiving content and data on GitHub" recommends using third-party services like GHTorrent or GH Archive.
So you can also deal with local copies/clone:
You could alternatively do the following if you have a local copy of the bare repository as mentioned in this answer,
git --no-pager --git-dir /path/to/bar/repo.git show branch:path/to/file >file
Or you must clone first the repo, meaning you get the full history: - in the .git repo - in the working tree.
git config core.sparsecheckout true
).git/info/sparse-checkout
fileTo re-read the working tree:
$ git read-tree -m -u HEAD
That way, you end up with a working tree including precisely what you want (even if it is only one file)
Richard Gomes points (in the comments) to "How do I clone, fetch or sparse checkout a single directory or a list of directories from git repository?"
A bash function which avoids downloading the history, which retrieves a single branch and which retrieves a list of files or directories you need.
With an extension method, you can accomplish this:
public static class Extension
{
public static string ToStringOrEmpty(this Object value)
{
return value == null ? "" : value.ToString();
}
}
The following would write nothing to the screen and would not thrown an exception:
string value = null;
Console.WriteLine(value.ToStringOrEmpty());
Depending on the actual value and what exception fits best:
ArgumentException
(something is wrong with the value)
ArgumentNullException
(the argument is null while this is not allowed)
ArgumentOutOfRangeException
(the argument has a value outside of the valid range)
If this is not precise enough, just derive your own exception class from ArgumentException
.
Yoooder's answer enlightened me. An input is invalid if it is not valid at any time, while an input is unexpected if it is not valid for the current state of the system. So in the later case an InvalidOperationException
is a reasonable choice.
As the accepted answer says, the most idiomatic way is to just use a module.
With that in mind, here's a proof of concept:
def singleton(cls):
obj = cls()
# Always return the same object
cls.__new__ = staticmethod(lambda cls: obj)
# Disable __init__
try:
del cls.__init__
except AttributeError:
pass
return cls
See the Python data model for more details on __new__
.
Example:
@singleton
class Duck(object):
pass
if Duck() is Duck():
print "It works!"
else:
print "It doesn't work!"
Notes:
You have to use new-style classes (derive from object
) for this.
The singleton is initialized when it is defined, rather than the first time it's used.
This is just a toy example. I've never actually used this in production code, and don't plan to.
A reference can never be NULL
.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
If you're just seeking to pull the data out of tables contained in the mdb, use Excel and ODBC (DATA tab...Get External Data...From Other Sources...From Data Connection Wizard...Other/Advanced...Microsoft Jet X.X OLE DB Provider...pick your db...pick your table(s) and voila! Data imported. Then just save the workbook that then can be linked or imported into the newer version of Access to build a new database.
The following steps fix the problem for Visual Studio 2015 and Visual Studio 2017:
.vs
folder.F5
and IIS Express should load as normal, allowing you to debug.Note: Based on my experience and others in the comments, this problem seems to be caused by moving a project between workstations, environments, or versions of Visual Studio. There must be some environment specific information contained in the
.vs
folder.
For me, once there was a mistake in spelling of function
For e.g. instead of
$(document).ready(function(){
});
I wrote
$(document).ready(funciton(){
});
So keep that also in check
The call to time(NULL)
returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t
variable, that pointer variable will point to the current time.
Specify the buildpack while creating the app.
heroku create appname --buildpack heroku/python
Benny's answer on Windows with the Linux subsystem:
code --list-extensions | wsl xargs -L 1 echo code --install-extension
Use this annotation
@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
Remove a block of code from multiple files
To expand on @Markus Olsson's answer, I needed to remove a block of code from multiple files. I had problems with Swedish characters in a core project, so I needed to install System.Text.CodePagesEncodingProvider nuget package and use System.Text.Encoding.GetEncoding(1252) instead of System.Text.Encoding.UTF8.
public static void Main(string[] args)
{
try
{
var dir = @"C:\Test";
//Get all html and htm files
var files = DirSearch(dir);
foreach (var file in files)
{
RmCode(file);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
private static void RmCode(string file)
{
string tempFile = Path.GetTempFileName();
using (var sr = new StreamReader(file, Encoding.UTF8))
using (var sw = new StreamWriter(new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite), Encoding.UTF8))
{
string line;
var startOfBadCode = "<div>";
var endOfBadCode = "</div>";
var deleteLine = false;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(startOfBadCode))
{
deleteLine = true;
}
if (!deleteLine)
{
sw.WriteLine(line);
}
if (line.Contains(endOfBadCode))
{
deleteLine = false;
}
}
}
File.Delete(file);
File.Move(tempFile, file);
}
private static List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files.Where(s => s.EndsWith(".htm") || s.EndsWith(".html")).ToList();
}
Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is 192.168.71.105, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: 192.168.71.1
The shortest way I know to generate valid json from array of integers is
let json = `[${cars}]`
for more general object/array use JSON.stringify(cars) (for object with circular references use this)
let cars = [1,2,3]; cars.push(4,5,6);
let json = `[${cars}]`;
console.log(json);
console.log(JSON.parse(json)); // json validation
_x000D_
Both getsize()
and stat()
will throw an exception if the file does not exist. This function will return True/False without throwing (simpler but less robust):
import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
I wrote an article on this subject over here. I think it could help you.
Typically it's doing something like that:
static void Main(string[] args)
{
// Convert from a DataTable source to an IEnumerable.
var usersSourceDataTable = CreateMockUserDataTable();
var usersConvertedList = usersSourceDataTable.ToEnumerable<User>();
// Convert from an IEnumerable source to a DataTable.
var usersSourceList = CreateMockUserList();
var usersConvertedDataTable = usersSourceList.ToDataTable<User>();
}
If you are making the fetch call to your localhost which I'm guessing is run by node.js in the same directory as your backbone code, than it will most likely be on http://localhost:3000
or something like that. Than this should be your model:
var model = Backbone.Model.extend({
url: '/item'
});
And in your node.js you now have to accept that call like this:
app.get('/item', function(req, res){
res.send('some info here');
});
You need
.abc,.ab {
display: none;
}
#f:hover ~ .ab {
display: block;
}
#s:hover ~ .abc {
display: block;
}
#s:hover ~ .a,
#f:hover ~ .a{
display: none;
}
Updated demo at http://jsfiddle.net/gaby/n5fzB/2/
The problem in your original CSS was that the ,
in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a
means #f:hover ~ .abc
and .a
. You set that to display:none
so it was always set to be hidden for all .a
elements.
You dont have to compile it. the first you use it (import) it is compiled by the CPython interpreter. But if you really want to compile there are several options.
To compile to exe
Or 2 compile just a specific *.py file, you can just use
import py_compile
py_compile.compile("yourpythoncode.py")
Here is an example to do that
cd /yourprojects/project-acme
git checkout efc11170c78 .
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
Try this
var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);
var i = 0, req_index = "";
$.each(json, function(index, value){
if(index == 'key2'){
req_index = i;
}
i++;
});
alert(req_index);
I am posting android Java base multi line edittext.
EditText editText = findViewById(R.id.editText);/* edittext access */
ViewGroup.LayoutParams params = editText.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/
editText.setSingleLine(false); /* Makes it Multi line */
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
I have applied the solution provided by @Levit and created function that will not call the extra Http Request.
It will solve the error Unable to Resolve Host
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) return false;
switch (activeNetwork.getType()) {
case ConnectivityManager.TYPE_WIFI:
if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
isInternet())
return true;
break;
case ConnectivityManager.TYPE_MOBILE:
if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
isInternet())
return true;
break;
default:
return false;
}
return false;
}
private static boolean isInternet() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
Debug.i(exitValue + "");
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
Now call it like,
if (!isInternetAvailable(getActivity())) {
//Show message
} else {
//Perfoem the api request
}
I often used this to get the key and value inside a dictionary: (VB.Net)
For Each kv As KeyValuePair(Of String, Integer) In layerList
Next
(layerList is of type Dictionary(Of String, Integer))
As said elsewhere on here, proguard is good, but what might not be known is that there is also a third-party maven plugin for it here http://pyx4me.com/pyx4me-maven-plugins/proguard-maven-plugin/...I've used them both together and they're very good.
function pageLoad() is very dangerous to use in this situation. You could have events become wired multiple times. I would also stay away from .live() as it attaches to the document element and has to traverse the entire page (slow and crappy).
The best solution I have seen so far is to use jQuery .delegate() function on a wrapper outside the update panel and make use of bubbling. Other then that, you could always wire up the handlers using Microsoft's Ajax library which was designed to work with UpdatePanels.
Keep the json file in Assets (parallel to app dir) directory
Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:
::app/services/myservice.ts
getOrderSummary(): Observable {
// get users from api
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
If there is no existing method then I guess you can iterate from 0 to input.size()/2
, taking each consecutive element and appending it to a new ArrayList.
EDIT: Actually, I think you can take that List and use it to instantiate a new ArrayList using one of the ArrayList constructors.
look at this function:
I had to do brew link --overwrite node
after brew install node
to update from 0.4 to 0.8.18
Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:
Here is my step-by-step for windows forms application:
Create setup project. You can use Setup Wizard.
Select project type.
Select output.
Hit Finish.
Open setup project properties.
Chose to include .NET framework.
Build setup project
Check output
Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:
Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects
There are many possibilities. Simplest way is to just use pgAdmin and get this from SQL window. However if you want to get this programmatically then examinate pg_proc
and pg_trigger
system catalogs or routines
and triggers
views from information schema (that's SQL standard way, but it might not cover all features especially PostgreSQL-specific). For example:
SELECT
routine_definition
FROM
information_schema.routines
WHERE
specific_schema LIKE 'public'
AND routine_name LIKE 'functionName';
You could simply not include the line into the new file instead of doing replace.
for line in infile :
if 'bad' not in line and 'naughty' not in line:
newopen.write(line)
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
I´ve resolved it with two simple methods.
Follow the explanation.
My existing style declaration:
<style name="SearchInfoText">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">24sp</item>
<item name="android:textColor">@color/Church_Grey</item>
<item name="android:shadowColor">@color/Shadow_Church</item>
<item name="android:shadowRadius">3</item>
<item name="android:shadowDx">1</item>
<item name="android:shadowDy">1</item>
</style>
My Android Java code:
TextView locationName = new TextView(getSupportActivity());
locationName.setId(IdGenerator.generateViewId());
locationName.setText(location.getName());
locationName.setLayoutParams(super.centerHorizontal());
locationName.setTextSize(24f);
locationName.setPadding(0, 0, 0, 15);
locationName.setTextColor(getResources().getColor(R.color.Church_Grey));
locationName.setShadowLayer(3, 1, 1, getResources().getColor(R.color.Shadow_Church));
Regards.
Most often, when $('#myModal').modal('show');
doesn't work, it's caused by having included jQuery twice. Including jQuery 2 times makes modals not to work.
Remove one of the links to make it work again.
Furthermore, some plugins cause errors too, in this case add
jQuery.noConflict();
$('#myModal').modal('show');
If you are using the Python wrappers, then (assuming your matrix name is mat):
mat.shape gives you an array of the type- [height, width, channels]
mat.size gives you the size of the array
Sample Code:
import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size
100% working this code
<a id="button" class="instagram-token-button" href="https://api.instagram.com/oauth/authorize/?client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code">Click here to get your Instagram Access Token and User ID</a>
<?PHP
if (isset($_GET['code'])) {
$code = $_GET['code'];
$client_id='< YOUR CLIENT ID >';
$redirect_uri='< YOUR REDIRECT URL >';
$client_secret='< YOUR CLIENT SECRET >';
$url='https://api.instagram.com/oauth/access_token';
$request_fields = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirect_uri,
'code' => $code
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$request_fields = http_build_query($request_fields);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_fields);
$results = curl_exec($ch);
$results = json_decode($results,true);
$access_token = $results['access_token'];
echo $access_token;
exit();
}
?>
I got solution after working whole day on it. It is little hacky solution Added span inside td tag
<td><span><%= item.StartICDate %></span></td>.
Date format which Im using is dd/MM/YYYY. Tested in Datatables1.9.0
You want to convert html (a byte-like object) into a string using .decode
, e.g. html = response.read().decode('utf-8')
.
i managed to get this working well via an automator task and have used shortcut to bind it to key combination ctrl+option+command+b. all i have to do is highlight the code i want block commented in xcode and press the above keys and the selected text is block commented out using /* ... */.
i use code folding a fair bit so the reason i wanted this functionality was so i could easily fold down a block of commented code ... code commented the usual way using // wont fold.
im not familiar with using mac automator but i simply followed the instrux in the following wwdc video
in the WWDC 2012 video Session 402 - Working Efficiently with Xcode ( from around 6 minutes in) there's a description of how to use the Mac OSX Automator to add a service to manipulate selected text. The example shown in the video is to remove duplicates in a selection of text using the shell commands sort and uniq. Using this approach you do the same but you enter the following command instead of what he does in the video
awk 'BEGIN{print "/"}{print $0}END{print "/"}'
(note there are meant to be 2 asterisks in the previous line that for some reason are not showing .... they do show up in the screenshot below so copy that as the correct command to enter)
you should end up running a shell script like this
this will, for any given selected text, put the comment delimiters before and after.
when you save it you should get options to name it (i called it blockcomment) and also to assign a keyboard shortcut
then you should be able to open xcode, select some text, right click, the context menu, and the name you gave to this script should show near the bottom
simply click the name and the script will run and block comment the selected code or use the keyboard shortcut you assigned.
hope this helps
Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo
- where BindingFlags
is not available reliably (depending on target framework).
In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:
IEnumerable<PropertyInfo> props =
type.GetTypeInfo().DeclaredProperties.Where(p =>
(p.GetMethod != null && p.GetMethod.IsStatic) ||
(p.SetMethod != null && p.SetMethod.IsStatic));
Caters for both read-only or write-only properties (despite write-only being a terrible idea).
The DeclaredProperties
member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:
var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);
There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo
query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.
It worked for me:
.vcontainer {
min-height: 10em;
display: table-cell;
vertical-align: middle;
}
Ok, Toast is no complex but it need a context object to work, it could be MyActivity.this
, then you can write:
Toast.maketext(MyActivity.this, "Toast text to show", Toast.LENGTH_SHORT).show();
Although Toast is a UI resource, then using it in another thread different to ui thread, will send an error or simply not work
If you want to print a variable, put the variable name.toString()
and concat that with text you want in the maketext String parameter ;)
Modifying Adam Rosenfield's code:
import sys
def send_msg(sock, msg):
size_of_package = sys.getsizeof(msg)
package = str(size_of_package)+":"+ msg #Create our package size,":",message
sock.sendall(package)
def recv_msg(sock):
try:
header = sock.recv(2)#Magic, small number to begin with.
while ":" not in header:
header += sock.recv(2) #Keep looping, picking up two bytes each time
size_of_package, separator, message_fragment = header.partition(":")
message = sock.recv(int(size_of_package))
full_message = message_fragment + message
return full_message
except OverflowError:
return "OverflowError."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
I would, however, heavily encourage using the original approach.
'data' should be a stringified JavaScript object:
data: JSON.stringify({ "userName": userName, "password" : password })
To send your formData
, pass it to stringify
:
data: JSON.stringify(formData)
Some servers also require the application/json
content type:
contentType: 'application/json'
There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray
The MyJsonDictionary class worked well for me EXCEPT that the resultant output is XML encoded - so "0" becomes "0030".
I am currently stuck at .NET 3.5, as are many others, so many of the other solutions are not available to me.
"Turns the pictures" upside down and realized I could never convince Microsoft to give me the format I wanted but...
string json = XmlConvert.DecodeName(xmlencodedJson);
TADA!
The result is what you would expect to see - regular human readable and non-XML encoded.
Works in .NET 3.5.
look at the basename command:
NAME="$(basename /foo/fizzbuzz.bar .bar)"
instructs it to remove the suffix .bar
, results in NAME=fizzbuzz
Notice: this answer promotes a tool I've written.
The selected answer here suggests to install an SSH server into every image. Conceptually this is not the right approach (https://docs.docker.com/articles/dockerfile_best-practices/).
I've created a containerized SSH server that you can 'stick' to any running container. This way you can create compositions with every container. The only requirement is that the container has bash.
The following example would start an SSH server exposed on port 2222 of the local machine.
$ docker run -d -p 2222:22 \
-v /var/run/docker.sock:/var/run/docker.sock \
-e CONTAINER=my-container -e AUTH_MECHANISM=noAuth \
jeroenpeeters/docker-ssh
$ ssh -p 2222 localhost
For more pointers and documentation see: https://github.com/jeroenpeeters/docker-ssh
Not only does this defeat the idea of one process per container, it is also a cumbersome approach when using images from the Docker Hub since they often don't (and shouldn't) contain an SSH server.
You can do the following to learn/test the concept:
Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module
In newly added Module1 add the declaration; Public Global1 As String
in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:
Sub setMe() Global1 = "Hello" End Sub
Sub showMe() Debug.Print (Global1) End Sub
setMe()
and then Sub showMe()
to test the global visibility/accessibility of the var Global1
Hope this will help.
First of all, in C++ linked-lists shouldn't be much more trouble to work with than an array. You can use the std::list or the boost pointer list for linked lists. The key issues with linked lists vs arrays are extra space required for pointers and terrible random access. You should use a linked list if you
Angular.js has a built-in date filter.
// in your controller:
$scope.date = '20140313T00:00:00';
// in your view, date property, filtered with date filter and format 'MM/dd/yyyy'
<p ng-bind="date | date:'MM/dd/yyyy'"></p>
// produces
03/13/2014
You can see the supported date formats in the source for the date filter.
edit:
If you're trying to get the correct format in the datepicker (not clear if you're using datepicker or just trying to use it's formatter), those supported format strings are here: https://api.jqueryui.com/datepicker/
In My Case, after a fews days of research,
All I did to revolve is listed below:
This should work for similar codesign issues.
Note, during this process the OS would ask for your credential validation.
Set your positional arguments with nargs, and check if positional args are empty.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
parser.print_help()
Reference Python nargs
Basically you have two options
scale_x_continuous(limits = c(-5000, 5000))
or
coord_cartesian(xlim = c(-5000, 5000))
Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.
You can also use the shorthand function xlim
(or ylim
), which like the first option removes data points outside of the given range:
+ xlim(-5000, 5000)
For more information check the description of coord_cartesian
.
The RStudio cheatsheet for ggplot2
makes this quite clear visually. Here is a small section of that cheatsheet:
Distributed under CC BY.
There is a boolean contains(Object obj) method within the List interface.
You should be able to say:
if (list.contains("a")) {
System.out.println("It's there");
}
According to the javadoc:
boolean contains(Object o)
Returns true if this list contains the specified element.
More formally, returns true if and only if this list contains at
least one element e such that (o==null ? e==null : o.equals(e)).
Note that ng-bind-html-unsafe is no longer suppported in rc 1.2. Use ng-bind-html instead. See: With ng-bind-html-unsafe removed, how do I inject HTML?
Integrated Security
and User ID
\ Password
authentication are mutually exclusive. To connect to SQL Server as the user running the code, remove User ID
and Password
from your connection string:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
To connect with specific credentials, remove Integrated Security
:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
there one more option that allows to get "select" size with joins, and table size as option too
-- 1
EXPLAIN PLAN
FOR
SELECT
Scheme.Table_name.table_column1 AS "column1",
Scheme.Table_name.table_column2 AS "column2",
Scheme.Table_name.table_column3 AS "column3",
FROM Scheme.Table_name
WHERE ;
SELECT * FROM TABLE (DBMS_XPLAN.display);
To list mongodb database on shell
show databases //Print a list of all available databases.
show dbs // Print a list of all databases on the server.
Few more basic commands
use <db> // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections //Print a list of all collections for current database.
show users //Print a list of users for current database.
show roles //Print a list of all roles, both user-defined and built-in, for the current database.
System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
make sure you're using the newest jquery, and problem solved
I met this problem with this code:
<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
After change it to this:
<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
It works fine
Try like this,
jQuery('.leaderMultiSelctdropdown').select2('data');