The MySQL server can be started manually from the command line. This can be done on any version of Windows.
To start the mysqld server from the command line, you should start a console window (or “DOS window”) and enter this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld"
The path to mysqld may vary depending on the install location of MySQL on your system.
You can stop the MySQL server by executing this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqladmin" -u root shutdown
**Note : **
If the MySQL root user account has a password, you need to invoke mysqladmin with the -p option and supply the password when prompted.
This command invokes the MySQL administrative utility mysqladmin to connect to the server and tell it to shut down. The command connects as the MySQL root user, which is the default administrative account in the MySQL grant system. Note that users in the MySQL grant system are wholly independent from any login users under Windows.
If mysqld doesn't start, check the error log to see whether the server wrote any messages there to indicate the cause of the problem. The error log is located in the C:\Program Files\MySQL\MySQL Server 5.0\data directory. It is the file with a suffix of .err. You can also try to start the server as mysqld --console; in this case, you may get some useful information on the screen that may help solve the problem.
The last option is to start mysqld with the --standalone and --debug options. In this case, mysqld writes a log file C:\mysqld.trace that should contain the reason why mysqld doesn't start. See MySQL Internals: Porting to Other Systems.
@echo off & setLocal EnableDelayedExpansion
for /L %%a in (1 1 100) do (
echo !random!
)
Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
(which references 32-bit programs) for part of the name of the program, or
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
(if it actually was a 64-bit program).
If you find something that matches your program in one of those, the contents of UninstallString
in that key usually give you the exact command you are looking for (that you can run in a script).
If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.
Then in a .bat script you can do
if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)
You can save it using the Save As dialog using ".something".
Execute gpedit.msc (local Policies)
Computer Configuration -> Windows settings -> Scripts -> Shutdown -> Properties -> Add
This happens because Oracle dropped support for Windows XP (which doesn't have RegDeleteKeyExA
used by the installer in its ADVAPI32.DLL
by the way) as described in http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-July/009005.html. Yet while the official support for XP has ended, the Java binaries are still (as of Java 8u20 EA b05 at least) XP-compatible - only the installer isn't...
Because of that, the solution is actually quite easy:
get 7-Zip (or any other good unpacker), unpack the distribution .exe manually, it has one .zip file inside of it (tools.zip
), extract it too,
use unpack200
from JDK8 to unpack all .pack files to .jar files (older unpacks won't work properly); JAVA_HOME
environment variable should be set to your Java unpack root, e.g. "C:\Program Files\Java\jdk8" - you can specify it implicitly by e.g.
SET JAVA_HOME=C:\Program Files\Java\jdk8
Unpack all files with a single command (in batch file):
FOR /R %%f IN (*.pack) DO "%JAVA_HOME%\bin\unpack200.exe" -r -v "%%f" "%%~pf%%~nf.jar"
Unpack all files with a single command (command line from JRE root):
FOR /R %f IN (*.pack) DO "bin\unpack200.exe" -r -v "%f" "%~pf%~nf.jar"
Unpack by manually locating the files and unpacking them one-by-one:
%JAVA_HOME%\bin\unpack200 -r packname.pack packname.jar
where packname
is for example rt
point the tool you want to use (e.g. Netbeans) to the %JAVA_HOME%
and you're good to go.
Note: you probably shouldn't do this just to use Java 8 in your web browser or for any similar reason (installing JRE 8 comes to mind); security flaws in early updates of major Java version releases are (mind me) legendary, and adding to that no real support for neither XP nor Java 8 on XP only makes matters much worse. Not to mention you usually don't need Java in your browser (see e.g. http://nakedsecurity.sophos.com/2013/01/15/disable-java-browsers-homeland-security/ - the topic is already covered on many pages, just Google it if you require further info). In any case, AFAIK the only thing required to apply this procedure to JRE is to change some of the paths specified above from \bin\
to \lib\
(the file placement in installer directory tree is a bit different) - yet I strongly advise against doing it.
See also: How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?, JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object
Assuming you have two programs that process the two files, process_in.exe and process_out.exe:
for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.
Creating static library worked for me, compiling using g++ -static
. It bundles the dependent libraries along with the build.
If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:
NET USE z: \server\c$\folder1\folder2
NET USE y: \server\d$
Note that you can map drive-to-drive or drill down and map to sub-folder.
These are the steps to share a folder from Windows to Linux Virtual Box
Step 1 : Install Virtual Box Extension Pack from this link
Step 2: Install Oracle Guest Additions:
By pressing -> Right Ctrl
and d
together
Run the command
sudo /media/VBOXADDITIONS_4.*/VBoxLinuxAdditions.run
Step 3 : Create Shared Folder by Clicking Settings in Vbox
Then Shared Folders -> + and give a name to the folder (e.g. VB_Share)
Select the Shared Folder path on Windows (e.g. D:\VBox_Share)
Step 4: Create a folder in named VB_share
in home\user-name
(e.g. home\satish\VB_share) and share
mkdir VB_Share
chmod 777 VB_share
Step 5: Run the following command
sudo mount –t vboxsf vBox_Share VB_Share
You can use binary file of curl .download file from here : http://www.paehl.com/open_source/?CURL_7.22.0 Download the file and after extract put in to any drive and set the absolute path into environment now you can also use curl as a command in windows. like c:\curl -u [email protected]:password http://localhost:3000/user/sign_in
workmad3 is apparently out of date, at least for current gpg, as the --allow-secret-key-import
is now obsolete and does nothing.
What happened to me was that I failed to export properly. Just doing gpg --export
is not adequate, as it only exports the public keys. When exporting keys, you have to do
gpg --export-secret-keys >keyfile
Just put your file.exe in the \bin\Debug folder and use:
Process.Start("File.exe");
That agony has been solved for me. I found out that what was taking over port 80 is http api service. I wrote in cmd:
net stop http
Asked me "The following services will be stopped, do you want to continue?" Pressed y
It stopped a number of services actually.
Then wrote localhost
and wallah, Apache is up and running on port 80.
Hope this helps
Important: Skype uses port 80 by default, you can change this in skype options > advanced > connection - and uncheck "use port 80"
You can download manually by parsing the XMLs that you see in Android SDK Manager log.
Currently the XMLs are addon_list and repository. These xmls can change over a course of time.
It has the location of the SDKs, you can browse to the link and download directly via browser. These files has to be placed under proper folder, example the files of google APIs has to be placed under add-ons
, if you don't know where the files has to go.
Here is something to help you.
The blogpost from my blog to Install Android SDKs offline --> Offline Installation of Android SDK's
Instead of telling you how you could execute a certain command (Esc:wq), I can provide you two links that may help you with VIM:
However, the best way to learn Vim is not only using it for Git commits, but as a regular editor for your everyday work.
If you're not going to switch to Vim, it's nonsense to keep its commands in mind. In that case, go and set up your favourite editor to use with Git.
Actually it is 256, see File System Functionality Comparison, Limits.
To repeat a post on http://fixunix.com/microsoft-windows/30758-windows-xp-file-name-length-limit.html
"Assuming we're talking about NTFS and not FAT32, the "255 characters for path+file" is a limitation of Explorer, not the filesystem itself. NTFS supports paths up to 32,000 Unicode characters long, with each component up to 255 characters.
Explorer -and the Windows API- limits you to 260 characters for the path, which include drive letter, colon, separating slashes and a terminating null character. It's possible to read a longer path in Windows if you start it with a
\\
"
If you read the above posts you'll see there is a 5th thing you can be certain of: Finding at least one obstinate computer user!
You could try this via SSH:
rm -rf foldernamehere
Way around would be moving M2
from user variables to system variables
the better way to resolve the issue is change the port number in Apache2\conf\httpd.conf . Change the port number as fallows::: Listen 8888 and ServerName machinename:8888 .Restart the Apache server after changing the port number.
I have PHP 5.3.1 and Apache
When I add the extension=php_intl.dll
to php.ini and restart apache, it comes an alert that says "the requested operation has failed"
And this error on Event Monitor:
Faulting application name: httpd.exe, version: 2.2.14.0, time stamp: 0x4ac181d6
Faulting module name: php5ts.dll, version: 5.3.1.0, time stamp: 0x4b051b35
Exception code: 0xc0000005
The problem was some DLLs like icudt36.dll were missing (noticed with sysinternals ProcMon), I've downloaded php 5.3.1 zip version and extract all DLL's to PHP folder. That solved the problem.
Use parentheses to group the individual branches:
IF EXIST D:\RPS_BACKUP\backups_to_zip\ (goto zipexist) else goto zipexistcontinue
In your case the parser won't ever see the else
belonging to the if
because goto
will happily accept everything up to the end of the command. You can see a similar issue when using echo
instead of goto
.
Also using parentheses will allow you to use the statements directly without having to jump around (although I wasn't able to rewrite your code to actually use structured programming techniques; maybe it's too early or it doesn't lend itself well to block structures as the code is right now).
I use the mouse:
Actually, the following works fine for me and creates new windows:
test.cmd:
@echo off
start test2.cmd
start test3.cmd
echo Foo
pause
test2.cmd
@echo off
echo Test 2
pause
exit
test3.cmd
@echo off
echo Test 3
pause
exit
Combine that with parameters to start
, such as /min
, as Moshe pointed out if you don't want the new windows to spawn in front of you.
rmdir /s /q folder
powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"
Note that in more cases del
and rmdir
wil leave you with leftover files, where Powershell manages to delete the files.
Here is my PowerShell method
gci env:* | sort-object name | Where-Object {$_.Name -like "MyApp*"} | Foreach {"[System.Environment]::SetEnvironmentVariable('$($_.Name)', '$($_.Value)', 'Machine')"}
What it does
So after running this on the source machine, simply transfer output onto the target machine and execute (elevated prompt if setting at machine level)
I created the Path Length Checker tool for this purpose, which is a nice, free GUI app that you can use to see the path lengths of all files and directories in a given directory.
I've also written and blogged about a simple PowerShell script for getting file and directory lengths. It will output the length and path to a file, and optionally write it to the console as well. It doesn't limit to displaying files that are only over a certain length (an easy modification to make), but displays them descending by length, so it's still super easy to see which paths are over your threshold. Here it is:
$pathToScan = "C:\Some Folder" # The path to scan and the the lengths for (sub-directories will be scanned as well).
$outputFilePath = "C:\temp\PathLengths.txt" # This must be a file in a directory that exists and does not require admin rights to write to.
$writeToConsoleAsWell = $true # Writing to the console will be much slower.
# Open a new file stream (nice and fast) and write all the paths and their lengths to it.
$outputFileDirectory = Split-Path $outputFilePath -Parent
if (!(Test-Path $outputFileDirectory)) { New-Item $outputFileDirectory -ItemType Directory }
$stream = New-Object System.IO.StreamWriter($outputFilePath, $false)
Get-ChildItem -Path $pathToScan -Recurse -Force | Select-Object -Property FullName, @{Name="FullNameLength";Expression={($_.FullName.Length)}} | Sort-Object -Property FullNameLength -Descending | ForEach-Object {
$filePath = $_.FullName
$length = $_.FullNameLength
$string = "$length : $filePath"
# Write to the Console.
if ($writeToConsoleAsWell) { Write-Host $string }
#Write to the file.
$stream.WriteLine($string)
}
$stream.Close()
You can retrieve the series through slicing your dataframe using one of these two methods:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html
import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randn(1,8))
series1=df.iloc[0,:]
type(series1)
pandas.core.series.Series
Visual Studio 2017 Team Explorer
According to https://blogs.msdn.microsoft.com/bharry/2017/04/05/team-explorer-for-tfs-2017/ you can now download it separately from Visual Studio via this link:
https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=TeamExplorer&rel=15
Just for clarification, CorFlags.exe is part of the .NET Framework SDK. I have the development tools on my machine, and the simplest way for me determine whether a DLL is 32-bit only is to:
Open the Visual Studio Command Prompt (In Windows: menu Start/Programs/Microsoft Visual Studio/Visual Studio Tools/Visual Studio 2008 Command Prompt)
CD to the directory containing the DLL in question
Run corflags like this:
corflags MyAssembly.dll
You will get output something like this:
Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Version : v2.0.50727
CLR Header: 2.5
PE : PE32
CorFlags : 3
ILONLY : 1
32BIT : 1
Signed : 0
As per comments the flags above are to be read as following:
You can try to install a demo certificate (some ssl providers offers them for free for a month) to be sure if the problem is related to cert validity or not.
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
For me the android:scaleType="centerCrop" did not resolve my problem. It actually expanded the image way more. So I tried with android:scaleType="fitXY" and It worked excellent.
You could try hbase api methods!
org.apache.hadoop.hbase.client.coprocessor.AggregationClient
After t.thielemans' answer, I worked that just
=VLOOKUP(A1, B:C, 2, FALSE)
works fine and does what I wanted, except that it returns #N/A
for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.
Edit (based on t.thielemans' comment):
To avoid #N/A
for non-matches, do:
=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
In SQL Server 2012 it is very very easy
SELECT col1, col2, ...
FROM ...
WHERE ...
ORDER BY -- this is a MUST there must be ORDER BY statement
-- the paging comes here
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
If we want to skip ORDER BY we can use
SELECT col1, col2, ...
...
ORDER BY CURRENT_TIMESTAMP
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
(I'd rather mark that as a hack - but it's used, e.g. by NHibernate. To use a wisely picked up column as ORDER BY is preferred way)
to answer the question:
--SQL SERVER 2012
SELECT PostId FROM
( SELECT PostId, MAX (Datemade) as LastDate
from dbForumEntry
group by PostId
) SubQueryAlias
order by LastDate desc
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
New key words offset
and fetch next
(just following SQL standards) were introduced.
But I guess, that you are not using SQL Server 2012, right? In previous version it is a bit (little bit) difficult. Here is comparison and examples for all SQL server versions: here
So, this could work in SQL Server 2008:
-- SQL SERVER 2008
DECLARE @Start INT
DECLARE @End INT
SELECT @Start = 10,@End = 20;
;WITH PostCTE AS
( SELECT PostId, MAX (Datemade) as LastDate
,ROW_NUMBER() OVER (ORDER BY PostId) AS RowNumber
from dbForumEntry
group by PostId
)
SELECT PostId, LastDate
FROM PostCTE
WHERE RowNumber > @Start AND RowNumber <= @End
ORDER BY PostId
In Laravel, I'm use:
private function getValueFromString(string $string, string $key)
{
parse_str(parse_url($string, PHP_URL_QUERY), $result);
return isset($result[$key]) ? $result[$key] : null;
}
My own suggestion is as follows:
function nativeSelector() {
var elements = document.querySelectorAll("body, body *");
var results = [];
var child;
for(var i = 0; i < elements.length; i++) {
child = elements[i].childNodes[0];
if(elements[i].hasChildNodes() && child.nodeType == 3) {
results.push(child);
}
}
return results;
}
var textnodes = nativeSelector(),
_nv;
for (var i = 0, len = textnodes.length; i<len; i++){
_nv = textnodes[i].nodeValue;
textnodes[i].nodeValue = _nv.replace(/£/g,'€');
}
The nativeSelector()
function comes from an answer (posted by Anurag) to this question: getElementsByTagName() equivalent for textNodes.
Actually I cannot reproduce the problem. The script as written in the question works fine, except for the case where $1 is empty.
However, there is a problem in the script related to redirection of stderr
. Although the two forms &>
and >&
exist, in your case you want to use >&
. You already redirected stdout
, that's why the form &>
does not work. You can easily verify it this way:
getent /etc/passwd username >/dev/null 2&>1
ls
You will see a file named 1
in the current directory. You want to use 2>&1
instead, or use this:
getent /etc/passwd username &>/dev/null
This also redirects stdout
and stderr
to /dev/null
.
Warning Redirecting stderr
to /dev/null
might not be such a good idea. When things go wrong, you will have no clue why.
You can use DateTime
import org.joda.time.DateTime
Option 1 : with yyyyMMddHHmmss
DateTime.now().toString("yyyyMMddHHmmss")
Will give 20190205214430
Option 2 : yyyy-dd-M--HH-mm-ss
DateTime.now().toString("yyyy-dd-M--HH-mm-ss")
will give 2019-05-2--21-43-32
use this attribute in style
font-size: 11px !important;//your font size
by !important it override your css
Solution using Java 8
features such as Stream API
and Method references
new BufferedReader(new StringReader(myString))
.lines().forEach(System.out::println);
or
public void someMethod(String myLongString) {
new BufferedReader(new StringReader(myLongString))
.lines().forEach(this::parseString);
}
private void parseString(String data) {
//do something
}
I have resolved this same issue by doing below steps:
File > Close Project
Import Project
Select you project via the system file popup
Check "Import project from external model" radio button and select Maven entry
And some Next buttons (select JDK, ...)
Then the project will be imported as Maven module.
Unfortunately .NET doesn't provide a way to do that natively.
To address this issue I created the OSS library Genumerics which provides most standard numeric operations for the following built-in numeric types and their nullable equivalents with the ability to add support for other numeric types.
sbyte
, byte
, short
, ushort
, int
, uint
, long
, ulong
, float
, double
, decimal
, and BigInteger
The performance is equivalent to a numeric type specific solution allowing you to create efficient generic numeric algorithms.
Here's an example of the code usage.
public static T Sum(T[] items)
{
T sum = Number.Zero<T>();
foreach (T item in items)
{
sum = Number.Add(sum, item);
}
return sum;
}
public static T SumAlt(T[] items)
{
// implicit conversion to Number<T>
Number<T> sum = Number.Zero<T>();
foreach (T item in items)
{
// operator support
sum += item;
}
// implicit conversion to T
return sum;
}
Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r
: r"Hello\tWorld\nHello World"
.
>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World
Also, \s
is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.
Use the all()
function with a generator expression:
>>> my_list1 = [30, 34, 56]
>>> my_list2 = [29, 500, 43]
>>> all(i >= 30 for i in my_list1)
True
>>> all(i >= 30 for i in my_list2)
False
Note that this tests for greater than or equal to 30, otherwise my_list1
would not pass the test either.
If you wanted to do this in a function, you'd use:
def all_30_or_up(ls):
for i in ls:
if i < 30:
return False
return True
e.g. as soon as you find a value that proves that there is a value below 30, you return False
, and return True
if you found no evidence to the contrary.
Similarly, you can use the any()
function to test if at least 1 value matches the condition.
I believe to check if a key exists in a hash you just do
if (exists $strings{$string}) {
...
} else {
...
}
The way to keep SELECT dbo.fCalculateEstimateDate(647)
call working is:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100) AS
Declare @Result varchar(100)
SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
Return @Result
Begin
End
CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100) AS
Begin
<Function Body>
End
SQL SERVER 2005:
print upper('hello');
print lower('HELLO');
The previous answers are a little dated. I found that all you need to do is query the TARGET_IPHONE_SIMULATOR
macro (no need to include any other header files [assuming you are coding for iOS]).
I attempted TARGET_OS_IPHONE
but it returned the same value (1) when running on an actual device and simulator, that's why I recommend using TARGET_IPHONE_SIMULATOR
instead.
If you need to work with games. As explained in this post https://www.learncodebygaming.com/blog/pyautogui-not-working-use-directinput, some games like Minecraft or Fortnite have their own way of registering mouse / keyboard events. The way to control mouse and keyboard events is by using the brand new PyDirectInput library. Their github repository is https://github.com/learncodebygaming/pydirectinput, and has a lot of great information.
Here's a quick code that does a mouse loop, and clicks:
import pydirectinput # pip install pydirectinput
pydirectinput.moveTo(0, 500)
pydirectinput.click()
See:
Code:
var strDate = "03.09.1979";
var dateParts = strDate.split(".");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
Instead of dtAll = dtOne.Copy();
in Jeromy Irvine's answer you can start with an empty DataTable
and merge one-by-one iteratively:
dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...
and so on.
This technique is useful in a loop where you want to iteratively merge data tables:
DataTable dtAllCountries = new DataTable();
foreach(String strCountry in listCountries)
{
DataTable dtCountry = getData(strCountry); //Some function that returns a data table
dtAllCountries.Merge(dtCountry);
}
Use the implode()
function:
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
This is excellent practice.
By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.
This way:
If the name of the variable is a bit "generic" (like "i"), there is no risk to mix it with another variable of same name somewhere later in your code (can also be mitigated using the -Wshadow
warning instruction on GCC)
The compiler knows that the variable scope is limited to inside the loop, and therefore will issue a proper error message if the variable is by mistake referenced elsewhere.
Last but not least, some dedicated optimization can be performed more efficiently by the compiler (most importantly register allocation), since it knows that the variable cannot be used outside of the loop. For example, no need to store the result for later re-use.
In short, you are right to do it.
Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time. You can also create a larger block, encompassing the loop, whose sole purpose is to declare variables which must retain their value from one loop to another. This typically includes the loop counter itself.
{
int i, retainValue;
for (i=0; i<N; i++)
{
int tmpValue;
/* tmpValue is uninitialized */
/* retainValue still has its previous value from previous loop */
/* Do some stuff here */
}
/* Here, retainValue is still valid; tmpValue no longer */
}
For question #2: The variable is allocated once, when the function is called. In fact, from an allocation perspective, it is (nearly) the same as declaring the variable at the beginning of the function. The only difference is the scope: the variable cannot be used outside of the loop. It may even be possible that the variable is not allocated, just re-using some free slot (from other variable whose scope has ended).
With restricted and more precise scope come more accurate optimizations. But more importantly, it makes your code safer, with less states (i.e. variables) to worry about when reading other parts of the code.
This is true even outside of an if(){...}
block. Typically, instead of :
int result;
(...)
result = f1();
if (result) then { (...) }
(...)
result = f2();
if (result) then { (...) }
it's safer to write :
(...)
{
int const result = f1();
if (result) then { (...) }
}
(...)
{
int const result = f2();
if (result) then { (...) }
}
The difference may seem minor, especially on such a small example.
But on a larger code base, it will help : now there is no risk to transport some result
value from f1()
to f2()
block. Each result
is strictly limited to its own scope, making its role more accurate. From a reviewer perspective, it's much nicer, since he has less long range state variables to worry about and track.
Even the compiler will help better : assuming that, in the future, after some erroneous change of code, result
is not properly initialized with f2()
. The second version will simply refuse to work, stating a clear error message at compile time (way better than run time). The first version will not spot anything, the result of f1()
will simply be tested a second time, being confused for the result of f2()
.
The open-source tool CppCheck (a static analysis tool for C/C++ code) provides some excellent hints regarding optimal scope of variables.
In response to comment on allocation: The above rule is true in C, but might not be for some C++ classes.
For standard types and structures, the size of variable is known at compilation time. There is no such thing as "construction" in C, so the space for the variable will simply be allocated into the stack (without any initialization), when the function is called. That's why there is a "zero" cost when declaring the variable inside a loop.
However, for C++ classes, there is this constructor thing which I know much less about. I guess allocation is probably not going to be the issue, since the compiler shall be clever enough to reuse the same space, but the initialization is likely to take place at each loop iteration.
For footer change from position: relative;
to position:fixed;
footer {
background-color: #333;
width: 100%;
bottom: 0;
position: fixed;
}
Example: http://jsfiddle.net/a6RBm/
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
$mylabel.text( $mylabel.text().replace('-', '') );
Since text()
gets the value, and text( "someValue" )
sets the value, you just place one inside the other.
Would be the equivalent of doing:
var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );
EDIT:
I hope I understood the question correctly. I'm assuming $mylabel
is referencing a DOM element in a jQuery object, and the string is in the content of the element.
If the string is in some other variable not part of the DOM, then you would likely want to call the .replace()
function against that variable before you insert it into the DOM.
Like this:
var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );
or a more verbose version:
var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );
You can not put
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.
Instead of using the "c" tags, you could also do the following:
<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />
<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>
I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?
Execute:
rails generate migration add_column_to_table column:boolean
It will generate this migration:
class AddColumnToTable < ActiveRecord::Migration
def change
add_column :table, :column, :boolean
end
end
Set the default value adding :default => 1
add_column :table, :column, :boolean, :default => 1
Run:
rake db:migrate
The error you have is because -credential
without -computername
can't exist.
You can try this way:
Invoke-Command -Credential $migratorCreds -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME
Declare an instance of the CBetfairAPI class or make it static.
Though they operate the same way, however, the mouseenter
event only triggers when the mouse pointer enters the selected element. The mouseover
event is triggered if a mouse pointer enters any child elements as well.
You can achieved by use bootstrap Spacing. Bootstrap Spacing includes a wide range of shorthand responsive margin and padding. In below example mr-1
set the margin
or padding
to $spacer
* .25.
Example:
<button class="btn btn-outline-primary mr-1" href="#">Sign up</button>
<button class="btn btn-outline-primary" href="#">Login</button>
You can read more at Bootstrap Spacing.
For C# user, run this simple Console App to understand how to verify the one time token code. Note that we need to install library Otp.Net from Nuget package first.
static string secretKey = "JBSWY3DPEHPK3PXP"; //add this key to your Google Authenticator app
private static void Main(string[] args)
{
var bytes = Base32Encoding.ToBytes(secretKey);
var totp = new Totp(bytes);
while (true)
{
Console.Write("Enter your code from Google Authenticator app: ");
string userCode = Console.ReadLine();
//Generate one time token code
string tokenInApp = totp.ComputeTotp();
int remainingSeconds = totp.RemainingSeconds();
if (userCode.Equals(tokenInApp)
&& remainingSeconds > 0)
{
Console.WriteLine("Success!");
}
else
{
Console.WriteLine("Failed. Try again!");
}
}
}
For a more flexible and lazy solution, you could match all properties of the objects. Most of the time, this should get you the behavior you want, and you can always be more specific when it doesn't. Here's a grep function that works based on this principle:
Function Select-ObjectPropertyValues {
param(
[Parameter(Mandatory=$true,Position=0)]
[String]
$Pattern,
[Parameter(ValueFromPipeline)]
$input)
$input | Where-Object {($_.PSObject.Properties | Where-Object {$_.Value -match $Pattern} | Measure-Object).count -gt 0} | Write-Output
}
I'm using Mac and I struggled to find the solution. My remote address was right and as said, it was a credentials problem. Apparently, in the past I used another Git Account on my computer and the mac's Keychain remembered the credentials of the previous account, so I really wasn't authorised to push.
How to fix? Open Keychain Access on your mac, choose "All Items" category and search for git. Delete all results found.
Now go to the terminal and try to push again. The terminal will ask for username and password. Enter the new relevant credentials and that's it!
Hope it'll help someone. I struggled it for few hours.
$(function () {_x000D_
$('#Add').click(function () {_x000D_
$('<p>Text</p>').appendTo('#Content');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
<button id="Add">Add<button>_x000D_
</div>
_x000D_
In addition to Sudheesh R
Add Ripple Effect/Animation to a Android Button with button rectangle shape with corner
Create xml file res/drawable/your_file_name.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:color="@color/colorWhite"
tools:targetApi="lollipop">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimaryDark" />
<corners android:radius="50dp" />
</shape>
</item>
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="@color/colorAccent"
android:startColor="@color/colorPrimary"
android:type="linear" />
<corners android:radius="50dp" />
</shape>
</item>
</ripple>
I just ran into this issue as well. There's an option to "refresh fields", which I found useful. What I didn't find intuitive at first was that one has to enter values used to execute the query in such a fashion as to refresh the fields. Once I figured this out, and refreshed the fields - things worked. The data sets and the shared dataset that's being called have to correlate.
Add -m to the recommended answer above to prune empty directories.
This is from a php script which solves the problem perfectly with every browser I've tested (FF since 3.5, IE8+, Chrome)
header("Content-Disposition: attachment; filename=\"".$fname_local."\"");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fname));
So as far as I can see, you're doing everything correctly. Have you checked your browser settings?
Here I got the error:
Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
Because you didn't pass a base64-encoded string. Look at your functions: both download
and dataURItoBlob
do expect a data URI for some reason; you however are passing a plain html markup string to download
in your example.
Not only is HTML invalid as base64, you are calling .split(',')[1]
on it which will yield undefined
- and "undefined"
is not a valid base64-encoded string either.
I don't know, but I read that I need to encode my string to base64
That doesn't make much sense to me. You want to encode it somehow, only to decode it then?
What should I call and how?
Change the interface of your download
function back to where it received the filename
and text
arguments.
Notice that the BlobBuilder
does not only support appending whole strings (so you don't need to create those ArrayBuffer
things), but also is deprecated in favor of the Blob
constructor.
Can I put a name on my saved file?
Yes. Don't use the Blob
constructor, but the File
constructor.
function download(filename, text) {
try {
var file = new File([text], filename, {type:"text/plain"});
} catch(e) {
// when File constructor is not supported
file = new Blob([text], {type:"text/plain"});
}
var url = window.URL.createObjectURL(file);
…
}
download('test.html', "<html>" + document.documentElement.innerHTML + "</html>");
See JavaScript blob filename without link on what to do with that object url, just setting the current location to it doesn't work.
Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page
In response to @MiniQuark's answer:
I was trying to read in a csv file that was half-French (containing accents) and also some strings which would eventually become integers and floats.
As a test, I created a test.txt
file that looked like this:
Montréal, über, 12.89, Mère, Françoise, noël, 889
I had to include lines 2
and 3
to get it to work (which I found in a python ticket), as well as incorporate @Jabba's comment:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import csv
import unicodedata
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
with open('test.txt') as f:
read = csv.reader(f)
for row in read:
for element in row:
print remove_accents(element)
The result:
Montreal
uber
12.89
Mere
Francoise
noel
889
(Note: I am on Mac OS X 10.8.4 and using Python 2.7.3)
Tried and working. you are using,
<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
I am using javascript , (don't know about php), use id ="status" in textarea like
<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag
<srcipt>
function UpdateStatus(){
//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({
type:"GET",//or POST
url:'http://localhost:7080/ajaxforjson/Testajax',
// (or whatever your url is)
data:{data1:var1},
//can send multipledata like {data1:var1,data2:var2,data3:var3
//can use dataType:'text/html' or 'json' if response type expected
success:function(responsedata){
// process on data
alert("got response as "+"'"+responsedata+"'");
}
})
}
</script>
and jsp is like
the servlet will look like: //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")
public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String data1=request.getParameter("data1");
//do processing on datas pass in other java class to add to DB
// i am adding or concatenate
String data="i Got : "+"'"+data1+"' ";
System.out.println(" data1 : "+data1+"\n data "+data);
response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Using the .val()
function on a multi-select list will return an array of the selected values:
var selectedValues = $('#multipleSelect').val();
and in your html:
<select id="multipleSelect" multiple="multiple">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
AngularJs has "Services" and "Factories" just for problems like yours.These are used to have something global between Controllers, Directives, Other Services or any other angularjs components..You can defined functions, store data, make calculate functions or whatever you want inside Services and use them in AngularJs Components as Global.like
angular.module('MyModule', [...])
.service('MyService', ['$http', function($http){
return {
users: [...],
getUserFriends: function(userId){
return $http({
method: 'GET',
url: '/api/user/friends/' + userId
});
}
....
}
}])
if you need more
Find More About Why We Need AngularJs Services and Factories
Have you ever thought the C# compiler could generate invalid CIL? Run this and you'll get a TypeLoadException
:
interface I<T> {
T M(T p);
}
abstract class A<T> : I<T> {
public abstract T M(T p);
}
abstract class B<T> : A<T>, I<int> {
public override T M(T p) { return p; }
public int M(int p) { return p * 2; }
}
class C : B<int> { }
class Program {
static void Main(string[] args) {
Console.WriteLine(new C().M(42));
}
}
I don't know how it fares in the C# 4.0 compiler though.
EDIT: this is the output from my system:
C:\Temp>type Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1 {
interface I<T> {
T M(T p);
}
abstract class A<T> : I<T> {
public abstract T M(T p);
}
abstract class B<T> : A<T>, I<int> {
public override T M(T p) { return p; }
public int M(int p) { return p * 2; }
}
class C : B<int> { }
class Program {
static void Main(string[] args) {
Console.WriteLine(new C().M(11));
}
}
}
C:\Temp>csc Program.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.
C:\Temp>Program
Unhandled Exception: System.TypeLoadException: Could not load type 'ConsoleAppli
cation1.C' from assembly 'Program, Version=0.0.0.0, Culture=neutral, PublicKeyTo
ken=null'.
at ConsoleApplication1.Program.Main(String[] args)
C:\Temp>peverify Program.exe
Microsoft (R) .NET Framework PE Verifier. Version 3.5.30729.1
Copyright (c) Microsoft Corporation. All rights reserved.
[token 0x02000005] Type load failed.
[IL]: Error: [C:\Temp\Program.exe : ConsoleApplication1.Program::Main][offset 0x
00000001] Unable to resolve token.
2 Error(s) Verifying Program.exe
C:\Temp>ver
Microsoft Windows XP [Version 5.1.2600]
Just to say one thing, WindowsAPICodePack
can not open CommonOpenFileDialog
on Windows 7 6.1.7600.
As above is great example and works great:
Typeface font = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf" );
Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);
BUT! > this will work if string inside button you set from xml:
<string name="icon_heart"></string>
button.setText(getString(R.string.icon_heart));
If you need to add it dynamically can use this:
String iconHeart = "";
String valHexStr = iconHeart.replace("&#x", "").replace(";", "");
long valLong = Long.parseLong(valHexStr,16);
button.setText((char) valLong + "");
You can also save a reference to module's global scope outside the (module.)exports.somemodule definition:
var _this = this;
exports.somefunction = function() {
console.log('hello');
}
exports.someotherfunction = function() {
_this.somefunction();
}
xhr.getResponseHeader('Set-Cookie');
It won't work for me.
I use this
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
success: function(output, status, xhr) {
alert(getCookie("MyCookie"));
},
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
Following this resource page, if the length of x is varying, we can use:
', '.join(['%.2f']*len(x))
to create a place holder for each element from the list x
. Here is the example:
x = [1/3.0, 1/6.0, 0.678]
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x)
print s
>>> elements in the list are [0.33, 0.17, 0.68]
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.getJSON('people.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
My JSON
file:
{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}
I succeeded in integrating a JSON
file to HTML
table after working a day on it!!!
I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href
attribute of each links. It will match whether double or single quotes are used.
<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1
You can view a full explanation of this regex at here.
Snippet playground:
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
Text to match:_x000D_
<input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
_x000D_
<button>Match</button>_x000D_
</label>
_x000D_
<form id="form1" runat="server">
<input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
required="">
<datalist id="datalist1" runat="server">
</datalist>
</form>
protected void Page_Load(object sender, EventArgs e)
{
autocomplete();
}
protected void autocomplete()
{
Database p = new Database();
DataSet ds = new DataSet();
ds = p.sqlcall("select [name] from [stu_reg]");
int row = ds.Tables[0].Rows.Count;
string abc="";
for (int i = 0; i < row;i++ )
abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
datalist1.InnerHtml = abc;
}
Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.
For me these steps worked
stop-all.sh
hadoop namenode -format
start-all.sh
Running docker with interactive mode might solve the issue.
Here is the example for running image with and without interactive mode
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0 b6b9a942a79b1243bada59db19c7999cfff52d0a8744542fa843c95354966a18
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0 bash c3d6a9529fd70c5b2dc2d7e90fe662d19c6dad8549e9c812fb2b7ce2105d7ff5
chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c3d6a9529fd7 test_again1.0 "bash" 2 seconds ago Up 1 second awesome_haibt
This is one way:
h1 {
text-indent: -9999px; /* sends the text off-screen */
background-image: url(/the_img.png); /* shows image */
height: 100px; /* be sure to set height & width */
width: 600px;
white-space: nowrap; /* because only the first line is indented */
}
h1 a {
outline: none; /* prevents dotted line when link is active */
}
Here is another way to hide the text while avoiding the huge 9999 pixel box that the browser will create:
h1 {
background-image: url(/the_img.png); /* shows image */
height: 100px; /* be sure to set height & width */
width: 600px;
/* Hide the text. */
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
if permission issue and you have ssh access in root folder
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
will resolve your error
Recursive Approach:
def rec_cart(start, array, partial, results):
if len(partial) == len(array):
results.append(partial)
return
for element in array[start]:
rec_cart(start+1, array, partial+[element], results)
rec_res = []
some_lists = [[1, 2, 3], ['a', 'b'], [4, 5]]
rec_cart(0, some_lists, [], rec_res)
print(rec_res)
Iterative Approach:
def itr_cart(array):
results = [[]]
for i in range(len(array)):
temp = []
for res in results:
for element in array[i]:
temp.append(res+[element])
results = temp
return results
some_lists = [[1, 2, 3], ['a', 'b'], [4, 5]]
itr_res = itr_cart(some_lists)
print(itr_res)
It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.
Download and include this plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>
and use like
if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {
}
//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");
//alert(hash);
Try this lets say your form id is formID
$(".nextbutton").click(function() { $("form#formID").submit(); });
hey guys i think what you are looking for is this one using select command. With this you can specify a RANGE GREATER THAN(>) OR LESSER THAN(<) IN MySQL WITH THIS:::::
select* from <**TABLE NAME**> where year(**COLUMN NAME**) > **DATE** OR YEAR(COLUMN NAME )< **DATE**;
FOR EXAMPLE:
select name, BIRTH from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+------------+
| name | BIRTH |
+----------+------------+
| bowser | 1979-09-11 |
| chirpy | 1998-09-11 |
| whistler | 1999-09-09 |
+----------+------------+
FOR SIMPLE RANGE LIKE USE ONLY GREATER THAN / LESSER THAN
mysql> select COLUMN NAME from <TABLE NAME> where year(COLUMN NAME)> 1996;
FOR EXAMPLE mysql>
select name from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+
| name |
+----------+
| bowser |
| chirpy |
| whistler |
+----------+
3 rows in set (0.00 sec)
Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:
<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>
There is also an alternative: you could use the open-source jTDS driver for MS-SQL Server, which is compatible although not made by Microsoft. For that driver, there is a maven artifact that you can use:
From http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds :
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
UPDATE nov 2016, Microsoft now published its MSSQL JDBC driver on github and it's also available on maven now:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS The shell has a pty (pseudo terminal device, same as you would have in i.e. a ssh session), and you can get the shell as root if desired. Not sure you need root to execute your script, but given you mention sudo it is likely.
After downloading you would simply use the following code:
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd('/path/to/osascript myscript.scpt');
Press the start button. In the search box type "cmd", then press Ctrl+Shift+Enter
You have to connect to MySQL and select a database before you can do this
$table_name = "myTable";
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'");
$row = mysql_fetch_array($query);
$next_inc_value = $row["AUTO_INCREMENT"];
So, I use IntelliJ for my Android project, and the following solved the issue in the IDE:
just cause it might save someone the few hours I wasted... IntelliJ -> Preferences -> Build, Execution, Deployment -> Build tools -> Maven -> Gradle
and set Gradle JVM to 1.8 make sure you also have JDK 8 installed...
NOTE: the project was compiling just fine from the command line
It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).
To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).
Since AmazonDynamoDBClient(credentials) is deprecated i use this.
init {
val cp= AWSStaticCredentialsProvider(BasicAWSCredentials(ACCESS_KEY, SECRET_KEY))
val client = AmazonDynamoDBClientBuilder.standard().withCredentials(cp).withRegion(Regions.US_EAST_1).build()
dynamoDB = DynamoDB(client)
}
Create a component inside a specific folder:
ng g c folder-name/component-name
Create a component inside a folder for a specific (existing) module with Angular-CLI:
ng g c folder-name/component-name --module=folder-name/moduleName.module.ts
To force download you may use Content-Type: application/force-download
header, which is supported by most browsers:
function downloadFile($filePath)
{
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
}
A BETTER WAY
Downloading files this way is not the best idea especially for large files. PHP will require extra CPU / Memory to read and output file contents and when dealing with large files may reach time / memory limits.
A better way would be to use PHP to authenticate and grant access to a file, and actual file serving should be delegated to a web server using X-SENDFILE method (requires some web server configuration):
X-SENDFILE
is natively supported by Lighttpd: https://redmine.lighttpd.net/projects/1/wiki/X-LIGHTTPD-send-filemod_xsendfile
module: https://tn123.org/mod_xsendfile/ On Ubuntu may be installed by: apt install libapache2-mod-xsendfile
X-Accel-Redirect
header: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/After configuring web server to handle X-SENDFILE
, just replace readfile($filePath)
with header('X-SENDFILE: ' . $filePath)
and web server will take care of file serving, which will require less resources than using PHP readfile
.
(For Nginx use X-Accel-Redirect
header instead of X-SENDFILE
)
Note: If you end up downloading empty files, it means you didn't configure your web server to handle X-SENDFILE
header. Check the links above to see how to correctly configure your web server.
Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"
Then with one simple $text1 = file_get_contents('text.txt');
command have your text with not a single problem.
I fixed this issue by moving my directory from my exFAT drive which does not support symlinking.
My exFat drive is shared between osx and a bootcamp windows partition so when I tried to clone and npm install my project it was failing but never explains that exFAT doesn't support this functionality.
There are drivers out there that you can install to add the ability to symlink but you'll have to do a lot of your setup manually compared to running a simple npm script.
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
I do not why, but this works for me . rather than use '%s'
.
If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"
I was having the problem as a beginner..........
There was issue in the path of the xml file I have saved.
Your connection to redis is failing. Try restarting your redis server, then starting up your client again by running these 3 commands:
sudo service redis-server restart
redis-server
redis-cli
To select the ith
row, use iloc
:
In [31]: df_test.iloc[0]
Out[31]:
ATime 1.2
X 2.0
Y 15.0
Z 2.0
Btime 1.2
C 12.0
D 25.0
E 12.0
Name: 0, dtype: float64
To select the ith value in the Btime
column you could use:
In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2
df_test['Btime'].iloc[0]
(recommended) and df_test.iloc[0]['Btime']
:DataFrames store data in column-based blocks (where each block has a single
dtype). If you select by column first, a view can be returned (which is
quicker than returning a copy) and the original dtype is preserved. In contrast,
if you select by row first, and if the DataFrame has columns of different
dtypes, then Pandas copies the data into a new Series of object dtype. So
selecting columns is a bit faster than selecting rows. Thus, although
df_test.iloc[0]['Btime']
works, df_test['Btime'].iloc[0]
is a little bit
more efficient.
There is a big difference between the two when it comes to assignment.
df_test['Btime'].iloc[0] = x
affects df_test
, but df_test.iloc[0]['Btime']
may not. See below for an explanation of why. Because a subtle difference in
the order of indexing makes a big difference in behavior, it is better to use single indexing assignment:
df.iloc[0, df.columns.get_loc('Btime')] = x
df.iloc[0, df.columns.get_loc('Btime')] = x
(recommended):The recommended way to assign new values to a DataFrame is to avoid chained indexing, and instead use the method shown by andrew,
df.loc[df.index[n], 'Btime'] = x
or
df.iloc[n, df.columns.get_loc('Btime')] = x
The latter method is a bit faster, because df.loc
has to convert the row and column labels to
positional indices, so there is a little less conversion necessary if you use
df.iloc
instead.
df['Btime'].iloc[0] = x
works, but is not recommended:Although this works, it is taking advantage of the way DataFrames are currently implemented. There is no guarantee that Pandas has to work this way in the future. In particular, it is taking advantage of the fact that (currently) df['Btime']
always returns a
view (not a copy) so df['Btime'].iloc[n] = x
can be used to assign a new value
at the nth location of the Btime
column of df
.
Since Pandas makes no explicit guarantees about when indexers return a view versus a copy, assignments that use chained indexing generally always raise a SettingWithCopyWarning
even though in this case the assignment succeeds in modifying df
:
In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
In [26]: df
Out[26]:
foo bar
0 A 99 <-- assignment succeeded
2 B 100
1 C 100
df.iloc[0]['Btime'] = x
does not work:In contrast, assignment with df.iloc[0]['bar'] = 123
does not work because df.iloc[0]
is returning a copy:
In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
In [67]: df
Out[67]:
foo bar
0 A 99 <-- assignment failed
2 B 100
1 C 100
Warning: I had previously suggested df_test.ix[i, 'Btime']
. But this is not guaranteed to give you the ith
value since ix
tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i]
will return the row labeled i
rather than the ith
row. For example,
In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [2]: df
Out[2]:
foo
0 A
2 B
1 C
In [4]: df.ix[1, 'foo']
Out[4]: 'C'
If you have an unordered vector you can take advantage of the fact that it's unordered and use something I saw from Dan Higgins at CPPCON
template< typename TContainer >
static bool EraseFromUnorderedByIndex( TContainer& inContainer, size_t inIndex )
{
if ( inIndex < inContainer.size() )
{
if ( inIndex != inContainer.size() - 1 )
inContainer[inIndex] = inContainer.back();
inContainer.pop_back();
return true;
}
return false;
}
Since the list order doesn't matter, just take the last element in the list and copy it over the top of the item you want to remove, then pop and delete the last item.
Just wanted to add my approach. Using hooks and context provider.
Nav.js
function NavBar() {
const filterDispatch = useDispatchFilter()
const {filter} = useStateFilter()
const activeRef = useRef(null)
const completeRef = useRef(null)
const cancelRef = useRef(null)
useEffect(() => {
let activeClass = '';
let completeClass = '';
let cancelClass = '';
if(filter === ACTIVE_ORDERS){
activeClass='is-active'
}else if ( filter === COMPLETE_ORDERS ){
completeClass='is-active'
}else if(filter === CANCEL_ORDERS ) {
cancelClass='is-active'
}
activeRef.current.className = activeClass
completeRef.current.className = completeClass
cancelRef.current.className = cancelClass
}, [filter])
return (
<div className="tabs is-centered">
<ul>
<li ref={activeRef}>
<button
className="button-base"
onClick={() => filterDispatch({type: 'FILTER_ACTIVE'})}
>
Active
</button>
</li>
<li ref={completeRef}>
<button
className="button-base"
onClick={() => filterDispatch({type: 'FILTER_COMPLETE'})}
>
Complete
</button>
</li>
<li ref={cancelRef}>
<button
className={'button-base'}
onClick={() => filterDispatch({type: 'FILTER_CANCEL'})}
>
Cancel
</button>
</li>
</ul>
</div>
)
}
export default NavBar
filterContext.js
export const ACTIVE_ORDERS = [
"pending",
"assigned",
"pickup",
"warning",
"arrived",
]
export const COMPLETE_ORDERS = ["complete"]
export const CANCEL_ORDERS = ["cancel"]
const FilterStateContext = createContext()
const FilterDispatchContext = createContext()
export const FilterProvider = ({ children }) => {
const [state, dispatch] = useReducer(FilterReducer, { filter: ACTIVE_ORDERS })
return (
<FilterStateContext.Provider value={state}>
<FilterDispatchContext.Provider value={dispatch}>
{children}
</FilterDispatchContext.Provider>
</FilterStateContext.Provider>
)
}
export const useStateFilter = () => {
const context = useContext(FilterStateContext)
if (context === undefined) {
throw new Error("place useStateMap within FilterProvider")
}
return context
}
export const useDispatchFilter = () => {
const context = useContext(FilterDispatchContext)
if (context === undefined) {
throw new Error("place useDispatchMap within FilterProvider")
}
return context
}
export const FilterReducer = (state, action) => {
switch (action.type) {
case "FILTER_ACTIVE":
return {
...state,
filter: ACTIVE_ORDERS,
}
case "FILTER_COMPLETE":
return {
...state,
filter: COMPLETE_ORDERS,
}
case "FILTER_CANCEL":
return {
...state,
filter: CANCEL_ORDERS,
}
}
return state
}
Works fast, and replaces redux.
int fun(int n_args, ...) {
int *p = &n_args;
int s = sizeof(int);
p += s + s - 1;
for(int i = 0; i < n_args; i++) {
printf("A1 %d!\n", *p);
p += 2;
}
}
Plain version
The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use
let UserSchema = new Schema({
username: {
type: String
},
events: [{
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}]
})
if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:
let UserSchema = new Schema({
username: {
type: String
},
events: {
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}
})
Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.
What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ
are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)
Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!
<script>
var marks = 0;
function getRandomNumbers(){ // generate a random number between 1 & 10
var number = Math.floor((Math.random() * 10) + 1);
return number;
}
function getNew(){
/*
This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;
document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"
}
function checkAns(){
/*
After entering the answer, the entered answer will be compared with the correct answer.
If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
The updated total marks should be always displayed at the total marks box.
*/
var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);
if(answer==(num1+num2)){
marks = marks + 10;
document.getElementById("resultBox").innerHTML = "Correct";
document.getElementById("resultBox").style.backgroundColor = "green";
document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;
}
else{
marks = marks - 3;
document.getElementById("resultBox").innerHTML = "Wrong";
document.getElementById("resultBox").style.backgroundColor = "red";
document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}
}
</script>
</head>
<body onLoad="getNew()">
<div class="container">
<h1>Let's add numbers</h1>
<div class="sum">
<input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
</div>
<h2>Enter the answer below and click 'Check'</h2>
<div class="answer">
<input id="ans" type="text" value="">
</div>
<input id="btnchk" onClick="checkAns()" type="button" value="Check" >
<div id="resultBox">***</div>
<input id="btnnew" onClick="getNew()" type="button" value="New">
<div id="totalMarks">Total marks : 0</div>
</div>
</body>
</html>
As a side answer it's worth to note that:
aria-hidden
or aria-expanded
. But only if implemented and tested properly! let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
I also come here for the same problem, The solution I found is to install npm and then restart the Visual Studio Code
To make a dropdown list you need two properties:
In your case you only have a list of string which cannot be exploited to create a usable drop down list.
While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:
@model List<string>
@Html.DropDownList(
"Foo",
new SelectList(
Model.Select(x => new { Value = x, Text = x }),
"Value",
"Text"
)
)
where Foo
will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:
<select name="Foo" id="Foo">
<option value="item 1">item 1</option>
<option value="item 2">item 2</option>
<option value="item 3">item 3</option>
...
</select>
This being said a far better view model for a drop down list is the following:
public class MyListModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
and then:
@model MyListModel
@Html.DropDownListFor(
x => x.SelectedItemId,
new SelectList(Model.Items, "Value", "Text")
)
and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId
property of this view model to the corresponding Value
of some element in the Items
collection.
I also had the same problem, use this Java script function on head tag or in , its 100% working fine, would not let you go back.
<script type = "text/javascript" >
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
Swift 3 / Swift 4 solution that also works with NIBs/XIB files in iOS 10+:
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
}
Remove static
keyword in method definition. Keep it just in your class definition.
static
keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.
((frmMain)this.Owner).MyListControl.Items.Add("abc");
Make sure to provide access level you want at Modifiers properties other than Private for MyListControl
at frmMain
The other answer didn't work for me. I had to use mongoose.disconnect();
as stated in this answer.
What have you tried? This should work.
h1 { font-size: 20pt; }
h2 { font-size: 16pt; }
If you use Python3, you can use ipaddress
module http://docs.python.org/py3k/library/ipaddress.html. Example:
>>> import ipaddress
>>> ipv6 = "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
>>> ipv4 = "192.168.2.10"
>>> ipv4invalid = "266.255.9.10"
>>> str = "Tay Tay"
>>> ipaddress.ip_address(ipv6)
IPv6Address('2001:db8:a0b:12f0::1')
>>> ipaddress.ip_address(ipv4)
IPv4Address('192.168.2.10')
>>> ipaddress.ip_address(ipv4invalid)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
address)
ValueError: '266.255.9.10' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address(str)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
address)
ValueError: 'Tay Tay' does not appear to be an IPv4 or IPv6 address
First try this in your Windows cmd window:
pip3 install pyqt5
If that is successful, it will look something like this:
C:\Windows\System32>pip3 install pyqt5
Collecting pyqt5
Downloading PyQt5-5.9-5.9.1-cp35.cp36.cp37-none-win_amd64.whl (77.2MB)
100% |################################| 77.2MB 13kB/s
Collecting sip<4.20,>=4.19.3 (from pyqt5)
Downloading sip-4.19.3-cp35-none-win_amd64.whl (49kB)
100% |################################| 51kB 984kB/s
Installing collected packages: sip, pyqt5
Successfully installed pyqt5-5.9 sip-4.19.3
If that did not work, you might try this link from SourceForge.
PyQt5 .exe installers for Windows
How to find the installer that's right for you?
First, determine what version of Python you have and whether you have 32-bit or 64-bit Python. Next, open one of the directories. I'm on Python 3.5 64-bit so I'm looking for a .exe with those specs. When you open a directory on SourceForge, you will see some directories with ONLY .zip or .tar.gz. That's not what you're looking for. A good indication of which directory you should click is given by the "Downloads/Week" column. I'll open the PyQt-5.6 directory in my case.
Here we notice some .exe files:
PyQt-5.6
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x32-2.exe
|_PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
|_PyQt5_gpl-5.6.zip
|_PyQt5_gpl-5.6.tar.gz
I know these are Python 3.5 by Py3.5
in the file name. I am also looking for the 64-bit version so I'll download PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe
. Final answer!
Note: if you try to install a version that's not compatible with your system, a dialog box will appear immediately after running the .exe. That's an indication that you've chosen the wrong one. I'm not trying to sound like a dbag... I did that several times!
To test a successful install, in your Python interpreter, try to import:
from PyQt5 import QtCore, QtGui, QtWidgets
I believe you can use...
RESET QUERY CACHE;
...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...
FLUSH QUERY CACHE;
See the Query Cache Status and Maintenance section of the MySQL manual for more information.
Here is another example which is working
public class EnregistrementVideoStackActivity extends Activity implements SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
File video;
private Camera mCamera;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_surface);
Log.i(null , "Video starting");
startRecording = (Button)findViewById(R.id.buttonstart);
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i(null, "Problem Start"+message);
mrec.release();
}
break;
case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void startRecording() throws IOException
{
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/zzzz.3gp");
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.release();
}
private void releaseMediaRecorder(){
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null){
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}
camera_surface.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/buttonstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/record_start" />
</RelativeLayout>
And of course include these permission in manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
If you mean with "Web Service" something accessed by other Programms SimpleXMLRPCServer might be right for you. It is included with every Python install since Version 2.2.
For Simple human accessible things I usually use Pythons SimpleHTTPServer which also comes with every install. Obviously you also could access SimpleHTTPServer by client programs.
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
You should use tags:
as documented in https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html
If you have a large playbook it may become useful to be able to run a specific part of the configuration without running the whole playbook.
Both plays and tasks support a “tags:” attribute for this reason.
Example:
tasks:
- yum: name={{ item }} state=installed
with_items:
- httpd
- memcached
tags:
- packages
- template: src=templates/src.j2 dest=/etc/foo.conf
tags:
- configuration
If you wanted to just run the “configuration” and “packages” part of a very long playbook, you could do this:
ansible-playbook example.yml --tags "configuration,packages"
On the other hand, if you want to run a playbook without certain tasks, you could do this:
ansible-playbook example.yml --skip-tags "notification"
You may also apply tags to roles:
roles:
- { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }
And you may also tag basic include statements:
- include: foo.yml tags=web,foo
Both of these have the function of tagging every single task inside the include statement.
Install GD Library
Which OS you are using?
http://php.net/manual/en/image.installation.php
Windows http://www.dmxzone.com/go/5001/how-do-i-install-gd-in-windows/
Linux http://www.cyberciti.biz/faq/ubuntu-linux-install-or-add-php-gd-support-to-apache/
You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a List<T>
which can grow as it needs to.
Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.
See Eric Lippert's blog post on arrays for more detail and insight than I could realistically provide :)
Disable debugging mode and developer options in your phone.
Start Android device monitor.
Now enable developer options and debugging mode in your phone.
You should be able to see your device listed after this in android device monitor. There after you should be able to see it under Android device chooser.
int main();
This is a simple declaration. It cannot take any command line arguments.
int main(int argc, char* argv[]);
This declaration is used when your program must take command-line arguments. When run like such:
myprogram arg1 arg2 arg3
argc
, or Argument Count, will be set to 4 (four arguments), and argv
, or Argument Vectors, will be populated with string pointers to "myprogram", "arg1", "arg2", and "arg3". The program invocation (myprogram
) is included in the arguments!
Alternatively, you could use:
int main(int argc, char** argv);
This is also valid.
There is another parameter you can add:
int main (int argc, char *argv[], char *envp[])
The envp
parameter also contains environment variables. Each entry follows this format:
VARIABLENAME=VariableValue
like this:
SHELL=/bin/bash
The environment variables list is null-terminated.
IMPORTANT: DO NOT use any argv
or envp
values directly in calls to system()
! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don't use system()
. There is almost always a better solution implemented through C libraries.
Using pgadmin4 :
Now there you can enable or disable login, roles and other options
Try this code
select (DATEDIFF(DD,'2014-08-01','2014-08-14')+1)- (DATEDIFF(WK,'2014-08-01','2014-08-14')* 2)
Try:
SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`
In Java reading and writing fields of all types except long and double occurs atomically, and if the field is declared with the volatile modifier, even long and double are atomically read and written. That is, we get 100% either what was there, or what happened there, nor can there be any intermediate result in the variables.
This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage
public void checkAlert() {
try {
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (Exception e) {
//exception handling
}
}
It seems to be true so far. The only SDK available from Apple only targets the macOS environment. I've been upset about that, but I'm looking into buying a mac now, just to do iPhone development. I really dislike what they are doing, and I hope a good SDK come out for other environments, such as Linux and Windows.
Obstacles regarding the SDK:
The iPhone SDK and free software: not a match
Apple's recently released a software development kit (SDK) for the iPhone, but if you were hoping to port or develop original open source software with it, the news isn't good. Code signing and nondisclosure conditions make free software a no-go.
The SDK itself is a free download, with which you can write programs and run them on a software simulator. But in order to actually release software you've written, you must enroll in the iPhone Developer Program -- a step separate from downloading the SDK, and one that requires Apple's approval.
I think it's rather elitist for them to think only macOS users are good enough to write programs for their phone, and the fact you need to buy a $100 license if you want to publish your stuff, really makes it more difficult for the hobbyist programmer. Though, if that's what you need to do, I'm planning on jumping through their hoops; I'd really like to get some stuff developed on my iPhone.
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
While it looks like your setup is correct, there are a few things to check:
env
- specifically PATH
.command -v java
tells you what?java
executable in $JAVA_HOME\bin
and does it have the execute bit set? If not chmod a+x java
it.I trust you have source
'd your .profile
after adding/changing the JAVA_HOME
and PATH
?
Also, you can help yourself in future maintenance of your JDK installation by writing this instead:
export JAVA_HOME=/home/aqeel/development/jdk/jdk1.6.0_35
export PATH=$JAVA_HOME/bin:$PATH
Then you only need to update one env variable when you setup the JDK installation.
Finally, you may need to run hash -r
to clear the Bash program cache. Other shells may need a similar command.
Cheers,
This answer shows how I ended up using this and the additional pitfalls I hit.
I made a master SCSS file. This file must have an underscore at the beginning for it to be imported:
// assets/_master.scss
$accent: #6D87A7;
$error: #811702;
Then, in the header of all of my other .SCSS files, I import the master:
// When importing the master, you leave out the underscore, and it
// will look for a file with the underscore. This prevents the SCSS
// compiler from generating a CSS file from it.
@import "assets/master";
// Then do the rest of my CSS afterwards:
.text { color: $accent; }
Do not include anything but variables, function declarations and other SASS features in your _master.scss
file. If you include actual CSS, it will duplicate this CSS across every file you import the master into.
for line in f
reads all file to a memory, and that can be a problem.
My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:
with open("blablabla.txt", "r") as fl_in:
while True:
line = fl_in.readline()
if not line:
break
line = line.strip()
# do what You want
You'll need to take a look at your Apache error log to see what the "internal server error" is. The four most likely cases, in my experience would be:
The CGI program is in a directory which does not have CGI execution enabled. Solution: Add the ExecCGI
option to that directory via either httpd.conf or a .htaccess file.
Apache is only configured to run CGIs from a dedicated cgi-bin
directory. Solution: Move the CGI program there or add an AddHandler cgi-script .cgi
statement to httpd.conf.
The CGI program is not set as executable. Solution (assuming a *nix-type operating system): chmod +x my_prog.cgi
The CGI program is exiting without sending headers. Solution: Run the program from the command line and verify that a) it actually runs rather than dying with a compile-time error and b) it generates the correct output, which should include, at the very minimum, a Content-Type
header and a blank line following the last of its headers.
when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
//ARGUMENTS
function func(){
console.log(arguments);//[1, 2, 3, 4]
//var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
var arrArguments = [].slice.call(arguments);//cp array with explicity THIS
arrArguments.push('new');
console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
I tried the following three methods, my file size is 1M, and I got results:
I run the program several times it looks that BufferedReader is faster.
@Test
public void testLargeFileIO_Scanner() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
InputStream inputStream = new FileInputStream(fileName);
try (Scanner fileScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
//System.out.println(line);
}
}
long end = new Date().getTime();
long time = end - start;
System.out.println("Scanner Time Consumed => " + time);
}
@Test
public void testLargeFileIO_BufferedReader() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
try (BufferedReader fileBufferReader = new BufferedReader(new FileReader(fileName))) {
String fileLineContent;
while ((fileLineContent = fileBufferReader.readLine()) != null) {
//System.out.println(fileLineContent);
}
}
long end = new Date().getTime();
long time = (long) (end - start);
System.out.println("BufferedReader Time Consumed => " + time);
}
@Test
public void testLargeFileIO_Stream() throws Exception {
long start = new Date().getTime();
String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
try (Stream inputStream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) {
//inputStream.forEach(System.out::println);
}
long end = new Date().getTime();
long time = end - start;
System.out.println("Stream Time Consumed => " + time);
}
Its just better to create a routing component that would handle all your routes! From the angular website documentation! That's good practice!
ng generate module app-routing --flat --module=app
The above CLI generates a routing module and adds to your app module, all you need to do from the generated component is to declare your routes, also don't forget to add this:
exports: [
RouterModule
],
to your ng-module decorator as it doesn't come with the generated app-routing module by default!
I been seeking the same thing without using some unsupported PHP class. Excel CSV dosn't always use the quote separators and escapes the quotes using "" because the algorithm was probably made back the 80's or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval'd code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.
function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
// SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
// AUTHOR: [email protected]
// RELEASED: 9/21/13 BETA
{ $r=1; $row=array(); $fields=array(); $csv="";
$escapes=array('\r', '\n', '\t', '\\', '\"'); //two byte escape codes
$escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code
if($mode=='EXCEL')// escape code = ""
{ $delim=','; $enclos='"'; $rowbr="\r\n"; }
else //mode=STANDARD all fields enclosed
{ $delim=','; $enclos='"'; $rowbr="\r\n"; }
$csv=""; $i=-1; $i2=0; $imax=count($rows);
while( $i < $imax )
{
// get field names
if($i == -1)
{ $row=$rows[0];
if($fmt=='2D_FIELDNAME_ARRAY')
{ $i2=0; $i2max=count($row);
while( list($k, $v) = each($row) )
{ $fields[$i2]=$k;
$i2++;
}
}
else //if($fmt='2D_NUMBERED_ARRAY')
{ $i2=0; $i2max=(count($rows[0]));
while($i2<$i2max)
{ $fields[$i2]=$i2;
$i2++;
}
}
if($headerrow==true) { $row=$fields; }
else { $i=0; $row=$rows[0];}
}
else
{ $row=$rows[$i];
}
$i2=0; $i2max=count($row);
while($i2 < $i2max)// numeric loop (order really matters here)
//while( list($k, $v) = each($row) )
{ if($i2 != 0) $csv=$csv.$delim;
$v=$row[$fields[$i2]];
if($mode=='EXCEL') //EXCEL 2quote escapes
{ $newv = '"'.(str_replace('"', '""', $v)).'"'; }
else //STANDARD
{ $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
$csv=$csv.$newv;
$i2++;
}
$csv=$csv."\r\n";
$i++;
}
return $csv;
}
function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
{ // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
// AUTHOR: [email protected]
// RELEASED: 9/21/13 BETA
//SWMessage("SW_ExplodeCSV() - CALLED HERE -");
$rows=array(); $row=array(); $fields=array();// rows = array of arrays
//escape code = '\'
$escapes=array('\r', '\n', '\t', '\\', '\"'); //two byte escape codes
$escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code
if($mode=='EXCEL')
{// escape code = ""
$delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="\r\n";
}
else //mode=STANDARD
{// all fields enclosed
$delim=','; $enclos='"'; $rowbr="\r\n";
}
$indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
$rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
$headerflg=0; $quotedflg=0;
$i=0; $i2=0; $imax=strlen($csv);
while($indxf < $imax)
{
//find first *possible* cell delimiters
$indxl=strpos($csv, $delim, $indxf); if($indxl===false) { $indxl=$imax; }
$encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
$rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }
if(($encindxf>$indxl)||($encindxf>$rowindxl))
{ $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
}
else
{ //find cell enclosure area (and real cell delimiter)
$quoteflg=1;
$enc=$encindxf;
while($enc<$indxl) //$enc = next open quote
{// loop till unquoted delim. is found
$enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
$encindxl=$enc; //last close quote
$indxl=strpos($csv, $delim, $enc+1); if($indxl===false) { $indxl=$imax; }//last delim.
$enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
if(($indxl==$imax)||($enc==$imax)) break;
}
$rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
}
if($quoteflg==0)
{ //no enclosured content - take as is
$colflg=1;
//get cell
// $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
$cell=substr($csv, $indxf, ($indxl-$indxf));
}
else// if($rowindxl > $encindxf)
{ // cell enclosed
$colflg=1;
//get cell - decode cell content
$cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);
if($mode=='EXCEL') //remove EXCEL 2quote escapes
{ $cell=str_replace($esc_enclos, $enclos, $cell);
}
else //remove STANDARD esc. sceme
{ $cell=str_replace($escapes, $escapes2, $cell);
}
}
if($colflg)
{// read cell into array
if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
{ $row[$fields[$colcnt]]=$cell; }
else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
{ $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;
$colcnt++; $colflg=0; $cell="";
$indxf=$indxl+1;//strlen($delim);
}
if($rowflg)
{// read row into big array
if(($headerrow) && ($headerflg==0))
{ $fields=$row;
$row=array();
$headerflg=1;
}
else
{ $rows[$rowcnt]=$row;
$row=array();
$rowcnt++;
}
$colcnt=0; $rowflg=0; $cell="";
$rowindxf=$rowindxl+2;//strlen($rowbr);
$indxf=$rowindxf;
}
$i++;
//SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt." rowcnt = ".$rowcnt." indxf = ".$indxf." indxl = ".$indxl." rowindxf = ".$rowindxf);
//if($i>20) break;
}
return $rows;
}
...bob can now go back to his speadsheets
By default WampServer is installed to port 80 which is already used by IIS. To set WampServer to use an open port, left click on the WampServer icon in the system tray and go to Apache > httpd.conf
Open the httpd.conf in Notepad. press ctrl+f and search for "Listen 80", change this line to "Listen 8080" (u can change this port as what you want), and then close and save the httpd.conf file.
Open a web browser and enter "[];, this will open the WampServer configuration page where you can configure Apache, MySQL, and PHP.
and some times this problem may occur because of skype also use 80 as default port hope this will help
I saw the above result and query will work fine if you need to check single column value which are duplicate. For example email.
But if you need to check with more columns and would like to check the combination of the result so this query will work fine:
SELECT COUNT(CONCAT(name,email)) AS tot,
name,
email
FROM users
GROUP BY CONCAT(name,email)
HAVING tot>1 (This query will SHOW the USER list which ARE greater THAN 1
AND also COUNT)
The best/easy/fast solution that you can use if it's a quick debugging, is to surround your code with catching exceptions. That's what I'm doing when I want to check something fast in production.
try {
// Page code
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Simply get date and convert
Declare @Date as Date =Getdate()
Select Format(@Date,'dd/MM/yyyy') as [dd/MM/yyyy] // output: 22/10/2020
Select Format(@Date,'dd-MM-yyyy') as [dd-MM-yyyy] // output: 22-10-2020
//string date
Select Format(cast('25/jun/2013' as date),'dd/MM/yyyy') as StringtoDate // output: 25/06/2013
Source: SQL server date format and converting it (Various examples)
You can use styles for modifiy the login button like this
<style name="FacebookLoginButton">
<item name="android:textSize">@dimen/smallTxtSize</item>
<item name="android:background">@drawable/facebook_signin_btn</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:layout_marginBottom">10dp</item>
<item name="android:layout_gravity">center_horizontal</item>
</style>
and in layout
<com.facebook.widget.LoginButton
xmlns:fb="http://schemas.android.com/apk/res-auto"
android:id="@+id/loginFacebookButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
fb:login_text="@string/loginFacebookButton"
fb:logout_text=""
style="@style/FacebookLoginButton"/>
Initially I also had problem getting FLAG_ACTIVITY_CLEAR_TOP to work. Eventually I got it to work by using the value of it (0x04000000). So looks like there's an Eclipse/compiler issue. But unfortunately the surviving activity is restarted, which is not what I want. So looks like there's no easy solution.
If you want formated number then use
SELECT TO_CHAR(number, 'fmt')
FROM DUAL;
SELECT TO_CHAR('123', 999.99)
FROM DUAL;
Result 123.00
Easiest solution is to use BuildConfig
.
I use BuildConfig.VERSION_NAME
in my application.
You can also use BuildConfig.VERSION_CODE
to get version code.
This is the easiest way to do this:
$text = var_export($bool_value,true);
echo $text;
or
var_export($bool_value)
If the second argument is not true, it will output the result directly.
Regex: match everything but:
foo
):
world.
at the end):
foo
) (no POSIX compliant patern, sorry):
|
symbol):
foo
):
cat
): /cat(*SKIP)(*FAIL)|[^c]*(?:c(?!at)[^c]*)*/i
or /cat(*SKIP)(*FAIL)|(?:(?!cat).)+/is
(cat)|[^c]*(?:c(?!at)[^c]*)*
(or (?s)(cat)|(?:(?!cat).)*
, or (cat)|[^c]+(?:c(?!at)[^c]*)*|(?:c(?!at)[^c]*)+[^c]*
) and then check with language means: if Group 1 matched, it is not what we need, else, grab the match value if not empty[^a-z]+
(any char other than a lowercase ASCII letter)|
: [^|]+
Demo note: the newline \n
is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.
Anchor note: In many languages, use \A
to define the unambiguous start of string, and \z
(in Python, it is \Z
, in JavaScript, $
is OK) to define the very end of the string.
Dot note: In many flavors (but not POSIX, TRE, TCL), .
matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s
in PCRE/Boost/.NET/Python/Java and /m
in Ruby) for the .
to match any char including a newline.
Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n
for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\.
will be declared as "world\\."
, or use a character class: "world[.]"
). Use raw string literals (Python r'\bworld\b'
), C# verbatim string literals @"world\."
, or slashy strings/regex literal notations like /world\./
.
use this in style
body
{
overflow:hidden;
width:100%;
}
Use this in head tag
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If
Most times, you won't need to "convert"; VBA will do safe implicit type conversion for you, without the use of converters like CStr
.
The below code works without any issues, because the variable is of Type String, and implicit type conversion is done for you automatically!
Dim myVal As String
Dim myNum As Integer
myVal = "My number is: "
myVal = myVal & myNum
Result:
"My number is: 0"
You don't even have to get that fancy, this works too:
Dim myString as String
myString = 77
"77"
The only time you WILL need to convert is when the variable Type is ambiguous (e.g., Type Variant, or a Cell's Value
(which is Variant)).
Even then, you won't have to use CStr
function if you're compounding with another String variable or constant. Like this:
Sheet1.Range("A1").Value = "My favorite number is " & 7
"My favorite number is 7"
So, really, the only rare case is when you really want to store an integer value, into a variant or Cell value, when not also compounding with another string (which is a pretty rare side case, I might add):
Dim i as Integer
i = 7
Sheet1.Range("A1").Value = i
7
Dim i as Integer
i = 7
Sheet1.Range("A1").Value = CStr(i)
"7"
I had the same problem as Marko and come across a solution like this:
/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS
/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal
/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
SELECT oi.Quantity * p.Price AS columnGrandTotal
FROM OrderItem oi
JOIN Product p ON oi.Id = p.Id
/*And return the sum of columnGrandTotal from the newly created table*/
SELECT SUM(columnGrandTotal) as [Grand Total]
FROM tableGrandTotal
And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)
EXEC GetGrandTotal
Try docker volume create
.
mkdir -p /data1/Downloads
docker volume create --driver local --name hello --opt type=none --opt device=/data1/Downloads --opt o=uid=root,gid=root --opt o=bind
docker run -i -v hello:/Downloads ubuntu bash
Take a look at the document https://docs.docker.com/engine/reference/commandline/volume_create/
public static String readFile(String fn) throws IOException
{
File f = new File(fn);
byte[] buffer = new byte[(int)f.length()];
FileInputStream is = new FileInputStream(fn);
is.read(buffer);
is.close();
return new String(buffer, "UTF-8"); // use desired encoding
}
I think all the answers here are relevant however if, like me, you are looking for where Visual Studio takes the template from when it creates a new version of the applicationHost.config then you can look here:
C:\Program Files (x86)\IIS Express\config\templates\PersonalWebServer
This happens a lot if you are often working on multiple branches of the same project and pressing 'debug' in a lot of them. Making an edit here will ensure that edit propagates to any new project/solution folders that get created.
Answer indirectly came from this answer
SELECT COUNT(*), table1.category_id, table2.category_name
FROM table1
INNER JOIN table2 ON table1.category_id=table2.category_id
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name
In addition to the ways already mentioned (dropping the war-file directly into the webapps-directory), if you have the Tomcat Manager -application installed, you can deploy war-files via browser too. To get to the manager, browse to the root of the server (in your case, localhost:8080), select "Tomcat Manager" (at this point, you need to know username and password for a Tomcat-user with "manager"-role, the users are defined in tomcat-users.xml in the conf-directory of the tomcat-installation). From the opening page, scroll downwards until you see the "Deploy"-part of the page, where you can click "browse" to select a WAR file to deploy from your local machine. After you've selected the file, click deploy. After a while the manager should inform you that the application has been deployed (and if everything went well, started).
Here's a longer how-to and other instructions from the Tomcat 7 documentation pages.
SHIFT+CTRL+B
should work
However sometimes an issue can happen in a locked down non-adminstrator evironment:
If you open an existing C# application from the folder you should have a .sln (solution file) etc..
Commonly you can get these message in VS Code
Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!
Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'
Finished
Failed to spawn 'dotnet --info' //this is a possible issue
To which then you will be asked to install .NET CLI tools
If impossible to get SDK installed with no admin privilege - then use other solution.
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
if($("h1").is(":hidden")){
// your code..
}
You need to require only one plugin which is the Subversion plugin.
Then simply, go into Jenkins ? job_name ? Build Trigger section ? (i) Trigger build remotely (i.e., from scripts) Authentication token: Token_name
Go to the SVN server's hooks directory, and then after fire the below commands:
cp post-commit.tmpl post-commit
chmod 777 post-commit
chown -R www-data:www-data post-commit
vi post-commit
Note: All lines should be commented Add the below line at last
Syntax (for Linux users):
/usr/bin/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name
Syntax (for Windows user):
C:/curl_for_win/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name
Delete Multiple checkbox using PHP Code
<input type="checkbox" name="chkbox[] value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
$cnt=array();
$cnt=count($_POST['chkbox']);
for($i=0;$i<$cnt;$i++)
{
$del_id=$_POST['chkbox'][$i];
$query="delete from $tablename where Id=".$del_id;
mysql_query($query);
}
}
You can use:
SELECT IDENT_CURRENT('tablename')
to access the latest identity for a perticular table.
e.g. Considering following code:
INSERT INTO dbo.MyTable(columns....) VALUES(..........)
INSERT INTO dbo.YourTable(columns....) VALUES(..........)
SELECT IDENT_CURRENT('MyTable')
SELECT IDENT_CURRENT('YourTable')
This would yield to correct value for corresponding tables.
It returns the last IDENTITY
value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT
is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT
returns the identity value generated for a specific table in any session and any scope.
A simple way without any libraries or sets
def mcount(l):
n = [] #To store count of each elements
for x in l:
count = 0
for i in range(len(l)):
if x == l[i]:
count+=1
n.append(count)
a = max(n) #largest in counts list
for i in range(len(n)):
if n[i] == a:
return(l[i],a) #element,frequency
return #if something goes wrong
Sometimes none of these would work for me. So I used to create a new web project in VS and select Authorization as "Individual User Accounts". I believe this work with some higher version of .NET Framework or something. But when you do this it will have your connection details. Mostly something like this
(LocalDb)\MSSQLLocalDB
If your data is already in your database you can do:
INSERT INTO MyTable(ID, Name)
SELECT ID, NAME FROM OtherTable
If you need to hard code the data then SQL 2008 and later versions let you do the following...
INSERT INTO MyTable (Name, ID)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
with your VARCHAR, you may also need to specify the length, or its usually good to
What about grabbing the text, making a sting of it, then putting it into the query witrh
String TableName = "ComplicatedTableNameHere";
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
String editTextString1 = editText1.getText().toString();
BROKEN DOWN
String TableName = "ComplicatedTableNameHere";
//sets the table name as a string so you can refer to TableName instead of writing out your table name everytime
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
//gets the text from your edit text fieldfield
//editText1 = your edit text name
//EditTextIDhere = the id of your text field
String editTextString1 = editText1.getText().toString();
//sets the edit text as a string
//editText1 is the name of the Edit text from the (EditText) we defined above
//editTextString1 = the string name you will refer to in future
then use
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
+ " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");
Hope this helps some what...
NOTE each string is within
'"+stringname+"'
its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word
The error message,
Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.
Is quite descriptive and accurate. The question is how should you avoid accessing the database on the main thread. That is a huge topic, but to get started, read about AsyncTask (click here)
-----EDIT----------
I see you are having problems when you run a unit test. You have a couple of choices to fix this:
Run the test directly on the development machine rather than on an Android device (or emulator). This works for tests that are database-centric and don't really care whether they are running on a device.
Use the annotation
@RunWith(AndroidJUnit4.class)
to run the test on the android device, but not in an activity with a UI.
More details about this can be found in this tutorial
This:
int fillarr(int arr[])
is actually treated the same as:
int fillarr(int *arr)
Now if you really want to return an array you can change that line to
int * fillarr(int arr[]){
// do something to arr
return arr;
}
It's not really returning an array. you're returning a pointer to the start of the array address.
But remember when you pass in the array, you're only passing in a pointer. So when you modify the array data, you're actually modifying the data that the pointer is pointing at. Therefore before you passed in the array, you must realise that you already have on the outside the modified result.
e.g.
int fillarr(int arr[]){
array[0] = 10;
array[1] = 5;
}
int main(int argc, char* argv[]){
int arr[] = { 1,2,3,4,5 };
// arr[0] == 1
// arr[1] == 2 etc
int result = fillarr(arr);
// arr[0] == 10
// arr[1] == 5
return 0;
}
I suggest you might want to consider putting a length into your fillarr function like this.
int * fillarr(int arr[], int length)
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
int * fillarr(int arr[], int length){
for (int i = 0; i < length; ++i){
// arr[i] = ? // do what you want to do here
}
return arr;
}
// then where you want to use it.
int arr[5];
int *arr2;
arr2 = fillarr(arr, 5);
// at this point, arr & arr2 are basically the same, just slightly
// different types. You can cast arr to a (char*) and it'll be the same.
If all you're wanting to do is set the array to some default values, consider using the built in memset function.
something like: memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them. http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
UPDATE 21/11/2012 @ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here
Hi So as promised here is my answer using only javascript :
The content of the BODY of the page :
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR APP ID',
status : true,
cookie : true,
xfbml : true
});
</script>
<div id="container_notlike">
YOU DONT LIKE
</div>
<div id="container_like">
YOU LIKE
</div>
The CSS :
body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}
#container_notlike, #container_like {
display:none
}
And finally the javascript :
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
});
So what what does it do ?
First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid
with YOUR_USER_ID (from your rails app for example)
After that it makes a FQL query on the page_fan
table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.
Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/
It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...
Finally some related docs :
Don't hesitate if you have any question ..
Cheers
UPDATE 2
As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).
For the document.ready, you could wrap your code in a function and use body onload="your_function"
or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.
And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block"
and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm
But jQuery is so easy :)
UPDATE
Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.
In your action controller :
decoded_request = Canvas.parse_signed_request(params[:signed_request])
And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)
decoded_request['page']['liked']
And here is the related Canvas Class (from fbgraph ruby library) :
class Canvas
class << self
def parse_signed_request(secret_id,request)
encoded_sig, payload = request.split('.', 2)
sig = ""
urldecode64(encoded_sig).each_byte { |b|
sig << "%02x" % b
}
data = JSON.parse(urldecode64(payload))
if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
raise "Bad signature algorithm: %s" % data['algorithm']
end
expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
if expected_sig != sig
raise "Bad signature"
end
data
end
private
def urldecode64(str)
encoded_str = str.gsub('-','+').gsub('_','/')
encoded_str += '=' while !(encoded_str.size % 4).zero?
Base64.decode64(encoded_str)
end
end
end
panel.setStyle("-fx-background-color: #FFFFFF;");
This works for me:
My pip
is not work after upgrade, so the first thing I need to do is to fix it with
sudo gedit /usr/bin/pip
Change the line
from pip import main
to
from pip._internal import main
Then,
sudo pip install -U numpy
in this question, you'll have some answers, including mine:
public Image resizeImage(int newWidth, int newHeight, string stPhotoPath)
{
Image imgPhoto = Image.FromFile(stPhotoPath);
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
//Consider vertical pics
if (sourceWidth < sourceHeight)
{
int buff = newWidth;
newWidth = newHeight;
newHeight = buff;
}
int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
float nPercent = 0, nPercentW = 0, nPercentH = 0;
nPercentW = ((float)newWidth / (float)sourceWidth);
nPercentH = ((float)newHeight / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((newWidth -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((newHeight -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(newWidth, newHeight,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Black);
grPhoto.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
imgPhoto.Dispose();
return bmPhoto;
}
A peculiar difference I have noted on gcc 5.2.1 and clang 3.6.2 is that if you have a critical loop like:
for (;;) {
if (!visited) {
....
}
node++;
if (!*node) break;
}
Then gcc will, when compiling with -O3
or -O2
, speculatively
unroll the loop eight times. Clang will not unroll it at all. Through
trial and error I found that in my specific case with my program data,
the right amount of unrolling is five so gcc overshot and clang
undershot. However, overshooting was more detrimental to performance, so
gcc performed much worse here.
I have no idea if the unrolling difference is a general trend or just something that was specific to my scenario.
A while back I wrote a few garbage collectors to teach myself more about performance optimization in C. And the results I got is in my mind enough to slightly favor clang. Especially since garbage collection is mostly about pointer chasing and copying memory.
The results are (numbers in seconds):
+---------------------+-----+-----+
|Type |GCC |Clang|
+---------------------+-----+-----+
|Copying GC |22.46|22.55|
|Copying GC, optimized|22.01|20.22|
|Mark & Sweep | 8.72| 8.38|
|Ref Counting/Cycles |15.14|14.49|
|Ref Counting/Plain | 9.94| 9.32|
+---------------------+-----+-----+
This is all pure C code, and I make no claim about either compiler's performance when compiling C++ code.
On Ubuntu 15.10, x86.64, and an AMD Phenom(tm) II X6 1090T processor.
helper.hxx
class helper
{
public:
static void fn1 ()
{ /* defined in header itself */ }
/* fn2 defined in src file helper.cxx */
static void fn2();
};
helper.cxx
#include "helper.hxx"
void helper::fn2()
{
/* fn2 defined in helper.cxx */
/* do something */
}
A.cxx
#include "helper.hxx"
A::foo() {
helper::fn1();
helper::fn2();
}
To know more about how c++ handles static functions visit: Are static member functions in c++ copied in multiple translation units?
This is a slight variation that worked better for me.
$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"
$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open($CSV)
$Worksheets = $Workbooks.worksheets
$Workbook.SaveAs($XLS,1)
$Workbook.Saved = $True
$xl.Quit()
If you are using command line use python -m compileall <argument>
to compile python code to python binary code.
Ex: python -m compileall -x ./*
Or, You can use this code to compile your library into byte-code.
import compileall
import os
lib_path = "your_lib_path"
build_path = "your-dest_path"
compileall.compile_dir(lib_path, force=True, legacy=True)
def moveToNewLocation(cu_path):
for file in os.listdir(cu_path):
if os.path.isdir(os.path.join(cu_path, file)):
compile(os.path.join(cu_path, file))
elif file.endswith(".pyc"):
dest = os.path.join(build_path, cu_path ,file)
os.makedirs(os.path.dirname(dest), exist_ok=True)
os.rename(os.path.join(cu_path, file), dest)
moveToNewLocation(lib_path)
look at ? docs.python.org for detailed documentation
declare n number(10);
begin
select count(*) into n from tab where tname='TEST';
if (n = 0) then
execute immediate
'create table TEST ( ID NUMBER(3), NAME VARCHAR2 (30) NOT NULL)';
end if;
end;
Here I am providing a negative example where your want to avoid when converting floating number to strings.
float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;
You get
99463 99.463 99.462997
Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.
I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.
string ftos(float f, int nd) {
ostringstream ostr;
int tens = stoi("1" + string(nd, '0'));
ostr << round(f*tens)/tens;
return ostr.str();
}
You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" />
control doesn't handle that.
If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change
event then strip the filename portion and save the path somewhere--but that's about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.
The same problem when I export the library httclient-4.3.5 in Android Studio 0.8.6 I need include this:
packagingOptions{
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
}
The library zip content the next jar:
commons-codec-1.6.jar
commons-logging-1.1.3.jar
fluent-hc-4.3.5.jar
httpclient-4.3.5.jar
httpclient-cache-4.3.5.jar
httpcore-4.3.2.jar
httpmime-4.3.5.jar
If you are using Sass:
$card-column-sizes: (
xs: 2,
sm: 3,
md: 4,
lg: 5,
);
@each $breakpoint-size, $column-count in $card-column-sizes {
@include media-breakpoint-up($breakpoint-size) {
.card-columns {
column-count: $column-count;
column-gap: 1.25rem;
.card {
display: inline-block;
width: 100%; // Don't let them exceed the column width
}
}
}
}
When spring boot is used we should exclude the SecurityAutoConfiguration.class both in application class and where exactly you are configuring the security like below.
Then only we can avoid the default security password.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
@EnableJpaRepositories
@EnableResourceServer
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class
})
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().anyRequest().authenticated();
httpSecurity.headers().cacheControl();
}
}
Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.
Converting a structure to JSON is very straightforward:
use strict;
use warnings;
use JSON::Any;
my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);
Best way I have used is to mount the VS 2010 Image or insert the Installation disc and run the uninstall
option, really works well
There is no DrawCircle
method; use DrawEllipse
instead. I have a static class with handy graphics extension methods. The following ones draw and fill circles. They are wrappers around DrawEllipse
and FillEllipse
:
public static class GraphicsExtensions
{
public static void DrawCircle(this Graphics g, Pen pen,
float centerX, float centerY, float radius)
{
g.DrawEllipse(pen, centerX - radius, centerY - radius,
radius + radius, radius + radius);
}
public static void FillCircle(this Graphics g, Brush brush,
float centerX, float centerY, float radius)
{
g.FillEllipse(brush, centerX - radius, centerY - radius,
radius + radius, radius + radius);
}
}
You can call them like this:
g.FillCircle(myBrush, centerX, centerY, radius);
g.DrawCircle(myPen, centerX, centerY, radius);
A wrapper around GNU ld that doesn't support linker scripts
Some .so files are actually GNU ld linker scripts, e.g. libtbb.so file is an ASCII text file with this contents:
INPUT (libtbb.so.2)
Some more complex builds may not support this. For example, if you include -v in the compiler options, you can see that the mainwin gcc wrapper mwdip discards linker script command files in the verbose output list of libraries to link in. A simple work around is to replace the linker script input command file with a copy of the file instead (or a symlink), e.g.
cp libtbb.so.2 libtbb.so
Or you could replace the -l argument with the full path of the .so, e.g. instead of -ltbb
do /home/foo/tbb-4.3/linux/lib/intel64/gcc4.4/libtbb.so.2
Make sure overflow is set to "scroll" not "auto." With that said, in OS X Lion, overflow set to "scroll" behaves more like auto in that scrollbars will still only show when being used. So if any the solutions above don't appear to be working that might be why.
This is what you'll need to fix it:
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0, 0, 0, .5);
-webkit-box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}
You can style it accordingly if you don't like the default.
I wanted a more exact and useful answer to this question. Here's the real answer (adjust accordingly if you want a byte array specifically; obviously the math will be off by a factor of 8 bits : 1 byte
):
class BitArray {
constructor(bits = 0) {
this.uints = new Uint32Array(~~(bits / 32));
}
getBit(bit) {
return (this.uints[~~(bit / 32)] & (1 << (bit % 32))) != 0 ? 1 : 0;
}
assignBit(bit, value) {
if (value) {
this.uints[~~(bit / 32)] |= (1 << (bit % 32));
} else {
this.uints[~~(bit / 32)] &= ~(1 << (bit % 32));
}
}
get size() {
return this.uints.length * 32;
}
static bitsToUints(bits) {
return ~~(bits / 32);
}
}
Usage:
let bits = new BitArray(500);
for (let uint = 0; uint < bits.uints.length; ++uint) {
bits.uints[uint] = 457345834;
}
for (let bit = 0; bit < 50; ++bit) {
bits.assignBit(bit, 1);
}
str = '';
for (let bit = bits.size - 1; bit >= 0; --bit) {
str += bits.getBit(bit);
}
str;
Output:
"00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000101000101100101010
00011011010000111111111111111111
11111111111111111111111111111111"
Note: This class is really slow to e.g. assign bits (i.e. ~2s per 10 million assignments) if it's created as a global variable, at least in the Firefox 76.0 Console on Linux... If, on the other hand, it's created as a variable (i.e. let bits = new BitArray(1e7);
), then it's blazingly fast (i.e. ~300ms per 10 million assignments)!
For more info, see here:
Note that I used Uint32Array because there's no way to directly have a bit/byte array (that you can interact with directly) and because even though there's a BigUint64Array
, JS only supports 32 bits:
Bitwise operators treat their operands as a sequence of 32 bits
...
The operands of all bitwise operators are converted to...32-bit integers
For MongoDB earlier than 2.6, the command to add a root user is addUser
(e.g.)
db.addUser({user:'admin',pwd:'<password>',roles:["root"]})
While you can do OO in C (e.g. by adding a theType *this
first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).
I would suggest at least looking at a re-design to compare how this would work out.
Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?
def someFunc(a, b, c):
params = locals()
for _item in params:
print type(params[_item]), _item, params[_item]
Demo:
>> someFunc(1, 'asd', 1.0)
>> <type 'int'> a 1
>> <type 'float'> c 1.0
>> <type 'str'> b asd
more about locals()
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
Note that the suggested solution of using /dev/urandom did work the first time for me but didn't work always after that.
DBA at my firm switched of 'SQL* net banners' and that fixed it permanently for me with or without the above.
I don't know what 'SQL* net banners' are, but am hoping by putting this information here that if you have(are) a DBA he(you) would know what to do.
Similarly I did for long:
myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;
var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
var imgsrc = jQuery('.MulImage')[i];
var CurrentImgSrc = imgsrc.src;
img = jQuery('<img class="dynamic" style="width:100%;">');
img.attr('src', CurrentImgSrc);
jQuery('.YourDivClass').append(img);
}
Encoding.GetString Method (Byte[]) convert bytes to a string.
When overridden in a derived class, decodes all the bytes in the specified byte array into a string.
Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)
Syntax
public virtual string GetString(byte[] bytes)
Parameters
bytes
Type: System.Byte[]
The byte array containing the sequence of bytes to decode.
Return Value
Type: System.String
A String containing the results of decoding the specified sequence of bytes.
Exceptions
ArgumentException - The byte array contains invalid Unicode code points.
ArgumentNullException - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.
Remarks
If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.
See the Remarks under Encoding.GetChars for more discussion of decoding techniques and considerations.
dummy.xml (drawable should be of very less size. i have taken 24dp)
<?xml version="1.0" encoding="utf-8"?>
<layer-list android:opacity="transparent" xmlns:android="http://schemas.android.com/apk/res/android">
<item android:width="100dp" android:gravity="right" android:start="300dp">
<bitmap android:src="@drawable/down_button_dummy_dummy" android:gravity="center"/>
</item>
</layer-list>
layout file snippet
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardElevation="5dp"
>
<Spinner
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@drawable/dummy">
</Spinner>
</android.support.v7.widget.CardView>
The JOIN
statements are also part of the FROM
clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM
. See http://www.postgresql.org/docs/9.1/static/sql-select.html .
So the direct solution to your problem is:
SELECT something
FROM
master as parent LEFT JOIN second as parentdata
ON parent.secondary_id = parentdata.id,
master as child LEFT JOIN second as childdata
ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'
A better option would be to only use JOIN
's, as it has already been suggested.